pcgamedb/cache/redis.go

82 lines
1.5 KiB
Go
Raw Normal View History

2024-09-24 06:17:11 -04:00
package cache
import (
"context"
"fmt"
"sync"
"time"
2024-11-20 06:09:04 -05:00
"pcgamedb/config"
"pcgamedb/log"
2024-11-15 02:02:45 -05:00
2024-09-24 06:17:11 -04:00
"github.com/redis/go-redis/v9"
)
var cache *redis.Client
var mutx = &sync.RWMutex{}
func connect() {
cache = redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%d", config.Config.Redis.Host, config.Config.Redis.Port),
Password: config.Config.Redis.Password,
DB: config.Config.Redis.DBIndex,
})
err := HealthCheck()
if err != nil {
log.Logger.Panic("Cannot connect to redis")
}
log.Logger.Info("Connected to redis")
}
func CheckConnect() {
mutx.RLock()
if cache != nil {
mutx.RUnlock()
return
}
mutx.RUnlock()
mutx.Lock()
if cache == nil {
connect()
}
mutx.Unlock()
}
func HealthCheck() error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
result, err := cache.Ping(ctx).Result()
if err != nil {
return err
}
if result != "PONG" {
return fmt.Errorf("unexpected response from Redis: %s", result)
}
return nil
}
func Get(key string) (string, bool) {
CheckConnect()
ctx := context.Background()
value, err := cache.Get(ctx, key).Result()
if err != nil {
return "", false
}
return value, true
}
func Set(key string, value interface{}) error {
2024-09-24 06:17:11 -04:00
CheckConnect()
ctx := context.Background()
2024-11-23 23:34:36 -05:00
cmd := cache.Set(ctx, key, value, 0)
2024-09-24 06:17:11 -04:00
return cmd.Err()
}
func SetWithExpire(key string, value interface{}, expire time.Duration) error {
2024-09-24 06:17:11 -04:00
CheckConnect()
ctx := context.Background()
cmd := cache.Set(ctx, key, value, expire)
return cmd.Err()
}