88 lines
1.7 KiB
Go
88 lines
1.7 KiB
Go
//
|
|
// redis_adapter.go
|
|
// Copyright (C) 2023 tiglog <me@tiglog.com>
|
|
//
|
|
// Distributed under terms of the MIT license.
|
|
//
|
|
|
|
package gcache
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
// Option is a redis option type
|
|
type RCOption func(r *RedisStore)
|
|
|
|
// ClientOptions is an Option type that allows configuring a redis client
|
|
func RCClientOptions(opts *redis.Options) RCOption {
|
|
return func(r *RedisStore) {
|
|
r.client = redis.NewClient(opts)
|
|
}
|
|
}
|
|
|
|
// CacheKeyGenerator allows configuring the cache key generation process
|
|
func RCCacheKeyGenerator(fn KeyFunc) RCOption {
|
|
return func(r *RedisStore) {
|
|
r.keyFn = fn
|
|
}
|
|
}
|
|
|
|
type RedisStore struct {
|
|
client *redis.Client
|
|
|
|
keyFn KeyFunc
|
|
}
|
|
|
|
// New returns a new RedisStore by applying all options passed into it
|
|
// It also sets sensible defaults too
|
|
func NewRedisStore(opts ...RCOption) *RedisStore {
|
|
r := &RedisStore{}
|
|
|
|
for _, opt := range opts {
|
|
opt(r)
|
|
}
|
|
|
|
if r.client == nil {
|
|
panic("需要指定 redis 的连接参数")
|
|
}
|
|
|
|
if r.keyFn == nil {
|
|
r.keyFn = DefaultKeyFunc
|
|
}
|
|
|
|
return r
|
|
}
|
|
|
|
func (r *RedisStore) Set(k string, data []byte, expires time.Duration) error {
|
|
cmd := r.client.Set(context.Background(), r.key(k), data, expires)
|
|
return cmd.Err()
|
|
}
|
|
|
|
func (r *RedisStore) Get(key string) ([]byte, error) {
|
|
return r.client.Get(context.Background(), r.key(key)).Bytes()
|
|
}
|
|
|
|
func (r *RedisStore) Delete(key string) error {
|
|
return r.client.Del(context.Background(), r.key(key)).Err()
|
|
}
|
|
|
|
func (r *RedisStore) Flush() error {
|
|
return r.client.FlushDB(context.Background()).Err()
|
|
}
|
|
|
|
func (r *RedisStore) Has(key string) bool {
|
|
if _, err := r.Get(key); err != nil {
|
|
return false
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
func (r *RedisStore) key(k string) string {
|
|
return r.keyFn(k)
|
|
}
|