最近在倒騰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();
}