2021-04-21 10:22:09 +08:00
|
|
|
|
package starter
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
2022-07-10 12:14:06 +08:00
|
|
|
|
"context"
|
2021-04-21 10:22:09 +08:00
|
|
|
|
"fmt"
|
2025-04-18 22:07:37 +08:00
|
|
|
|
"mayfly-go/internal/pkg/config"
|
2025-04-23 20:36:32 +08:00
|
|
|
|
"mayfly-go/pkg/cache"
|
2023-09-02 17:24:18 +08:00
|
|
|
|
"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客户端
|
2021-07-28 18:03:19 +08:00
|
|
|
|
redisConf := config.Conf.Redis
|
2023-09-02 17:24:18 +08:00
|
|
|
|
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
|
|
|
|
|
|
})
|
|
|
|
|
|
// 测试连接
|
2022-07-10 12:14:06 +08:00
|
|
|
|
_, 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
|
|
|
|
|
|
}
|