5.go-zero集成gorm 和 go-redis
-
安装gorm相关依赖
go get -u gorm.io/gormgo get -u gorm.io/driver/mysql -
编写配置文件

-
编写model加载配置

- 在main中加载配置文件
var configFile = flag.String("f", "etc/auth.yaml", "the config file")func main() {flag.Parse()var c config.Configconf.MustLoad(*configFile, &c)....
}
InitGorm连接MySQL

ServiceContext中给DB赋值
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2package svcimport ("im-server/core""im-server/im_auth/auth_api/internal/config""gorm.io/gorm"
)type ServiceContext struct {Config config.ConfigDB *gorm.DB
}func NewServiceContext(c config.Config) *ServiceContext {return &ServiceContext{Config: c,DB: core.InitGorm(c.MySql.DataSource),}
}
如法炮制,我们下面开始集成 go-redis
- 安装依赖
github.com/redis/go-redis@upgrade
2.在yaml配置文件中增加redis相关配置
Name: auth
Host: 0.0.0.0
Port: 8889
MySql:DataSource: root:a12345678@tcp(127.0.0.1:3306)/my_qq?charset=utf8mb4&parseTime=True&loc=Local
Redis:Host: 127.0.0.1Port: 6379Password: ""
- 修改config文件
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2package configimport "github.com/zeromicro/go-zero/rest"type Config struct {rest.RestConfMySql struct {DataSource string}Redis struct {Host stringPort intPassword string}
}
package coreimport ("fmt""github.com/redis/go-redis"
)func InitRedis(host string, port int) *redis.Client {rdb := redis.NewClient(&redis.Options{Addr: fmt.Sprintf("%s:%d", host, port),Password: "", // No password setDB: 0, // Use default DB})return rdb
}
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2package svcimport ("github.com/redis/go-redis""im-server/core""im-server/im_auth/auth_api/internal/config""gorm.io/gorm"
)type ServiceContext struct {Config config.ConfigDB *gorm.DBRedis *redis.Client
}func NewServiceContext(c config.Config) *ServiceContext {return &ServiceContext{Config: c,DB: core.InitGorm(c.MySql.DataSource),Redis: core.InitRedis(c.Redis.Host, c.Redis.Port),}
}