我有一个要求:
- 跟踪 neo4j 更改并对更改的数据执行异步操作。
- 将异步过程的结果存储回单独节点中的 Neo。
对于第 1 步,我实现了 TransactionEventHandler 并将其在服务器插件中注册为
public class MyPlugin extends ServerPlugin{
@Name( "track_change" )
@Description( "Track Neo4j changes")
@PluginTarget( GraphDatabaseService.class )
public void registerEventHandler( @Source GraphDatabaseService graphDb ){
graphDb.registerTransactionEventHandler(new MyTransactionEventHandler());
}
}
这工作得很好。现在,对于步骤 2,我想在 MyTransactionEventHandler 中编写嵌入代码:
private void saveStatus(String status) {
Transaction tx = graphDb.beginTx();
try
{
Label label = DynamicLabel.label("Status");
Node requestNode = graphDb.createNode(label);
requestNode.setProperty(STATUS, status);
tx.success();
}catch(Exception e){
tx.failure();
logger.severe(e.getMessage());
}finally{
tx.close();
}
}
为此,我需要在处理程序中使用 GraphDatabaseService 的实例。因此,我应该使用 GraphDatabaseFactory 创建一个新的嵌入式实例,还是通过将其传递给处理程序来使用插件中的实例。 Neo4j 文档指出:
The GraphDatabaseService instance can be shared among multiple threads. Note however that you can’t create multiple instances pointing to the same database.
我尝试通过将插件传递给 MyTransactionEventHandler 的构造函数来使用插件中的一个,但有时这会导致创建节点时出错。
java.lang.IllegalStateException: This transaction has already been completed.
这被理解为异步操作可能需要更长的时间。那么在这种情况下创建 GraphDatabaseService 的另一个实例是否可以?如果没有,那么推荐的方法是什么。
感谢任何帮助。
最佳答案
异常到底出现在哪个 tx-event-handler 方法中? 请分享完整的方法/代码。而且你的 tx 上没有 close() 。
此外,您应该在生命周期中注册 tx 处理程序,而不是在 http 方法调用中。
您不会创建 GraphDatabaseService 的新实例,它只是传递给您。
关于java - Neo4j 插件中 GraphDatabaseService 的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31645994/