golib/gcache/adapter_redis.go

53 lines
1.0 KiB
Go
Raw Normal View History

2023-06-15 21:22:51 +08:00
//
// adapter_redis.go
// Copyright (C) 2022 tiglog <me@tiglog.com>
//
// Distributed under terms of the MIT license.
//
package gcache
import (
"context"
"sync"
"time"
"github.com/go-redis/redis/v8"
)
2023-06-15 21:22:51 +08:00
// 使用 redis 服务缓存
type redisCacheAdapter struct {
mu sync.Mutex
redis *redis.Client
}
func NewRedisCacheAdapter(rds *redis.Client) ICacheAdapter {
return &redisCacheAdapter{
redis: rds,
}
}
func (c *redisCacheAdapter) Get(key string, dest interface{}) error {
cmd := c.redis.Get(context.Background(), key)
return cmd.Scan(dest)
}
func (c *redisCacheAdapter) Set(key string, val interface{}, ttl time.Duration) error {
cmd := c.redis.Set(context.Background(), key, val, ttl)
return cmd.Err()
}
func (c *redisCacheAdapter) Has(key string) bool {
cmd := c.redis.Exists(context.Background(), key)
result, _ := cmd.Result()
if result == 1 {
return true
}
return false
}
func (c *redisCacheAdapter) Del(keys ...string) (int64, error) {
cmd := c.redis.Del(context.Background(), keys...)
return cmd.Result()
}