Load balance policy

We can indicate a special load balance policy when we create engine group. There are 5 load balances on xorm. They are RandomPolicy, WeightRandomPolicy, RoundRobinPolicy, WeightRoundRobinPolicy and LeastConnPolicy. You can also implement yourself policy according GroupPolicy interface.

  • RandomPolicy
import (
    _ "github.com/lib/pq"
    "github.com/xormplus/xorm"
)

var eg *xorm.EngineGroup

func main() {
	conns := []string{
		"postgres://postgres:root@localhost:5432/test?sslmode=disable;",
		"postgres://postgres:root@localhost:5432/test1?sslmode=disable;",
		"postgres://postgres:root@localhost:5432/test2?sslmode=disable",
	}
    
    var err error
	eg, err = xorm.NewEngineGroup("postgres", conns, xorm.RandomPolicy())
}
  • WeightRandomPolicy
import (
    _ "github.com/lib/pq"
    "github.com/xormplus/xorm"
)

var eg *xorm.EngineGroup

func main() {
    conns := []string{
		"postgres://postgres:root@localhost:5432/test?sslmode=disable;",
		"postgres://postgres:root@localhost:5432/test1?sslmode=disable;",
		"postgres://postgres:root@localhost:5432/test2?sslmode=disable",
	}
    
    var err error
    //此时设置的test1数据库和test2数据库的随机访问权重为2和3
	eg, err = xorm.NewEngineGroup("postgres", conns, xorm.WeightRandomPolicy([]int{2, 3}))
}
  • RoundRobinPolicy
import (
    _ "github.com/lib/pq"
    "github.com/xormplus/xorm"
)

var eg *xorm.EngineGroup

func main() {
    conns := []string{
		"postgres://postgres:root@localhost:5432/test?sslmode=disable;",
		"postgres://postgres:root@localhost:5432/test1?sslmode=disable;",
		"postgres://postgres:root@localhost:5432/test2?sslmode=disable",
	}
    
    var err error
	eg, err = xorm.NewEngineGroup("postgres", conns, xorm.RoundRobinPolicy())
}
  • WeightRoundRobinPolicy
import (
    _ "github.com/lib/pq"
    "github.com/xormplus/xorm"
)

var eg *xorm.EngineGroup

func main() {
    conns := []string{
		"postgres://postgres:root@localhost:5432/test?sslmode=disable;",
		"postgres://postgres:root@localhost:5432/test1?sslmode=disable;",
		"postgres://postgres:root@localhost:5432/test2?sslmode=disable",
	}
    
    var err error
    //此时设置的test1数据库和test2数据库的轮询访问权重为2和3
	eg, err = xorm.NewEngineGroup("postgres", conns, xorm.WeightRoundRobinPolicy([]int{2, 3}))
}
  • LeastConnPolicy
import (
    _ "github.com/lib/pq"
    "github.com/xormplus/xorm"
)

var eg *xorm.EngineGroup

func main() {
    conns := []string{
		"postgres://postgres:root@localhost:5432/test?sslmode=disable;",
		"postgres://postgres:root@localhost:5432/test1?sslmode=disable;",
		"postgres://postgres:root@localhost:5432/test2?sslmode=disable",
	}
    
    var err error
	eg, err = xorm.NewEngineGroup("postgres", conns, xorm.LeastConnPolicy())
}
  • Customerize Policy

You can also implement yourself policy according GroupPolicy interface.

type GroupPolicy interface {
	Slave(*EngineGroup) *Engine
}