init: init refactor
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
package svc
|
||||
|
||||
import (
|
||||
"sundynix-micro-go/app/user/model"
|
||||
"sundynix-micro-go/app/user/rpc/internal/config"
|
||||
"sundynix-micro-go/common/utils/jwt"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type ServiceContext struct {
|
||||
Config config.Config
|
||||
DB *gorm.DB
|
||||
Redis *redis.Client
|
||||
JWT *jwt.JWT
|
||||
}
|
||||
|
||||
func NewServiceContext(c config.Config) *ServiceContext {
|
||||
// 初始化GORM
|
||||
db, err := gorm.Open(mysql.Open(c.DB.DataSource), &gorm.Config{})
|
||||
if err != nil {
|
||||
logx.Errorf("连接数据库失败: %v", err)
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// 自动迁移
|
||||
if err := db.AutoMigrate(&model.SundynixUser{}, &model.SundynixUserRole{}); err != nil {
|
||||
logx.Errorf("数据库迁移失败: %v", err)
|
||||
}
|
||||
|
||||
// 初始化Redis
|
||||
var rdb *redis.Client
|
||||
if len(c.Cache) > 0 {
|
||||
rdb = redis.NewClient(&redis.Options{
|
||||
Addr: c.Cache[0].Host,
|
||||
Password: c.Cache[0].Pass,
|
||||
})
|
||||
}
|
||||
|
||||
// 初始化JWT
|
||||
jwtUtil := jwt.NewJWT(c.JwtAuth.AccessSecret)
|
||||
|
||||
return &ServiceContext{
|
||||
Config: c,
|
||||
DB: db,
|
||||
Redis: rdb,
|
||||
JWT: jwtUtil,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user