// Use Write Mode: read user from sources `db1` db.Clauses(dbresolver.Write).First(&user)
// Specify Resolver: read user from `secondary`'s replicas: db8 db.Clauses(dbresolver.Use("secondary")).First(&user)
// Specify Resolver and Write Mode: read user from `secondary`'s sources: db6 or db7 db.Clauses(dbresolver.Use("secondary"), dbresolver.Write).First(&user)
事务
使用事务时,DBResolver 将继续使用该事务,并且不会根据配置切换到数据源/副本
但是您可以在启动事务之前指定要使用的数据库,例如
// Start transaction based on default replicas db tx := db.Clauses(dbresolver.Read).Begin()
// Start transaction based on default sources db tx := db.Clauses(dbresolver.Write).Begin()
// Start transaction based on `secondary`'s sources tx := db.Clauses(dbresolver.Use("secondary"), dbresolver.Write).Begin()
负载均衡
GORM 支持基于策略的负载均衡数据源/副本,策略应该是实现以下接口的结构体
type Policy interface { Resolve([]gorm.ConnPool) gorm.ConnPool }