gpt4 book ai didi

mysql - 如何锁定 MySQL 行并稍后在应用程序上下文中释放

转载 作者:行者123 更新时间:2023-11-30 22:58:43 25 4
gpt4 key购买 nike

我非常了解 SELECT ... FOR UPDATE 方法,但它在稍后通过相同连接更新时确实有效。但是放在应用程序上下文中,情况并不多,因为数据库管理器使用连接池。我想从数据库中获取记录,它们在下面的 Controller 中被锁定,在没有其他 Controller 可以读取或更新它们的情况下处理它们,并在完成工作后更新它们并释放锁。如何做到这一点?

我正在使用 Spring JDBCTemplate 并具有以下几个类:

ItemDao:

@Service
public class ItemDao extends AppDao {

// this is supposed to lock the row
public UserItems getItemsForUpdate(long userId) {
return jdbcTemplate.queryForObject("select * from tbl_items where ownerId = ?", new UserItemsRowMapper(), userId);
}

public void updateItems(UserItems items) {

try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(items);
oos.close();
byte[] data = baos.toByteArray();

jdbcTemplate.update("update tbl_items set data = ? where id = ?", new Object[] { data, items.getId() });
} catch (Exception e) {
logger.error(e);
}
}

}

Web 端点处理程序:

@Controller
public class EnergyFillHandler extends BaseItemsUpdatedHandler<EnergyFillRequest> {

@RequestMapping(value="/energyFill", method=RequestMethod.POST)
public @ResponseBody List<BaseResponse> handle(@RequestBody EnergyFillRequest json) {

UserItems items = itemDao.getItems(u.getId());

... do something; if someone else calls getItems
he needs to be blocked at this point

itemDao.updateItems(userItems);

... items are now released and anyone can read and obtain lock on them
}
}

最佳答案

您的问题似乎是 readers-writers problem 的一个特点扩展到数据库中的事务。我会创建一个 SQL 事务类,它主要负责数据库的 CRUD 操作。然后我会有一个标志,它可以以与互斥锁非常相似的方式锁定和释放,这样你就可以确保没有两个并发进程在它们的关键部分(执行 UPDATE 或 INSERT 到 DB)在同时。

我也相信有一个 readers-writers lock它专门处理控制对共享资源的访问,您可能会感兴趣。

如有任何问题,请告诉我!

关于mysql - 如何锁定 MySQL 行并稍后在应用程序上下文中释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25039536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com