2021-03-24 23:33:28 +08:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"github.com/go-redis/redis/v8"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type RedisBackend struct {
|
2021-03-26 17:59:53 +08:00
|
|
|
ctx context.Context
|
|
|
|
client *redis.Client
|
|
|
|
prefixVal string
|
|
|
|
prefixHsh string
|
2021-03-24 23:33:28 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (b *RedisBackend) Get(key string) (res string, err error) {
|
2021-03-26 17:59:53 +08:00
|
|
|
return b.get(b.prefixVal, key)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (b *RedisBackend) GetHash(key string) (res string, err error) {
|
|
|
|
return b.get(b.prefixHsh, key)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (b *RedisBackend) Set(key, value string, ttl time.Duration) (err error) {
|
|
|
|
return b.set(b.prefixVal, key, value, ttl)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (b *RedisBackend) SetHash(key, value string, ttl time.Duration) (err error) {
|
|
|
|
return b.set(b.prefixHsh, key, value, ttl)
|
|
|
|
}
|
|
|
|
|
|
|
|
///
|
|
|
|
|
|
|
|
func (b *RedisBackend) get(prefix, key string) (res string, err error) {
|
|
|
|
cmd := b.client.Get(b.ctx, prefix+key)
|
2021-03-24 23:33:28 +08:00
|
|
|
if err := cmd.Err(); err != nil && err != redis.Nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
res, _ = cmd.Result()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-03-26 17:59:53 +08:00
|
|
|
func (b *RedisBackend) set(prefix, key, value string, ttl time.Duration) (err error) {
|
|
|
|
cmd := b.client.Set(b.ctx, prefix+key, value, ttl)
|
2021-03-24 23:33:28 +08:00
|
|
|
err = cmd.Err()
|
|
|
|
return
|
|
|
|
}
|