44 lines
908 B
Go
44 lines
908 B
Go
|
package storage
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"github.com/go-redis/redis/v9"
|
||
|
"github.com/spf13/viper"
|
||
|
)
|
||
|
|
||
|
type RedisHandler struct {
|
||
|
client *redis.Client
|
||
|
}
|
||
|
|
||
|
func NewRedisHandler(cfg *viper.Viper) (*RedisHandler, error) {
|
||
|
redisClient := redis.NewClient(&redis.Options{
|
||
|
Addr: cfg.GetString("storage.kv.redis.addr"),
|
||
|
DB: cfg.GetInt("storage.kv.redis.db"),
|
||
|
})
|
||
|
|
||
|
_, err := redisClient.Ping(context.Background()).Result()
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
return &RedisHandler{
|
||
|
client: redisClient,
|
||
|
}, nil
|
||
|
}
|
||
|
|
||
|
func (rh *RedisHandler) Put(k string, v any) error {
|
||
|
return rh.client.Set(context.Background(), k, v, 0).Err()
|
||
|
}
|
||
|
|
||
|
func (rh *RedisHandler) Get(k string) (any, error) {
|
||
|
value, err := rh.client.Get(context.Background(), k).Result()
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
return value, nil
|
||
|
}
|
||
|
|
||
|
func (rh *RedisHandler) Delete(k string) error {
|
||
|
return rh.client.Del(context.Background(), k).Err()
|
||
|
}
|