| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- package cache
- import (
- "context"
- "time"
- "github.com/redis/go-redis/v9"
- )
- // Redis cache implement
- type Redis struct {
- client *redis.Client
- }
- // NewRedis 创建 redis 客户端
- func NewRedis(client *redis.Client, options *redis.Options) (*Redis, error) {
- if client == nil {
- client = redis.NewClient(options)
- }
- r := &Redis{
- client: client,
- }
- if err := r.connect(); err != nil {
- return nil, err
- }
- return r, nil
- }
- func (*Redis) String() string {
- return "redis"
- }
- func (r *Redis) connect() error {
- var err error
- _, err = r.client.Ping(context.TODO()).Result()
- return err
- }
- func (r *Redis) Get(key string) (string, error) {
- return r.client.Get(context.TODO(), key).Result()
- }
- func (r *Redis) Set(key string, value interface{}, expiration int) error {
- return r.client.Set(context.TODO(), key, value, time.Duration(expiration)*time.Second).Err()
- }
- func (r *Redis) Del(key string) error {
- return r.client.Del(context.TODO(), key).Err()
- }
- // HashGet 获取哈希
- func (r *Redis) HashGet(hk, key string) (string, error) {
- return r.client.HGet(context.TODO(), hk, key).Result()
- }
- // HashDel 删除哈希
- func (r *Redis) HashDel(hk, key string) error {
- return r.client.HDel(context.TODO(), hk, key).Err()
- }
- // HashSet 设置哈希
- func (r *Redis) HashSet(hk, key string, value interface{}) error {
- return r.client.HSet(context.TODO(), hk, key, value).Err()
- }
- // Increase 递增
- func (r *Redis) Increase(key string) error {
- return r.client.Incr(context.TODO(), key).Err()
- }
- // Decrease 递减
- func (r *Redis) Decrease(key string) error {
- return r.client.Decr(context.TODO(), key).Err()
- }
- // Expire 设置过期时间
- func (r *Redis) Expire(key string, dur time.Duration) error {
- return r.client.Expire(context.TODO(), key, dur).Err()
- }
- // GetClient 获取 redis client
- func (r *Redis) GetClient() *redis.Client {
- return r.client
- }
|