共享数据库连接



首先我读了这篇文章:https://www.alexedwards.net/blog/organising-database-access

基本上所有的文章都假设在repository结构中存储db连接。

但假设存在这种情况:我们有两个仓库也有一些手柄。在这个句柄中,我们必须从第一个存储库中读取一些模型。然后创建另一个模型并插入到第二个存储库中。我们必须做交易。

如果我们在每个存储库中存储db连接:在第一个存储库中我们开始事务,然后我们不能在第二个存储库中使用此事务。

我考虑了这些解决方案:1 .

func (self *handles) SomeHandle(ctx context.Context) {
dbConnection := self.acquireConnectionFromPool();
dbConnection.beginTransaction();
// skip errors checking
model := self.repositoryOne.get(dbConnection);
// create new model
self.repositoryTwo.save(dbConnection, newModel);
dbConnection.commit();
}
  • func (self *handles) SomeHandle(ctx context.Context) {
    dbConnection := self.acquireConnectionFromPool();
    dbConnection.beginTransaction();
    ctxDb := context.WithValue(ctx, "db", dbConnection)
    // skip errors checking
    model := self.repositoryOne.get(ctxDb);
    // create new model
    self.repositoryTwo.save(ctxDb, newModel);
    dbConnection.commit();
    }
    

    哪个解决方案更好?

    sql.DB不仅仅是与数据库的连接。它通过根据需要创建/池化连接,从您那里抽象出连接处理。在存储库的任何地方重用一个sql.DB是安全的。这个结论可以从文档中得出:

    SetConnMaxIdleTime设置连接空闲的最大时间。

    以上定义足以说明sql.DB不是一个连接,而是一个接口,它通过抽象出驱动程序/连接实现来提供对数据库的通用访问。

    最新更新