feat: 优化redis日志实例的注入方式

This commit is contained in:
2025-12-31 16:57:25 +08:00
parent 5fa6e8118b
commit 147b12cddf
3 changed files with 29 additions and 23 deletions

View File

@@ -34,6 +34,7 @@ func init() {
lock: &sync.RWMutex{},
instanceTable: make(map[string]*define.ClientInfo),
whiteCommandTable: make(map[string]bool),
logger: zap.NewNop(),
}
}
@@ -64,10 +65,6 @@ func (o *OwnClient) isAllowCommand(command string) bool {
}
// Exec 执行命令
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 11:05 2024/6/19
func (o *OwnClient) Exec(ctx context.Context, instanceFlag string, command consts.RedisCmd, args ...any) *define.RedisResult {
if nil == ctx {
ctx = context.Background()
@@ -97,10 +94,6 @@ func (o *OwnClient) Exec(ctx context.Context, instanceFlag string, command const
defer func() {
res.FinishTime = time.Now().UnixMilli()
res.UsedTime = res.FinishTime - res.StartTime
if nil == o.logger {
// 未注入日志实例
return
}
logDataList := []zap.Field{
zap.Int64("start_time", res.StartTime),
zap.Int64("finish_time", res.FinishTime),
@@ -113,10 +106,25 @@ func (o *OwnClient) Exec(ctx context.Context, instanceFlag string, command const
for _, item := range o.extraLogFieldList {
logDataList = append(logDataList, zap.Any(item, ctx.Value(item)))
}
o.logger.Info(
"Redis命令执行记录",
logDataList...,
)
isError := false
if res.Err != nil && res.Err != redisClient.Nil {
isError = true
}
loggerInstance := o.logger
if nil != instance && nil != instance.Logger {
loggerInstance = instance.Logger
}
if isError {
loggerInstance.Error(
"Redis 命令执行失败",
logDataList...,
)
} else {
loggerInstance.Info(
"Redis 命令执行成功",
logDataList...,
)
}
}()
if instance, res.Err = o.GetRealClientWithError(instanceFlag); nil != res.Err {
return res
@@ -147,10 +155,6 @@ func (o *OwnClient) Exec(ctx context.Context, instanceFlag string, command const
}
// SetCommandWhiteList 设置命令白名单, 空 或者 包含 * 则认为所有命令均允许执行
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 11:02 2024/6/19
func (o *OwnClient) SetCommandWhiteList(commandList []consts.RedisCmd) {
o.lock.Lock()
defer o.lock.Unlock()
@@ -175,13 +179,14 @@ func (o *OwnClient) GetRealClientWithError(instanceFlag string) (*define.ClientI
return instance, nil
}
func (o *OwnClient) AddClient(instanceFlag string, instanceConfig *define.Config) error {
func (o *OwnClient) AddClient(instanceFlag string, logger *zap.Logger, instanceConfig *define.Config) error {
if nil == instanceConfig.Master && !instanceConfig.ReadOnly {
// 不是只读, 则要求 主库配置 和 从库配置都要存在
return errors.New(instanceFlag + " : master config is nil")
}
clientInfo := &define.ClientInfo{
Logger: logger,
ReadOnly: instanceConfig.ReadOnly,
Master: nil,
Slave: nil,
@@ -235,10 +240,6 @@ func (o *OwnClient) GetMockInstance() redismock.ClientMock {
}
// newClient 获取客户端连接
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:12 2024/10/8
func (o *OwnClient) newClient(instanceConfig *define.Options) *redisClient.Client {
if o.mockMode {
// mock模式下, 直接返回mock实例