1
\$\begingroup\$

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
}
\$\endgroup\$
  • \$\begingroup\$ Singletons are usually to be avoided. The thing to ask yourself is: am I making life harder on myself WRT unit testing.. with singletons, the answer more often than not is yes. There's also a chance that 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 a sync.Once makes reconnecting a lot harder in cases like that. Also Redis embeds Client, both fields are exported, what happens if someone accidentally assigns nil? \$\endgroup\$ – Elias Van Ootegem Jul 1 at 14:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.