Total Lines | 66 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | package infrastructures |
||
2 | |||
3 | import ( |
||
4 | "context" |
||
5 | "log/slog" |
||
6 | "sync" |
||
7 | "time" |
||
8 | |||
9 | "github.com/gofiber/fiber/v2/log" |
||
10 | "github.com/memnix/memnix-rest/config" |
||
11 | "github.com/redis/go-redis/extra/redisotel/v9" |
||
12 | "github.com/redis/go-redis/v9" |
||
13 | ) |
||
14 | |||
15 | type RedisManager struct { |
||
16 | client *redis.Client |
||
17 | } |
||
18 | |||
19 | var ( |
||
20 | redisInstance *RedisManager //nolint:gochecknoglobals //Singleton |
||
21 | redisOnce sync.Once //nolint:gochecknoglobals //Singleton |
||
22 | ) |
||
23 | |||
24 | func GetRedisClient() *redis.Client { |
||
25 | return GetRedisManagerInstance().GetRedisClient() |
||
26 | } |
||
27 | |||
28 | func GetRedisManagerInstance() *RedisManager { |
||
29 | redisOnce.Do(func() { |
||
30 | redisInstance = &RedisManager{} |
||
31 | }) |
||
32 | return redisInstance |
||
33 | } |
||
34 | |||
35 | func (r *RedisManager) ConnectRedis(redisConf config.RedisConfig) error { |
||
36 | r.client = r.NewRedisClient(redisConf) |
||
37 | |||
38 | _, err := r.client.Ping(context.Background()).Result() |
||
39 | if err != nil { |
||
40 | return err |
||
41 | } |
||
42 | |||
43 | return nil |
||
44 | } |
||
45 | |||
46 | func (r *RedisManager) CloseRedis() error { |
||
47 | return r.client.Close() |
||
48 | } |
||
49 | |||
50 | func (r *RedisManager) GetRedisClient() *redis.Client { |
||
51 | return r.client |
||
52 | } |
||
53 | |||
54 | func (r *RedisManager) NewRedisClient(redisConf config.RedisConfig) *redis.Client { |
||
55 | client := redis.NewClient(&redis.Options{ |
||
56 | Addr: redisConf.Addr, |
||
57 | MinIdleConns: redisConf.MinIdleConns, |
||
58 | PoolSize: redisConf.PoolSize, |
||
59 | PoolTimeout: time.Duration(redisConf.PoolTimeout) * time.Second, |
||
60 | }) |
||
61 | |||
62 | if err := redisotel.InstrumentTracing(client); err != nil { |
||
63 | log.Error("failed to instrument redis", slog.Any("error", err)) |
||
64 | } |
||
65 | |||
66 | return client |
||
67 | } |
||
68 |