【问题标题】:Neo4j: explicit pessimistic locking via Java API or CypherNeo4j:通过 Java API 或 Cypher 进行显式悲观锁定
【发布时间】:2019-10-26 16:07:12
【问题描述】:

有没有办法通过 Neo4J Java API 或 Cypher 手动获取特定节点集上的写锁?

examples in documentation,但仅适用于嵌入式 Neo4j 版本。标准JavaTransaction接口不包含此类方法:https://neo4j.com/docs/api/java-driver/current/org/neo4j/driver/v1/Transaction.html

我也找不到通过 Cypher 的方法。

【问题讨论】:

  • 您的问题解决了吗?也许你可以分享一些代码?

标签: java neo4j locking neo4j-driver


【解决方案1】:

您可以通过写入节点来获取写锁,例如通过设置或删除属性。我认为这在删除不存在的属性时也有效。

如果您安装了APOC Procedures,您可以调用apoc.lock.nodes() 过程,将要锁定的节点列表传递给它。

【讨论】:

  • 它对我有用,谢谢。棘手的部分是你需要像 transaction.run(...).consume() 一样来阻塞线程,因为惰性事务 API
  • @silent-box 所以你改变了一个节点来获取锁?
【解决方案2】:

为了扩展@InverseFalcon的答案,这里是一个通过写入节点的写锁的例子:

@Test
public void testPessimisticLocking() throws InterruptedException {
    txn.execute(status -> {
        session.query("CREATE (n:Lock {uuid:'test'})", Map.of(), false);
        return null;
    });

    ExecutorService executor = Executors.newFixedThreadPool(2);
    Runnable task = () -> {
        LOG.debug("Starting task");

        txn.execute(status -> {
            long time = System.nanoTime();
            LOG.debug("Locking node with time={}", time);
            session.query("MATCH (n:Lock {uuid:'test'}) SET n.time = {0}", Map.of("0", time), false);

            LOG.debug("Query done, waiting some time...");
            try {
                Thread.sleep(5000);
            }
            catch (InterruptedException e) {
                LOG.warn("Interrupted", e);
            }
            LOG.debug("Waiting done");

            return null;
        });

        LOG.debug("Finished task");
    };

    for (int i = 0; i < 2; i++) {
        executor.execute(task);
    }

    executor.shutdown();
    executor.awaitTermination(20, TimeUnit.MINUTES);
}

测试创建一个标签为“Lock”的节点。它并行启动两个任务,试图获取节点上的写锁。一旦获得锁(模拟工作负载),每个任务在事务中等待 5 秒。调试输出为:

2019-10-26 09:47:09,502 [pool-3-thread-1] DEBUG - Starting task
2019-10-26 09:47:09,508 [pool-3-thread-1] DEBUG - Locking node with time=82297334790500
2019-10-26 09:47:09,513 [pool-3-thread-2] DEBUG - Starting task
2019-10-26 09:47:09,515 [pool-3-thread-2] DEBUG - Locking node with time=82297342219000
2019-10-26 09:47:09,605 [pool-3-thread-2] DEBUG - Query done, waiting some time...
2019-10-26 09:47:14,627 [pool-3-thread-2] DEBUG - Waiting done
2019-10-26 09:47:14,643 [pool-3-thread-1] DEBUG - Query done, waiting some time...
2019-10-26 09:47:14,645 [pool-3-thread-2] DEBUG - Finished task
2019-10-26 09:47:19,643 [pool-3-thread-1] DEBUG - Waiting done
2019-10-26 09:47:19,841 [pool-3-thread-1] DEBUG - Finished task

在日志中,您可以看到一个任务在另一个任务完成事务时正在获取锁。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    • 2014-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多