cic-custodial/pkg/redis/pool.go

48 lines
938 B
Go
Raw Normal View History

2022-11-30 10:51:24 +01:00
package redis
import (
"context"
"time"
"github.com/go-redis/redis/v8"
)
type RedisPoolOpts struct {
2023-02-17 09:43:20 +01:00
DSN string
2022-11-30 10:51:24 +01:00
MinIdleConns int
}
type RedisPool struct {
Client *redis.Client
}
2023-02-17 09:43:20 +01:00
// NewRedisPool creates a reusable connection across the cic-custodial componenent.
// Note: Each db namespace requires its own connection pool.
func NewRedisPool(ctx context.Context, o RedisPoolOpts) (*RedisPool, error) {
2022-11-30 10:51:24 +01:00
redisOpts, err := redis.ParseURL(o.DSN)
if err != nil {
return nil, err
}
redisOpts.MinIdleConns = o.MinIdleConns
redisClient := redis.NewClient(redisOpts)
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
2022-11-30 10:51:24 +01:00
defer cancel()
_, err = redisClient.Ping(ctx).Result()
if err != nil {
return nil, err
}
return &RedisPool{
Client: redisClient,
}, nil
}
2023-02-17 09:43:20 +01:00
// Interface adapter for asynq to resuse the same Redis connection pool.
2022-11-30 10:51:24 +01:00
func (r *RedisPool) MakeRedisClient() interface{} {
return r.Client
}