relynolli-server/internal/redis.go

45 lines
1018 B
Go
Raw Permalink 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-26 02:21:35 +03:00
cacheStore *persistence.RedisStore
2024-03-15 21:27:45 +03:00
)
type Cache interface {
}
2024-03-26 02:21:35 +03:00
func InitRedis() *redis.Client {
2024-03-21 23:44:50 +03:00
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")
}
2024-03-26 02:21:35 +03:00
redisInstance = redis.NewClient(&redis.Options{Addr: os.Getenv("REDIS_ADDRESS"), Password: os.Getenv("REDIS_PASSWORD"), DB: redis_db_num, Username: os.Getenv("REDIS_USERNAME")})
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
2024-03-26 02:21:35 +03:00
func InitCacheStore() *persistence.RedisStore {
2024-03-21 23:44:50 +03:00
if cacheStore == nil {
2024-03-26 02:21:35 +03:00
cacheStore = persistence.NewRedisCache(os.Getenv("REDIS_ADDRESS"), os.Getenv("REDIS_PASSWORD"), 15*time.Minute)
2024-03-21 23:44:50 +03:00
}
return cacheStore
}