44 lines
965 B
Go
44 lines
965 B
Go
package cache
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
type redisCache struct {
|
|
client *redis.Client
|
|
}
|
|
|
|
// NewRedisCache creates a new instance of Redis cache implementing Cache interface
|
|
func NewRedisCache(addr, password string, db int) (Cache, error) {
|
|
rdb := redis.NewClient(&redis.Options{
|
|
Addr: addr,
|
|
Password: password,
|
|
DB: db,
|
|
})
|
|
|
|
if err := rdb.Ping(context.Background()).Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &redisCache{client: rdb}, nil
|
|
}
|
|
|
|
func (c *redisCache) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error {
|
|
return c.client.Set(ctx, key, value, expiration).Err()
|
|
}
|
|
|
|
func (c *redisCache) Get(ctx context.Context, key string) (string, error) {
|
|
return c.client.Get(ctx, key).Result()
|
|
}
|
|
|
|
func (c *redisCache) Del(ctx context.Context, key string) error {
|
|
return c.client.Del(ctx, key).Err()
|
|
}
|
|
|
|
func (c *redisCache) Close() error {
|
|
return c.client.Close()
|
|
}
|