stay gorm v2 In the version , We can see that read-write separation is supported , The read-write separation is based on master-slave replication , So we need to configure mysql Master-slave replication of
1、 Why master-slave replication is needed ?
In complex business systems , There is such a scene : If there is a sentence sql Statement needs lock table , Resulting in temporary inability to use the read service , Then it will affect the running business . Use master-slave replication , Let the main database be responsible for writing , Read from the library , such , Even if the main database appears to lock the table , The normal operation of the business can also be ensured by reading from the database .
Do hot data backup
More and more business ,I/O Access frequency is too high , A single machine can't satisfy , At this time, do multi library storage , Lower the disk I/O Frequency of visits , Improve the... Of a single machine I/O performance .
2、 What is master-slave replication ?
MySQL Master-slave replication means that data can be copied from one MySQL The database server master node is replicated to one or more slave nodes .
MySQL Asynchronous replication is used by default , In this way, the slave node does not need to visit the master server all the time to update its data , Data can be updated on a remote connection , The slave node can copy all databases or specific databases in the master database , Or a specific watch .
Excerpt from :Gorm Read / write separation
3、 Realization
import (
"gorm.io/gorm"
"gorm.io/plugin/dbresolver"
"gorm.io/driver/mysql"
)
db, err := gorm.Open(mysql.Open("db1_dsn"), &gorm.Config{})
db.Use(dbresolver.Register(dbresolver.Config{
// use `db2` as sources, `db3`, `db4` as replicas
Sources: []gorm.Dialector{mysql.Open("db2_dsn")},
Replicas: []gorm.Dialector{mysql.Open("db3_dsn"), mysql.Open("db4_dsn")},
// sources/replicas load balancing policy
Policy: dbresolver.RandomPolicy{},
}).Register(dbresolver.Config{
// use `db1` as sources (DB's default connection), `db5` as replicas for `User`, `Address`
Replicas: []gorm.Dialector{mysql.Open("db5_dsn")},
}, &User{}, &Address{}).Register(dbresolver.Config{
// use `db6`, `db7` as sources, `db8` as replicas for `orders`, `Product`
Sources: []gorm.Dialector{mysql.Open("db6_dsn"), mysql.Open("db7_dsn")},
Replicas: []gorm.Dialector{mysql.Open("db8_dsn")},
}, "orders", &Product{}, "secondary"))
Reference resources :DBResolver
4、 doubt
read resolver Will read data from the Library , You can only do read operations , Write resolver Directly operate the main library , You can read and write at the same time . But I found that reading resolver Can also write , It is speculated here that master-slave replication may not be enabled , As a result, the master and slave databases are the same , Thus reading and writing resolver Of source The source is the same , So read it reolver You can read or write , In doubt , To be examined .