redis.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package cache
  2. import (
  3. "time"
  4. "github.com/go-redis/redis/v7"
  5. )
  6. // NewRedis redis模式
  7. func NewRedis(client *redis.Client, options *redis.Options) (*Redis, error) {
  8. if client == nil {
  9. client = redis.NewClient(options)
  10. }
  11. r := &Redis{
  12. client: client,
  13. }
  14. err := r.connect()
  15. if err != nil {
  16. return nil, err
  17. }
  18. return r, nil
  19. }
  20. // Redis cache implement
  21. type Redis struct {
  22. client *redis.Client
  23. }
  24. func (*Redis) String() string {
  25. return "redis"
  26. }
  27. // connect connect test
  28. func (r *Redis) connect() error {
  29. var err error
  30. _, err = r.client.Ping().Result()
  31. return err
  32. }
  33. // Get from key
  34. func (r *Redis) Get(key string) (string, error) {
  35. return r.client.Get(key).Result()
  36. }
  37. // Set value with key and expire time
  38. func (r *Redis) Set(key string, val interface{}, expire int) error {
  39. return r.client.Set(key, val, time.Duration(expire)*time.Second).Err()
  40. }
  41. // Del delete key in redis
  42. func (r *Redis) Del(key string) error {
  43. return r.client.Del(key).Err()
  44. }
  45. // HashGet from key
  46. func (r *Redis) HashGet(hk, key string) (string, error) {
  47. return r.client.HGet(hk, key).Result()
  48. }
  49. // HashDel delete key in specify redis's hashtable
  50. func (r *Redis) HashDel(hk, key string) error {
  51. return r.client.HDel(hk, key).Err()
  52. }
  53. // Increase
  54. func (r *Redis) Increase(key string) error {
  55. return r.client.Incr(key).Err()
  56. }
  57. func (r *Redis) Decrease(key string) error {
  58. return r.client.Decr(key).Err()
  59. }
  60. // Set ttl
  61. func (r *Redis) Expire(key string, dur time.Duration) error {
  62. return r.client.Expire(key, dur).Err()
  63. }
  64. // GetClient 暴露原生client
  65. func (r *Redis) GetClient() *redis.Client {
  66. return r.client
  67. }