cic-custodial/pkg/redis/pool.go

53 lines
1.0 KiB
Go
Raw Permalink Normal View History

2022-11-30 10:51:24 +01:00
package redis
import (
"context"
"time"
2023-03-14 16:40:50 +01:00
"github.com/redis/go-redis/v9"
2022-11-30 10:51:24 +01:00
)
const (
systemGlobalLockKey = "system:global_lock"
)
2022-11-30 10:51:24 +01:00
type (
RedisPoolOpts struct {
DSN string
MinIdleConns int
}
RedisPool struct {
Client *redis.Client
}
)
2022-11-30 10:51:24 +01:00
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()
if err := redisClient.SetNX(ctx, systemGlobalLockKey, false, 0).Err(); err != nil {
2022-11-30 10:51:24 +01:00
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
}