Recently I have learned about singleton design pattern. I have tried to implement Redis connection following singleton design pattern.
conn/redis.go
package conn
import (
"sync"
"github.com/go-redis/redis"
)
// Redis client
type Redis struct {
*redis.Client
}
var redisInstance *Redis
var once sync.Once
func GetRedis() *Redis {
once.Do(func() {
cfg := config.Redis()
redisInstance = &Redis{
Client: redis.NewClient(&redis.Options{
Addr: cfg.Address,
Password: cfg.Password,
DB: cfg.DB,
}),
}
})
return redisInstance
}
redis.Client
becomes invalid (connection drops, you may need to create a new client - IDK if that's the case here, but some packages work like that). Wrapping everything in async.Once
makes reconnecting a lot harder in cases like that. AlsoRedis
embedsClient
, both fields are exported, what happens if someone accidentally assignsnil
? \$\endgroup\$