Reputation: 103
I have a requirement to:
For step 1, I implemented TransactionEventHandler and registered it in Server plugin as
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());
}
}
This is working perfectly fine. Now for step 2, I want to write embedded code in MyTransactionEventHandler as
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();
}
}
For this I need an instance of GraphDatabaseService in my handler. So should I create a new embedded instance using GraphDatabaseFactory or use the one from plugin by passing it to handler. Neo4j documentation states that:
The GraphDatabaseService instance can be shared among multiple threads. Note however that you can’t create multiple instances pointing to the same database.
I tried using the one from plugin by passing it to constructor of MyTransactionEventHandler, but sometime this results in error while creating node.
java.lang.IllegalStateException: This transaction has already been completed.
Which is understood as async operation may be taking longer. So is this ok to create another instance of GraphDatabaseService in this case. If not, then what are the recommended way(s) to do this.
Appreciate any help.
Upvotes: 0
Views: 380
Reputation: 41686
Where exactly does the exception appear in which tx-event-handler method? Please share the full method / code. Also you have no close() on your tx.
Also you should register the tx handler in the lifecycle and not in a http method call.
You will not create a new instance of GraphDatabaseService, it is just passed to you.
Upvotes: 1