hash.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package cache
  2. import (
  3. "github.com/go-redis/redis"
  4. )
  5. func (p *RedisCache) HMGet(key string, fields ...string) ([]string, error) {
  6. args := []interface{}{"hmget", key}
  7. for _, val := range fields {
  8. args = append(args, val)
  9. }
  10. return p.commandReturnStringSlice(args...)
  11. }
  12. func (p *RedisCache) HGet(key, field string) (string, error) {
  13. if p.isCluster {
  14. return p.cluster.HGet(key, field).Result()
  15. }
  16. return p.client.HGet(key, field).Result()
  17. }
  18. func (p *RedisCache) HGetAll(key string) (map[string]string, error) {
  19. if p.isCluster {
  20. return p.cluster.HGetAll(key).Result()
  21. }
  22. return p.client.HGetAll(key).Result()
  23. }
  24. func (p *RedisCache) HMSet(key string, fields map[string]interface{}) (string, error) {
  25. if p.isCluster {
  26. return p.cluster.HMSet(key, fields).Result()
  27. }
  28. return p.client.HMSet(key, fields).Result()
  29. }
  30. func (p *RedisCache) HSet(key, field string, value interface{}) (bool, error) {
  31. if p.isCluster {
  32. return p.cluster.HSet(key, field, value).Result()
  33. }
  34. return p.client.HSet(key, field, value).Result()
  35. }
  36. func (p *RedisCache) HIncrBy(key, field string, incr int64) (int64, error) {
  37. if p.isCluster {
  38. return p.cluster.HIncrBy(key, field, incr).Result()
  39. }
  40. return p.client.HIncrBy(key, field, incr).Result()
  41. }
  42. func (p *RedisCache) BatchHGetAll(keys ...string) (map[string]map[string]string, error) {
  43. cmds := make(map[string]*redis.StringStringMapCmd, len(keys))
  44. if p.isCluster {
  45. if _, err := p.cluster.Pipelined(func(pipe redis.Pipeliner) error {
  46. for _, key := range keys {
  47. cmds[key] = pipe.HGetAll(key)
  48. }
  49. return nil
  50. }); err != nil {
  51. return nil, err
  52. }
  53. } else {
  54. if _, err := p.client.Pipelined(func(pipe redis.Pipeliner) error {
  55. for _, key := range keys {
  56. cmds[key] = pipe.HGetAll(key)
  57. }
  58. return nil
  59. }); err != nil {
  60. return nil, err
  61. }
  62. }
  63. results := make(map[string]map[string]string, len(cmds))
  64. for _, key := range keys {
  65. if v, ok := cmds[key]; ok && v != nil {
  66. results[key] = v.Val()
  67. }
  68. }
  69. return results, nil
  70. }