Neo4j 驱动程序在运行

Neo4j Driver in play

我在 play 应用程序中使用 Neo4j java driver

目前我为每个控制器(即每个 http 调用)初始化一个新驱动程序。当可自动关闭的关闭方法运行时,它似乎会阻止整个调用大约两秒钟。 运行 不关闭驱动程序(显然是个坏主意)将我的测试时间从 25 秒减少到 5 秒。

我确实怀疑我以错误的方式使用驱动程序,我想我应该在整个应用程序中使用一个驱动程序,但不知道如何使用。 java Neo4j驱动在play框架中的正确使用方法是什么?

Driver 接口的 Javadoc 声明:

Driver implementations are typically thread-safe, act as a template for Session creation and host a connection pool. All configuration and authentication settings are held immutably by the Driver. Should different settings be required, a new Driver instance should be created.

A driver maintains a connection pool for each remote Neo4j server. Therefore the most efficient way to make use of a Driver is to use the same instance across the application.

因此,一般来说,您应该使用单个 Driver 实例。

共享同一个实例的一种方法是实现一个提供 singleton Driver 实例的工厂 class。这是一个非常基本的线程安全示例:

class DriverFactory {
    private static Driver instance;
    public static synchronized Driver getDriver() {
        if (instance == null) {
            instance = GraphDatabase.driver(...);
        }
        return instance;
    }
}