【问题标题】:How do define read replicas in gorm postgresql如何在 gorm postgresql 中定义只读副本
【发布时间】:2019-10-06 02:21:32
【问题描述】:

我在我的应用服务器中使用 golang 并使用 gorm 作为 ORM。我使用 postgresql 作为谷歌云 sql 中的数据库。

我为应用服务器正在使用的 postgres 创建了 2 个只读副本。

以前,我使用 node.js 和 sequelize,在那里,我可以将只读副本定义为

    read: [
      { host: '8.8.8.8', username: 'anotherusernamethanroot', password: 'lolcats!' },
      { host: 'localhost', username: 'root', password: null }
    ],
    write: { host: 'localhost', username: 'root', password: null }
  },

但是对于 gorm,我没有看到任何方法可以做到这一点(在文档中)。

那么,有没有一种方法可以定义只读副本并由 gorm 处理。如果不是,此用例的最佳做法是什么?

【问题讨论】:

  • 有什么办法吗?

标签: postgresql go go-gorm


【解决方案1】:

现在 Gorm V2 已经发布,您可以将 dbresolver 插件用于此用例。复制您作为示例提供的内容如下所示:

import (
  "gorm.io/gorm"
  "gorm.io/plugin/dbresolver"
  "gorm.io/driver/postgres"
)

db, err := gorm.Open(postgres.Open("host=localhost user=root"), &gorm.Config{})

db.Use(dbresolver.Register(dbresolver.Config{
    Replicas: []gorm.Dialector{
        postgres.Open("host=8.8.8.8 user=anotherusernamethanroot password=lolcats!"), 
        postgres.Open("host=localhost user=root"),
    },
    Policy: dbresolver.RandomPolicy{},
})

查看文档:https://gorm.io/docs/dbresolver.html

【讨论】:

    猜你喜欢
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    • 2018-09-17
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    • 2017-08-13
    相关资源
    最近更新 更多