neo4j自动关闭连接

class CypherExecutor implements AutoCloseable {

    private final Driver driver;

    public CypherExecutor(String uri, String username, String password) {
        this.driver = GraphDatabase.driver(uri, AuthTokens.basic(username, password))
    }

    public <T> List<T> readCyphers(String cypher, Function<Record, T> mapper) {
        try (Session session = driver.session()) {
            Result result = session.run(cypher);
            return result.list(mapper);
        }
    }

    @Override
    public void close() throws Exception {
        driver.close();
    }
}

 

 

public class Neo4jSession implements Closeable {



    @Autowired
    private Driver driver;

    /**
     * 查询遇到异常时进行重试,最多重试三次
     *
     * @param cql
     * @return
     */
    public List<Record> run(String cql) {
        Result result = null;
        boolean isAvailable;
        int count = 0;
        try (Session session = driver.session()) {
            do {
                try {
                    result = session.run(cql);
                    isAvailable = true;
                } catch (ServiceUnavailableException e) {
                    isAvailable = false;
                    count++;
                    log.error(e.getMessage());
                }
                //失败重试最多3次,避免陷入死循环!
                if (count == 3) {
                    break;
                }
            } while (!isAvailable);
            //返回result必须在session关闭之前,否则读不到result
            if (result != null){
                return result.list();
            }else{
                return Lists.newArrayList();
            }
        }


    }

    @Override
    public void close() throws IOException {
        driver.close();
    }
}

 

posted @ 2023-04-04 10:24  Mars.wang  阅读(143)  评论(0)    收藏  举报