string.go
1.6 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
package redis
import (
"encoding/json"
"errors"
"github.com/gomodule/redigo/redis"
)
func Set(key string, v interface{}, timeout int64) error {
if len(key) <= 0 || timeout < 0 || v == nil {
err := errors.New("Invalid argument")
return err
}
c := redisPool.Get()
defer c.Close()
switch v := v.(type) {
case int8, int16, int32, int, int64, uint8, uint16, uint, uint32, uint64, string:
if timeout == 0 {
if _, err := c.Do("SET", key, v); err != nil {
return err
}
} else {
if _, err := c.Do("SETEX", key, timeout, v); err != nil {
return err
}
}
default:
b, err := json.Marshal(v)
if err != nil {
return err
}
if timeout == 0 {
if _, err = c.Do("SET", key, string(b)); err != nil {
return err
}
} else {
if _, err = c.Do("SETEX", key, timeout, string(b)); err != nil {
return err
}
}
}
return nil
}
func Get(key string) (string, error) {
if len(key) < 1 {
return "", errors.New("Invalid argument")
}
c := redisPool.Get()
defer c.Close()
v, err := redis.String(c.Do("GET", key))
if err != nil {
return "", err
}
return v, nil
}
//获取指定键的INCR
func Incr(key string, timeout int64) (int64, bool) {
if len(key) < 1 {
return 0, false
}
c := redisPool.Get()
defer c.Close()
var isExpire bool = false
// timeout大于0并且不存在改key,则需要设置ttl
exists, err := Exists(key)
if err != nil {
return 0, false
}
if timeout > INFINITE && !exists {
isExpire = true
}
v, err := redis.Int64(c.Do("INCR", key))
if err != nil || v == 0 {
return 0, false
}
if isExpire {
Expire(key, timeout)
}
return v, true
}