relynolli-server/internal/redis.go

45 lines
979 B
Go
Raw Normal View History

2024-03-15 21:27:45 +03:00
package internal
import (
"context"
"log"
"os"
"strconv"
2024-03-21 23:44:50 +03:00
"time"
"github.com/gin-contrib/cache/persistence"
"github.com/redis/go-redis/v9"
2024-03-15 21:27:45 +03:00
)
var (
redisInstance *redis.Client = nil
2024-03-21 23:44:50 +03:00
cacheStore *persistence.RedisStore
2024-03-15 21:27:45 +03:00
)
type Cache interface {
}
2024-03-21 23:44:50 +03:00
func InitRedis() (*redis.Client) {
2024-03-15 21:27:45 +03:00
if redisInstance == nil {
redis_db_num, err := strconv.Atoi(os.Getenv("REDIS_DATABASE"))
if err != nil {
log.Fatalln("REDIS_DATABASE should be integer")
}
redisInstance = redis.NewClient(&redis.Options{Addr: os.Getenv("REDIS_ADDRESS"), Password: os.Getenv("REDIS_PASSWORD"), DB: redis_db_num})
2024-03-21 23:44:50 +03:00
2024-03-15 21:27:45 +03:00
_, conError := redisInstance.Ping(context.Background()).Result()
if conError != nil {
log.Fatalln("Cannot connect to redis host")
}
}
return redisInstance
}
2024-03-21 23:44:50 +03:00
func InitCacheStore() *persistence.RedisStore{
if cacheStore == nil {
cacheStore = persistence.NewRedisCache(os.Getenv("REDIS_ADDRESS"), os.Getenv("REDIS_PASSWORD"), 15 * time.Minute)
}
return cacheStore
}