-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis_client.go
116 lines (98 loc) · 2.22 KB
/
redis_client.go
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
package gluaredis
import (
"context"
"time"
"github.com/redis/go-redis/v9"
lua "github.com/yuin/gopher-lua"
)
const (
REDIS_CLIENT_TYPENAME = "redis_client_typename"
)
var ctx = context.Background()
func registerRedisClientType(L *lua.LState) {
mt := L.NewTypeMetatable(REDIS_CLIENT_TYPENAME)
L.SetField(mt, "__index", L.SetFuncs(L.NewTable(), redisClientMethods))
}
var redisClientMethods = map[string]lua.LGFunction{
"set": set,
"setnx": setnx,
"get": get,
"del": del,
"expire": expire,
}
func checkRedisClient(L *lua.LState) *redis.Client {
ud := L.CheckUserData(1)
if v, ok := ud.Value.(*redis.Client); ok {
return v
}
L.ArgError(1, "redis client expected")
return nil
}
func set(L *lua.LState) int {
rdb := checkRedisClient(L)
key := L.CheckString(2)
value := L.CheckString(3)
expire := L.CheckInt(4)
err := rdb.Set(ctx, key, value, time.Duration(expire)*time.Second).Err()
if err != nil {
L.Push(lua.LString(err.Error()))
} else {
L.Push(lua.LNil)
}
return 1
}
func setnx(L *lua.LState) int {
rdb := checkRedisClient(L)
key := L.CheckString(2)
value := L.CheckString(3)
expire := L.CheckInt(4)
success, err := rdb.SetNX(ctx, key, value, time.Duration(expire)*time.Second).Result()
L.Push(lua.LBool(success))
if err != nil {
L.Push(lua.LString(err.Error()))
} else {
L.Push(lua.LNil)
}
return 2
}
func get(L *lua.LState) int {
rdb := checkRedisClient(L)
key := L.CheckString(2)
val, err := rdb.Get(ctx, key).Result()
L.Push(lua.LString(val))
if err == redis.Nil {
L.Push(lua.LBool(false))
L.Push(lua.LNil)
} else if err != nil {
L.Push(lua.LBool(false))
L.Push(lua.LString(err.Error()))
} else {
L.Push(lua.LBool(true))
L.Push(lua.LNil)
}
return 3
}
func del(L *lua.LState) int {
rdb := checkRedisClient(L)
key := L.CheckString(2)
err := rdb.Del(ctx, key).Err()
if err != nil {
L.Push(lua.LString(err.Error()))
} else {
L.Push(lua.LNil)
}
return 1
}
func expire(L *lua.LState) int {
rdb := checkRedisClient(L)
key := L.CheckString(2)
expire := L.CheckInt(3)
success, err := rdb.Expire(ctx, key, time.Duration(expire)*time.Second).Result()
L.Push(lua.LBool(success))
if err != nil {
L.Push(lua.LString(err.Error()))
} else {
L.Push(lua.LNil)
}
return 2
}