pcm-coordinator/rpc/internal/svc/servicecontext.go

66 lines
1.8 KiB
Go
Raw 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.

/*
Copyright (c) [2023] [pcm]
[pcm-coordinator] is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPaRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
*/
package svc
import (
"github.com/go-redis/redis/v8"
_ "github.com/go-sql-driver/mysql"
"github.com/robfig/cron/v3"
"github.com/zeromicro/go-zero/core/logx"
"gitlink.org.cn/jcce-pcm/pcm-coordinator/pkg/utils"
"gitlink.org.cn/jcce-pcm/pcm-coordinator/rpc/internal/config"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
)
type ServiceContext struct {
Config config.Config
DbEngin *gorm.DB
Cron *cron.Cron
RedisClient *redis.Client
}
func NewServiceContext(c config.Config) *ServiceContext {
//启动Gorm支持
dbEngin, err := gorm.Open(mysql.Open(c.DB.DataSource), &gorm.Config{
NamingStrategy: schema.NamingStrategy{
SingularTable: true, // 使用单数表名,启用该选项,此时,`User` 的表名应该是 `t_user`
},
Logger: logger.Default.LogMode(logger.Warn),
})
if err != nil {
logx.Error("gorm初始化错误", err.Error())
panic(err)
}
//添加snowflake支持
err = utils.InitSnowflake(c.SnowflakeConf.MachineId)
if err != nil {
logx.Errorf("InitSnowflake err: ", err)
panic("InitSnowflake err")
}
return &ServiceContext{
Cron: cron.New(cron.WithSeconds()),
Config: c,
DbEngin: dbEngin,
RedisClient: redis.NewClient(&redis.Options{
Addr: c.RedisConf.Host,
Password: c.RedisConf.Pass,
DB: 0, // use default DB
}),
}
}