直接搜哈代码
1. 重写servicectx
type ServiceContext struct {
Config config.Config
UserDb *DbSplit
}
var SmsObj utils.ISms
var DefaultRedis *redis.Client
func NewServiceContext(c config.Config) *ServiceContext {
config.GlobalConfig = c
initStart()
return &ServiceContext{
Config: c,
UserDb: dbMap[config.DbUser],
}
}
2.读写分离
package svc
import "gorm.io/gorm"
var dbMap map[string]*DbSplit
func initStart() {
dbMap = make(map[string]*DbSplit)
}
func GetDb(key string) *DbSplit {
if v, ok := dbMap[key]; ok {
return v
}
panic("no found this key with db" + key)
}
type DbSplit struct {
readObj *gorm.DB
writeObj *gorm.DB
}
func (sp *DbSplit) Read() *gorm.DB {
if sp.readObj == nil {
return sp.Write()
}
return sp.readObj
}
func (sp *DbSplit) Write() *gorm.DB {
return sp.writeObj
}
func (sp *DbSplit) Save(v interface{}) *gorm.DB {
return sp.Write().Save(v)
}
func (sp *DbSplit) Create(v interface{}) *gorm.DB {
return sp.Write().Create(v)
}
func (sp *DbSplit) Table(v string) *gorm.DB {
return sp.Read().Table(v)
}
func (sp *DbSplit) Model(v interface{}) *gorm.DB {
return sp.Read().Model(v)
}
func NewDbSplit(dsn, dsnRead string, key string) {
db, err := gorm.Open(driver.Open(dsn), &gorm.Config{})
if err != nil {
panic("can't connect to mysql" + err.Error())
}
//db.Set()
sp := &DbSplit{
readObj: db,
writeObj: db,
}
dbGo, _ := db.DB()
dbGo.SetConnMaxLifetime(3600 * time.Second)
dbGo.SetConnMaxIdleTime(20)
dbGo.SetMaxIdleConns(50)
if dsnRead != "" {
db1, err1 := gorm.Open(driver.Open(dsn), &gorm.Config{})
if err1 != nil {
panic("can't connect to mysql" + err1.Error())
}
sp.readObj = db1
}
dbMap[key] = sp
}
3. 使用
3.1 注册hander
func LoginHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.RootUserLoginReq
if err := api_utils.Parse(r, &req); err != nil {
commonHandler.ResponseWriter(w, nil, err)
return
}
l := root_logic.NewRootLoginLogic(r.Context(), svcCtx)
resp, err := l.RootLogin(&req)
commonHandler.ResponseWriter(w, resp, err)
}
}
3.2 service logic 具体逻辑
func NewRootLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RootLoginLogic {
return &RootLoginLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *RootLoginLogic) RootLogin(req *types.RootUserLoginReq) (resp *types.RootUserLoginRes, err error) {
var us user.Users
l.svcCtx.UserDb.Table(user.UsersTableName()).Where("account=?", req.Username).First(&us)
// ......
return &types.RootUserLoginRes{Token: token, User: uis}, nil
}