使用 Golang 设置 Neo4J

Setting up Neo4J with Golang

我正在为其中一个微服务在实时项目中使用 Neo4j 设置 Go

我浏览了有关设置相同内容的文档,但它没有显示执行相同操作的最佳实践(特别是全局并在整个应用程序中传递会话实例)

我正在做同样的设置,想知道这是否是正确的方法:

// app.go

import ""github.com/neo4j/neo4j-go-driver/neo4j""

type App struct {
    Router *mux.Router
    DB *sqlx.DB
    Neo4j neo4j.Session // setting neo4j session globally for injection
}

// =============================
// Neo4j initialization 
// =============================
    driver, err2 := neo4j.NewDriver(
        neo4jConfig.connstring,
        neo4j.BasicAuth(neo4jConfig.username, neo4jConfig.password, ""),
        func(c *neo4j.Config){
            c.Encrypted = false
        },
    )
    checkForErrors(err2, "Cannot connect to NEO4J")
    defer driver.Close()
    session, err3 := driver.NewSession(neo4j.SessionConfig{})
    a.Neo4j = session //  assigning the session instance

现在这将作为依赖项注入正在执行查询的 repo 包中

example in the readme 表示如下:

// Sessions are short-lived, cheap to create and NOT thread safe. Typically create one or more sessions
// per request in your web application. Make sure to call Close on the session when done.
// For multi-database support, set sessionConfig.DatabaseName to requested database
// Session config will default to write mode, if only reads are to be used configure session for
// read mode.
session := driver.NewSession(neo4j.SessionConfig{})

因此拥有全局 driver 实例不是问题,但您不应使用全局 session 实例,因为它不是线程安全的。