github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/conf/redis/redis_kv.go (about)

     1  package redis
     2  
     3  import (
     4  	"encoding/json"
     5  	"time"
     6  
     7  	"github.com/gomodule/redigo/redis"
     8  )
     9  
    10  type CacheKeys interface {
    11  	CacheKeys() []string
    12  }
    13  
    14  func (r *Redis) Get(k string, v any) error {
    15  	raw, err := redis.Bytes(r.Exec(&Cmd{Name: "GET", Args: []any{r.Key(k)}}))
    16  	if err != nil {
    17  		return err
    18  	}
    19  	return json.Unmarshal(raw, v)
    20  }
    21  
    22  func (r *Redis) SetEx(k string, v any, exp time.Duration) error {
    23  	raw, err := json.Marshal(v)
    24  	if err != nil {
    25  		return err
    26  	}
    27  	_, err = r.Exec(&Cmd{Name: "SET", Args: []any{r.Key(k), raw, "PX", exp.Milliseconds()}})
    28  	return err
    29  }
    30  
    31  func (r *Redis) Set(k string, v any) error {
    32  	raw, err := json.Marshal(v)
    33  	if err != nil {
    34  		return err
    35  	}
    36  	_, err = r.Exec(&Cmd{Name: "SET", Args: []any{r.Key(k), raw}})
    37  	return err
    38  }
    39  
    40  func (r *Redis) Del(ks ...string) error {
    41  	keys := make([]any, 0, len(ks))
    42  	for _, k := range ks {
    43  		keys = append(keys, r.Key(k))
    44  	}
    45  	_, err := r.Exec(&Cmd{Name: "DEL", Args: keys})
    46  	return err
    47  }
    48  
    49  func (r *Redis) RawDel(ks ...string) error {
    50  	keys := make([]any, 0, len(ks))
    51  	for _, k := range ks {
    52  		keys = append(keys, k)
    53  	}
    54  	_, err := r.Exec(&Cmd{Name: "DEL", Args: keys})
    55  	return err
    56  }
    57  
    58  func (r *Redis) IncrBy(k string, count int64) (int64, error) {
    59  	return redis.Int64(r.Exec(&Cmd{Name: "INCRBY", Args: []any{r.Key(k), count}}))
    60  }
    61  
    62  func (r *Redis) Exists(k string) (bool, error) {
    63  	return redis.Bool(r.Exec(&Cmd{Name: "EXISTS", Args: []any{r.Key(k)}}))
    64  }
    65  
    66  func (r *Redis) Keys(pattern string) ([]string, error) {
    67  	return redis.Strings(r.Exec(&Cmd{Name: "KEYS", Args: []any{r.Key(pattern)}}))
    68  }