\$\begingroup\$
\$\endgroup\$
1
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
}
asked Jun 26, 2019 at 8:48
user104759
You must log in to answer this question.
lang-golang
redis.Clientbecomes 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.Oncemakes reconnecting a lot harder in cases like that. AlsoRedisembedsClient, both fields are exported, what happens if someone accidentally assignsnil? \$\endgroup\$