我如何使用悲观锁实现跳过锁定功能?

问题描述 投票:0回答:1

我想实现跳过锁定。我正在使用PostgreSQL 9.6.17。我正在使用以下代码

@Lock(LockModeType.PESSIMISTIC_WRITE)
@QueryHints({@QueryHint(name = "javax.persistence.lock.timeout", value = "-2")})
@Query("Select d from Demo d where d.id in (?1)")
List<Demo> getElementByIds(List<Long> ids);

我正在通过cmd同时从2个服务进行相同的DB调用(向发出DB调用的两个服务的并行Curl请求)。从1个服务器,我从1 ... 4传递ID,从其他服务器,我从1 ... 7传递ID。但是,如果第一个服务在1 ... 4行上执行了锁定,然后第二个服务不得不等到第一个服务删除了它的锁,但理想情况下,第二个服务应返回第5 ... 7行从第一个服务中,我这样拨打电话:>

List<Long> ids = new ArrayList<>();
    ids.add(1l);
    ids.add(2l);
    ids.add(3l);
    ids.add(4l);
    List<Demo> demos = demoRepo.getElementByIds(ids);
    try{
        Thread.sleep(500);
    } catch (Exception e) {

    }
    logger.info("current time: " + System.currentTimeMillis());

并且从第二个服务中,我这样打电话:

List<Long> ids = new ArrayList<>();
    ids.add(1l);
    ids.add(2l);
    ids.add(3l);
    ids.add(4l);
    ids.add(5l);
    ids.add(6l);
    ids.add(7l);
    try{
        Thread.sleep(100);
    } catch (Exception e) {

    }
    logger.info("current time: " + System.currentTimeMillis());
    List<Demo> demos = demoRepo.getElementByIds(ids);
    logger.info("current time: " + System.currentTimeMillis());

但是在等待另一个服务释放锁之后,两个查询总是返回相同的行。

我正在使用的Spring JPA版本:

<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.2.5.RELEASE</version>

我还在应用程序级别本身尝试过spring.jpa.javax.persistence.lock.timeout = -2,它也无法正常工作。这两种方法似乎都可以像PESSIMISTIC_WRITE一样工作。

请提出如何实现跳过锁定功能的建议。

我想实现跳过锁定。我正在使用PostgreSQL 9.6.17。我正在使用以下代码@Lock(LockModeType.PESSIMISTIC_WRITE)@QueryHints({@ QueryHint(name =“ javax.persistence.lock.timeout”,value = ...

postgresql hibernate spring-boot spring-data-jpa jpa-2.0
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.