c5_labsci/zciyon/dbroute.go
2026-01-27 00:52:00 +08:00

60 lines
1.9 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
=================================================================================
* License: GPL-2.0 license
* Author: 众产® https://ciy.cn/code
* Version: 0.1.0
=================================================================================
多读库路由 NewCiyDBRoute
** 该路由库可能由HAProxy取代
=================================================================================
dbr, err = c.NewCiyDBRoute(dbn[]string, 最大连接数, 空闲连接数, 保活秒) //main初始化
dbr.Takeout() //取出一个负载较低的数据库连接池
=================================================================================
示例:
dbr, err = c.NewCiyDBRoute([]string{"user:pass@tcp(localhost:3306)/dbname"}) //main初始化一直开着程序结束才关
db := dbr.Takeout() //取出一个数据库连接池
=================================================================================
*/
package zciyon
import (
"fmt"
)
// 数据路由,包含多个数据库池路由,取出一个连接池用。
type CiyDBRoute struct {
routes []*CiyMysql
}
// 多台读服务器dsn要求内容一致的互为镜像
func NewCiyDBRoute(dsns []string, maxopenconn int, maxidelconn int, maxlifesec int) (*CiyDBRoute, error) {
dbroute := &CiyDBRoute{}
dbroute.routes = make([]*CiyMysql, 0)
for idx, dsn := range dsns {
dbr, err := NewCiyMysql(dsn, maxopenconn, maxidelconn, maxlifesec)
if err != nil {
return nil, fmt.Errorf("DB[%d]: %v", idx, err)
}
dbr.MonitorHealth(10)
dbroute.routes = append(dbroute.routes, dbr)
}
if len(dbroute.routes) == 0 {
return nil, fmt.Errorf("no dsn")
}
return dbroute, nil
}
// 取出一个相对健康的目标数据库连接池
func (thos *CiyDBRoute) Takeout() CiyMysql {
minhealth := 100000
dbidx := 0
for idx, dbr := range thos.routes {
if dbr.Health < minhealth {
minhealth = dbr.Health
dbidx = idx
}
}
return *thos.routes[dbidx]
}