go-zero 配置文件模版(后续写代码直接照抄即可)
作者:互联网
Name: sms_bot-api
Host: 127.0.0.1
Port: 8888
Database:
Pkg : "./internal/svc"
DriverName: "mysql"
DSN: "root:98123456@tcp(192.168.4.240:3306)/qe?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai"
Logger:
Path: "./tmp/sql.log"
MaxAge: 180
Interval: 2
Redis:
Host: 192.168.4.240:6379
Pass: ""
DB: 0
ExpireTime: 3
go-zero
项目中 svc
目录内容
package svc
import (
"context"
"github.com/go-redis/redis/v8"
_ "github.com/go-sql-driver/mysql"
"github.com/kotlin2018/mbt"
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"io"
"log"
"path"
"sms_bot/internal/config"
"time"
)
// 服务依赖项(比如说: 加载配置文件,数据库连接句柄,自定义全局错误信息)
type ServiceContext struct {
Config config.Config
Redis *redis.Client
}
func NewServiceContext(c config.Config) *ServiceContext {
conf := &mbt.Database{
Pkg: c.Database.Pkg,
DriverName: c.Database.DriverName,
DSN: c.Database.DSN,
Logger: &mbt.Logger{
Path: c.Logger.Path,
MaxAge: c.Logger.MaxAge,
Interval: c.Logger.Interval,
PrintSql: true,
},
}
mbt.New(conf).Register(initMapper()).SetOutPut(initLogger(c.Logger.Path, c.Logger.MaxAge, c.Logger.Interval)).Run()
client := redis.NewClient(&redis.Options{
Addr: c.Redis.Host,
Password: c.Redis.Pass,
DB: c.Redis.DB,
})
_, err := client.Ping(context.Background()).Result()
if err != nil {
log.Fatalln("请配置redis服务")
}
return &ServiceContext{
Config: c,
Redis: client,
}
}
func initMapper() map[interface{}]interface{} {
h := mbt.H{
&TSmsbotDao: &TSmsbot{}, // sms机器人表
&TTaskDao: &TTask{}, // 任务表
&TTaskTypeDao: &TTaskType{}, // 任务类型表
}
return h
}
func initLogger(logFilePath string, maxAge, interval int) io.Writer {
writer, _ := rotatelogs.New(
path.Join(logFilePath+"-%Y-%m-%d.log"), //拼接成log文件名
rotatelogs.WithLinkName(logFilePath),
rotatelogs.WithMaxAge(time.Duration(maxAge)*time.Hour),
rotatelogs.WithRotationTime(time.Duration(interval)*time.Hour),
)
return writer
}
标签:配置文件,rotatelogs,Redis,redis,mbt,zero,go,Logger 来源: https://blog.csdn.net/qq_39297673/article/details/120104696