Create Engine Group
Create Engine Group
XORM supports to create EngineGroup to handle Master/Slave databases. You can invoke xorm.NewEngineGroup
to do that. For example:
import (
_ "github.com/lib/pq"
"xorm.io/xorm"
)
var eg *xorm.EngineGroup
func main() {
conns := []string{
"postgres://postgres:root@localhost:5432/test?sslmode=disable;", // first one is master
"postgres://postgres:root@localhost:5432/test1?sslmode=disable;", // slave
"postgres://postgres:root@localhost:5432/test2?sslmode=disable", // slave
}
var err error
eg, err = xorm.NewEngineGroup("postgres", conns)
}
Or
import (
_ "github.com/lib/pq"
"xorm.io/xorm"
)
var eg *xorm.EngineGroup
func main() {
var err error
master, err := xorm.NewEngine("postgres", "postgres://postgres:root@localhost:5432/test?sslmode=disable")
if err != nil {
return
}
slave1, err := xorm.NewEngine("postgres", "postgres://postgres:root@localhost:5432/test1?sslmode=disable")
if err != nil {
return
}
slave2, err := xorm.NewEngine("postgres", "postgres://postgres:root@localhost:5432/test2?sslmode=disable")
if err != nil {
return
}
slaves := []*xorm.Engine{slave1, slave2}
eg, err = xorm.NewEngineGroup(master, slaves)
}
You can create many engine groups for different databases. Generally, you just need to create only one engine group. EngineGroup
is goroutine safe.
When you want to manually close the engine group, call enginegroup.Close
.
- NewEngineGroup
func NewEngineGroup(args1 interface{}, args2 interface{}, policies ...GroupPolicy) (*EngineGroup, error)
- Master
func (eg *EngineGroup) Master() *Engine
It will return Master database Engine
so that you can operate master only.
- Slave
func (eg *EngineGroup) Slave() *Engine
It will return the current slave engine according the load balance policy.
- Slaves
func (eg *EngineGroup) Slaves() []*Engine
It will return all the slaves.
- GetSlave
func (eg *EngineGroup) GetSlave(i int) *Engine
It will return the slave engine according the index.
- SetPolicy
func (eg *EngineGroup) SetPolicy(policy GroupPolicy) *EngineGroup
It will set a load balance policy.