himbot/lib/redis.go

56 lines
985 B
Go
Raw Normal View History

2023-12-27 12:47:14 -07:00
package lib
import (
"context"
"os"
"time"
"github.com/redis/go-redis/v9"
)
2023-12-27 15:02:23 -07:00
var redis_host = os.Getenv("REDIS_HOST")
var redis_password = os.Getenv("REDIS_PASSWORD")
2023-12-27 15:05:26 -07:00
var rdb = redis.NewClient(&redis.Options{
Addr: redis_host,
Password: redis_password,
DB: 0,
})
2023-12-27 12:47:14 -07:00
func SetCache(key string, value string, ttlMinutes int) bool {
2023-12-27 15:02:23 -07:00
println("Setting the Cache")
2023-12-27 12:47:14 -07:00
rdb := redis.NewClient(&redis.Options{
Addr: redis_host,
Password: redis_password,
DB: 0,
})
if rdb == nil {
panic("Failed to create Redis client")
}
2023-12-27 12:47:14 -07:00
err := rdb.Set(context.Background(), key, value, time.Minute*time.Duration(ttlMinutes)).Err()
if err != nil {
panic(err)
}
2023-12-27 12:47:14 -07:00
return err != nil
}
func GetCache(key string) string {
2023-12-27 15:02:23 -07:00
println("Fetching From Cache")
2023-12-27 15:05:26 -07:00
if rdb == nil {
panic("Failed to create Redis client")
}
2023-12-27 12:47:14 -07:00
val, err := rdb.Get(context.Background(), key).Result()
2023-12-27 12:47:14 -07:00
if err != nil {
2023-12-27 15:02:23 -07:00
println("Cache Miss")
2023-12-27 12:47:14 -07:00
return "nil"
}
2023-12-27 15:02:23 -07:00
println("Cache Hit")
2023-12-27 12:47:14 -07:00
return val
}