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:

  1. import (
  2. _ "github.com/lib/pq"
  3. "xorm.io/xorm"
  4. )
  5. var eg *xorm.EngineGroup
  6. func main() {
  7. conns := []string{
  8. "postgres://postgres:[email protected]:5432/test?sslmode=disable;", // first one is master
  9. "postgres://postgres:[email protected]:5432/test1?sslmode=disable;", // slave
  10. "postgres://postgres:[email protected]ocalhost:5432/test2?sslmode=disable", // slave
  11. }
  12. var err error
  13. eg, err = xorm.NewEngineGroup("postgres", conns)
  14. }

Or

  1. import (
  2. _ "github.com/lib/pq"
  3. "xorm.io/xorm"
  4. )
  5. var eg *xorm.EngineGroup
  6. func main() {
  7. var err error
  8. master, err := xorm.NewEngine("postgres", "postgres://postgres:[email protected]:5432/test?sslmode=disable")
  9. if err != nil {
  10. return
  11. }
  12. slave1, err := xorm.NewEngine("postgres", "postgres://postgres:[email protected]:5432/test1?sslmode=disable")
  13. if err != nil {
  14. return
  15. }
  16. slave2, err := xorm.NewEngine("postgres", "postgres://postgres:[email protected]:5432/test2?sslmode=disable")
  17. if err != nil {
  18. return
  19. }
  20. slaves := []*xorm.Engine{slave1, slave2}
  21. eg, err = xorm.NewEngineGroup(master, slaves)
  22. }

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
  1. func NewEngineGroup(args1 interface{}, args2 interface{}, policies ...GroupPolicy) (*EngineGroup, error)
  • Master
  1. func (eg *EngineGroup) Master() *Engine

It will return Master database Engine so that you can operate master only.

  • Slave
  1. func (eg *EngineGroup) Slave() *Engine

It will return the current slave engine according the load balance policy.

  • Slaves
  1. func (eg *EngineGroup) Slaves() []*Engine

It will return all the slaves.

  • GetSlave
  1. func (eg *EngineGroup) GetSlave(i int) *Engine

It will return the slave engine according the index.

  • SetPolicy
  1. func (eg *EngineGroup) SetPolicy(policy GroupPolicy) *EngineGroup

It will set a load balance policy.