1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- package cache
- import (
- "context"
- "errors"
- "github.com/go-redis/redis/v8"
- "time"
- )
- type rediscli struct {
- c *redis.Client
- }
- type Options redis.Options
- func (c *rediscli) Set(ctx context.Context, key, val string, t time.Duration) (bool, error) {
- _, err := c.c.Set(ctx, key, val, t).Result()
- if err != nil {
- return false, err
- }
- return true, nil
- }
- func (c *rediscli) Get(ctx context.Context, key string) (string, error) {
- v, err := c.c.Get(ctx, key).Result()
- if err != nil {
- if errors.Is(err, redis.Nil) {
- return "", ErrorCacheNotFound
- }
- return "", err
- }
- return v, nil
- }
- func (c *rediscli) Delete(ctx context.Context, key string) (bool, error) {
- _, err := c.c.Del(ctx, key).Result()
- if err != nil {
- return false, err
- }
- return true, nil
- }
- func NewRedis(o *Options) Cache {
- return &rediscli{c: newRedisClient(o)}
- }
- func newRedisClient(o *Options) *redis.Client {
- redisClient := redis.NewClient((*redis.Options)(o))
- timeout, cancel := context.WithTimeout(context.Background(), 2*time.Second)
- defer cancel()
- _, err := redisClient.Ping(timeout).Result()
- if err != nil {
- panic(err)
- }
- return redisClient
- }
|