gpt4 book ai didi

Spring hibernate 插入竞争条件

转载 作者:行者123 更新时间:2023-11-29 13:34:39 25 4
gpt4 key购买 nike

我目前遇到 Spring Hibernate 的竞争问题(通过服务和 daoImpl 类上的注释进行事务处理)。这是我遇到的:

表格:

  • 设备类型:id(串口),name
  • 设备:id(序列号)、device_identifier、device_type_id、ip_address

注意 device_identifier 和 device_type_id 是唯一的

这是我在多线程进程中的片段:

    if(deviceDao.findByIdentifierAndTypeId(identifier, typeId) == null){
Device newDevice = new Device();
newDevice.setIdentifier(identifier);
newDevice.setTypeId(typeId);
deviceDao.add(newDevice);
}

那么发生的事情是,我有一个通过 websockets 监听设备的服务器(这里可能不是重要的细节),服务器将首先尝试确定该设备是否已经在数据库中,如果没有则创 build 备记录已经找到了。

现在我遇到的问题是服务器可以处理来自设备的多条消息(针对来自设备的每条消息创建一个线程),因此存在竞争条件。

想象一下:

设备A一个接一个发送两条消息:

    Sends hello message              Sends "here is my ip" message
| |
| |
| |
does not see device in DB |
tries to insert does not see device in DB
| tries to insert
Insert completed |
Failed to insert (Unique key constraints not met)

显然第二次插入设备时,唯一约束会导致失败。但我在想,当第一个插入完成时,Spring 可以将其拾起,并且知道当第二个线程再次尝试插入时,它不需要这样做。但是,尽管我尝试了各种传播和隔离模式,但这并没有发生。我一定遗漏了一些非常基本的东西,请指出我如何解决这个问题的正确方向。提前感谢您的回复。如果需要/要求,我会提供更多信息。

最佳答案

这是设计使然的行为。默认情况下,您只会看到已提交的行(READ COMMITTED 隔离级别)。对于外部进程,您可以将未提交的行视为尚未出现在数据库中

最好的解决方案是捕获唯一约束违规并重试(最好有延迟)。您还可以将隔离级别设置为读取未提交,但这可能会产生其他竞争条件,我不建议这样做。

关于 Spring hibernate 插入竞争条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15874802/

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