-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.go
More file actions
69 lines (59 loc) · 1.28 KB
/
cli.go
File metadata and controls
69 lines (59 loc) · 1.28 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
package rdl
import (
"time"
"github.com/garyburd/redigo/redis"
goredis "github.com/go-redis/redis"
)
// cmdScript is the script to implement the `SetIfValIs` interface
var cmdScript string = `
local v=redis.call("get", KEYS[1]);
if (not v) or (v == ARGV[3]) then
return redis.call("setex", KEYS[1], ARGV[1], ARGV[2])
end
`
// RedigoClient implemented `SetIfValIs` interface
type RedigoClient struct {
pool *redis.Pool
}
func NewRedigo(pool *redis.Pool) *RedigoClient {
return &RedigoClient{
pool: pool,
}
}
func (cli *RedigoClient) SetIfValIs(
k string,
newVal string,
ex time.Duration,
origin string,
) (ok bool) {
c := cli.pool.Get()
defer c.Close()
s := redis.NewScript(1, cmdScript)
reply, err := s.Do(c, k, int64(ex.Seconds()), newVal, origin)
return err == nil && reply == "OK"
}
// GoRedisClient implemented `SetIfValIs` interface
type GoRedisClient struct {
conn *goredis.Client
}
func NewGoRedis(conn *goredis.Client) *GoRedisClient {
return &GoRedisClient{
conn: conn,
}
}
func (cli *GoRedisClient) SetIfValIs(
k string,
newVal string,
ex time.Duration,
origin string,
) (ok bool) {
s := goredis.NewScript(cmdScript)
reply, err := s.Run(
cli.conn,
[]string{k},
int64(ex.Seconds()),
newVal,
origin,
).Result()
return err == nil && reply == "OK"
}