最近在倒腾neo4j,在使用多线程方式往neo4j插入关系数据时,有些线程抛出异常:
Neo.TransientError.Transaction.DeadlockDetected
查了下原因,在创建关系数据时(nodea->nodeb),nodeb(endnode)会被write-lock,当这个节点上了写锁后,其他的线程就会抛出这个异常,解决办法就是让相同的endnode使用同一个线程处理,我这边直接将相同的endnode的相关数据放在了同一个文件,一个线程单独处理一个文件,避免多线程处理统一个endnode
好吧,这事我想简单了,测试一段时间后,还是出现了这个异常,但比之前好很多;为了解决这个问题换了一种方案,添加重试机制,先引入maven坐标
<dependency>
<groupId>com.github.rholder</groupId>
<artifactId>guava-retrying</artifactId>
<version>2.0.0</version>
</dependency>
具体实现如下
public static void executeSql(String sql) throws Exception {
Class.forName("org.neo4j.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:neo4j:http://hadoop:7474?user=neo4j&password=neo4j");
con.setAutoCommit(false);
Statement statement = con.createStatement();
Callable<Integer> task = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
statement.execute(sql);
return 1;
}
};
Retryer<Integer> retryer = RetryerBuilder.<Integer>newBuilder()
.retryIfResult(Predicates.<Integer>isNull())
.retryIfResult(Predicates.equalTo(2))
.retryIfExceptionOfType(Exception.class)
.withStopStrategy(StopStrategies.stopAfterAttempt(5))
.withWaitStrategy(WaitStrategies.fixedWait(300, TimeUnit.MILLISECONDS))
.build();
try {
retryer.call(task);
} catch (ExecutionException e) {
e.printStackTrace();
} catch (RetryException e) {
e.printStackTrace();
}
con.commit();
con.close();
}