Files
mayfly-go/server/internal/pkg/starter/cache.go

48 lines
1.2 KiB
Go
Raw Normal View History

2021-04-21 10:22:09 +08:00
package starter
import (
"context"
2021-04-21 10:22:09 +08:00
"fmt"
"mayfly-go/internal/pkg/config"
2025-04-23 20:36:32 +08:00
"mayfly-go/pkg/cache"
"mayfly-go/pkg/logx"
2022-12-26 20:53:07 +08:00
"mayfly-go/pkg/rediscli"
2021-04-21 10:22:09 +08:00
2023-03-17 09:46:41 +08:00
"github.com/redis/go-redis/v9"
2021-04-21 10:22:09 +08:00
)
2025-04-23 20:36:32 +08:00
// 有配置redis信息则初始化redis。多台机器部署需要使用redis存储验证码、权限、公私钥等信息
func initCache() {
redisCli := connRedis()
if redisCli == nil {
logx.Info("no redis configuration exists, local cache is used")
return
}
logx.Info("redis connection is successful, redis cache is used")
2022-12-26 20:53:07 +08:00
rediscli.SetCli(connRedis())
2025-04-23 20:36:32 +08:00
cache.SetCache(cache.NewRedisCache(redisCli))
2022-01-13 17:06:04 +08:00
}
2022-12-26 20:53:07 +08:00
func connRedis() *redis.Client {
2021-04-21 10:22:09 +08:00
// 设置redis客户端
redisConf := config.Conf.Redis
if redisConf.Host == "" {
// logx.Panic("未找到redis配置信息")
2022-01-13 17:06:04 +08:00
return nil
2021-04-21 10:22:09 +08:00
}
2025-04-23 20:36:32 +08:00
logx.Infof("redis connecting [%s:%d]", redisConf.Host, redisConf.Port)
2021-04-21 10:22:09 +08:00
rdb := redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%d", redisConf.Host, redisConf.Port),
Password: redisConf.Password, // no password set
DB: redisConf.Db, // use default DB
})
// 测试连接
_, e := rdb.Ping(context.TODO()).Result()
2021-04-21 10:22:09 +08:00
if e != nil {
2025-04-23 20:36:32 +08:00
logx.Panicf("redis connection faild! [%s:%d][%s]", redisConf.Host, redisConf.Port, e.Error())
2021-04-21 10:22:09 +08:00
}
return rdb
}