Skip to content

Commit

Permalink
redis db: add default pool config
Browse files Browse the repository at this point in the history
  • Loading branch information
agungdwiprasetyo committed Jan 3, 2024
1 parent e2f8df7 commit 103fb7b
Showing 1 changed file with 32 additions and 5 deletions.
37 changes: 32 additions & 5 deletions config/database/redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,31 @@ package database

import (
"context"
"log"
"time"

"github.com/golangid/candi/cache"
"github.com/golangid/candi/codebase/interfaces"
"github.com/golangid/candi/config/env"
"github.com/golangid/candi/logger"
"github.com/gomodule/redigo/redis"
)

type RedisPoolOption func(pool *redis.Pool)

func RedisPoolOptionSetMaxIdle(count int) RedisPoolOption {
return func(pool *redis.Pool) { pool.MaxIdle = count }
}
func RedisPoolOptionSetMaxActive(count int) RedisPoolOption {
return func(pool *redis.Pool) { pool.MaxActive = count }
}
func RedisPoolOptionSetIdleTimeout(dur time.Duration) RedisPoolOption {
return func(pool *redis.Pool) { pool.IdleTimeout = dur }
}
func RedisPoolOptionSetMaxConnLifetime(dur time.Duration) RedisPoolOption {
return func(pool *redis.Pool) { pool.MaxConnLifetime = dur }
}

type redisInstance struct {
read, write *redis.Pool
cache interfaces.Cache
Expand Down Expand Up @@ -50,31 +68,40 @@ func (m *redisInstance) Disconnect(ctx context.Context) (err error) {

// InitRedis connection from environment:
// REDIS_READ_DSN, REDIS_WRITE_DSN
func InitRedis() interfaces.RedisPool {
func InitRedis(opts ...RedisPoolOption) interfaces.RedisPool {
deferFunc := logger.LogWithDefer("Load Redis connection...")
defer deferFunc()

inst := &redisInstance{
read: ConnectRedis(env.BaseEnv().DbRedisReadDSN),
write: ConnectRedis(env.BaseEnv().DbRedisWriteDSN),
read: ConnectRedis(env.BaseEnv().DbRedisReadDSN, opts...),
write: ConnectRedis(env.BaseEnv().DbRedisWriteDSN, opts...),
}
inst.cache = cache.NewRedisCache(inst.read, inst.write)
return inst
}

// ConnectRedis connect to redis with dsn
func ConnectRedis(dsn string) *redis.Pool {
func ConnectRedis(dsn string, opts ...RedisPoolOption) *redis.Pool {
pool := &redis.Pool{
Dial: func() (redis.Conn, error) {
return redis.DialURL(dsn)
},

// default pool config
MaxIdle: 80,
MaxActive: 500,
IdleTimeout: 20 * time.Minute,
MaxConnLifetime: 1 * time.Hour,
}
for _, opt := range opts {
opt(pool)
}

ping := pool.Get()
defer ping.Close()
_, err := ping.Do("PING")
if err != nil {
panic("redis ping: " + err.Error())
log.Panicf("redis ping: %s", err.Error())
}

return pool
Expand Down

0 comments on commit 103fb7b

Please sign in to comment.