hash.go
2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package redis
import (
"errors"
"github.com/gomodule/redigo/redis"
)
//设置指定hash指定key的值
func Hset(key string, field string, value interface{}, timeout int64) error {
if len(key) < 1 || len(field) < 1 {
return errors.New("Invalid argument")
}
c := redisPool.Get()
defer c.Close()
var err error
_, err = c.Do("HSET", key, field, value)
if err != nil {
return err
}
//设置有效时间
if timeout > 0 {
length := Hlen(key)
if 1 == length {
_, err := c.Do("EXPIRE", key, timeout)
if err != nil {
Del(key)
return err
}
}
}
return nil
}
//获取指定hash的所有key
func Hkeys(key string) ([][]byte, error) {
if len(key) < 1 {
return nil, errors.New("Invalid argument")
}
c := redisPool.Get()
defer c.Close()
v, err := redis.ByteSlices(c.Do("HKEYS", key))
if err != nil {
return nil, err
}
return v, nil
}
//获取指定hash指定key的value
func Hget(key string, field string) (string, error) {
if len(key) < 1 {
return "", errors.New("invalid argument")
}
c := redisPool.Get()
defer c.Close()
v, err := redis.String(c.Do("HGET", key, field))
if err != nil {
return "", err
}
return v, nil
}
//获取指定hash的key和value
func Hgetall(key string) (map[string]string, error) {
if len(key) < 1 {
return nil, errors.New("Invalid argument")
}
c := redisPool.Get()
defer c.Close()
v, err := redis.StringMap(c.Do("HGETALL", key))
if err != nil {
return nil, err
}
return v, nil
}
//获取hash字段数量
func Hlen(key string) int {
if len(key) < 1 {
return 0
}
c := redisPool.Get()
defer c.Close()
v, err := redis.Int(c.Do("HLEN", key))
if err != nil || v <= 0 {
return 0
}
return v
}
// 删除哈希指定字段
func Hdel(key string, field string) error {
if len(key) < 1 {
return errors.New("Invalid argument")
}
c := redisPool.Get()
defer c.Close()
var err error
_, err = c.Do("HDEL", key, field)
if err != nil {
return err
}
return nil
}
// 查看哈希表 key 中,指定的字段是否存在
func Hexists(key string, field string) bool {
if len(key) < 1 || len(field) < 1 {
return false
}
cli := redisPool.Get()
defer cli.Close()
v, err := redis.Int(cli.Do("HEXISTS", key, field))
if err != nil || v == 0 {
return false
}
return true
}