34 lines
764 B
Go
34 lines
764 B
Go
package utils
|
|
|
|
import (
|
|
"context"
|
|
"log"
|
|
"time"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
type Cache struct {
|
|
client redis.UniversalClient
|
|
ttl time.Duration
|
|
prefix string
|
|
}
|
|
|
|
func NewCache(client redis.UniversalClient, ttl time.Duration, prefix string) (*Cache, error) {
|
|
return &Cache{client: client, ttl: ttl, prefix: prefix}, nil
|
|
}
|
|
|
|
func (c *Cache) Add(ctx context.Context, key string, value string) {
|
|
log.Printf("Adding key %s to cache with value %s", key, value)
|
|
c.client.Set(ctx, c.prefix+key, value, c.ttl)
|
|
}
|
|
|
|
func (c *Cache) Get(ctx context.Context, key string) (string, bool) {
|
|
s, err := c.client.Get(ctx, c.prefix+key).Result()
|
|
if err != nil {
|
|
return "", false
|
|
}
|
|
log.Printf("Retrieved key %s from cache with value %s", key, s)
|
|
return s, true
|
|
}
|