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
|
|
|
|
|
2023-06-21 10:52:25 +08:00
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/go-redis/redis/v8"
|
|
|
|
)
|
|
|
|
|
2023-06-15 21:22:51 +08:00
|
|
|
// 使用 redis 服务缓存
|
2023-06-21 10:52:25 +08:00
|
|
|
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()
|
|
|
|
}
|