-
Notifications
You must be signed in to change notification settings - Fork 1
/
redis.go
257 lines (204 loc) · 4.9 KB
/
redis.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"os"
"strings"
"github.com/garyburd/redigo/redis"
)
// var (
// redisAddress = flag.String("redis-address", ":6379", "Address to the Redis server")
// maxConnections = flag.Int("max-connections", 10, "Max connections to Redis")
// )
var (
con redis.Conn
)
// http://redis.io/commands
func testRedis() {
// redisPool := redis.NewPool(func() (redis.Conn, error) {
// c, err := redis.Dial("tcp", url)
//
// if err != nil {
// return nil, err
// }
//
// return c, err
// }, 1)
// defer redisPool.Close()
// ok !!!
// c := redisPool.Get()
// get
key := "test2"
// or use type assertion
value, err := redis.String(con.Do("GET", key))
if err != nil {
log.Println("got err:", err)
// e.g. got err: redigo: nil returned
} else {
log.Println("got:", value)
}
// exist
// exists, err := redis.Bool(c.Do("EXISTS", "foo"))
// set
key2 := "test3"
status, err := con.Do("SET", key2, "body2")
if err != nil {
log.Println("set err:", err)
// message := fmt.Sprintf("Could not SET %s:%s", key, value)
} else {
log.Println("set status:", status)
}
// set json
// key8 := "key8"
// user := GitHubUser{"1", "1", "1", 8, 3}
// value3, _ := json.Marshal(user)
// n, err := con.Do("SET", key8, value3)
// if err != nil {
// fmt.Println(err)
// }
// value7, err := redis.Bytes(con.Do("GET", key8))
// if err != nil {
// fmt.Println("get json fail:", err)
// }
// // 将json解析成map类型
// var object GitHubUser
// err = json.Unmarshal(value7, &object)
// if err != nil {
// fmt.Println("convert fail:", err)
// } else {
// fmt.Println("json:", object)
// }
// values, err := redis.Values(c.Do("SORT", "albums",
// for len(values) > 0 {
// values, err = redis.Scan(values, &title, &rating)
// func (s *Script) Send(c Conn, keysAndArgs ...interface{}) error
// Send evaluates the script without waiting for the reply.
// delete
n, err := con.Do("DEL", "test3")
if err != nil {
log.Println("got err:", err)
// message := fmt.Sprintf("Could not SET %s:%s", key, value)
} else {
log.Println("del status:", n)
}
// redis> SET key2 "World"
// OK
// redis> DEL key1 key2 key3
}
// type singleton struct {
// }
// var instance *singleton
// var once sync.Once
// func GetInstance() *singleton {
// once.Do(func() {
// instance = &singleton{}
// })
// return instance
// }
func close(con redis.Conn) {
defer con.Close()
}
func connect() redis.Conn {
// log.Println("redis init")
url := ""
redisPWD := ""
db_url := os.Getenv("REDIS_URL")
i := strings.Index(db_url, "@")
// log.Println("@ is at:", i)
if i > -1 {
url = db_url[(i + 1):len(db_url)]
j := strings.Index(db_url, "h:")
if j > -1 {
redisPWD = db_url[(j + 2):i]
}
} else {
url = db_url[8:len(db_url)]
}
// log.Println("url:", url)
// log.Println("pwd:", redisPWD)
c, err := redis.Dial("tcp", url)
if err != nil {
log.Println("redis dial fail")
return nil //nil, err
}
if redisPWD != "" {
if _, err := c.Do("AUTH", redisPWD); err != nil {
c.Close()
log.Println("redis auth fail")
return nil //nil, err
}
}
// log.Println("redis init ok !!!")
return c
}
func SetUserOrJustUpdateToken(account string, token string) {
mux.Lock()
elem, ok := GetUserFromDB(account)
var user GitHubUser
if ok == true {
log.Println("update a user")
// update it
user = *elem
user.Tokens = append(user.Tokens, token)
} else {
// add it
log.Println("add a new user")
user = GitHubUser{account, []string{token}, NOTSTART, 0, 0}
}
SetUserToDB(account, user)
mux.Unlock()
}
func SetUser(account string, user GitHubUser) error {
mux.Lock()
SetUserToDB(account, user)
defer mux.Unlock()
return nil
}
func SetUserToDB(account string, user GitHubUser) error {
con := connect()
if con == nil {
fmt.Println("redis connection fails")
return errors.New("You can't set user to redis due to no redis connection")
}
defer close(con)
value, _ := json.Marshal(user)
_, err := con.Do("SET", account, value)
if err != nil {
fmt.Println("set user to db error:", err)
} else {
fmt.Println("set user to db ok")
}
return err
}
func GetUser(account string) (*GitHubUser, error) {
mux.Lock()
defer mux.Unlock()
elem, ok := GetUserFromDB(account) // elem, ok := userMap[account]
if ok == true {
return elem, nil
}
return nil, errors.New("user does not exist")
}
func GetUserFromDB(account string) (*GitHubUser, bool) {
con := connect()
if con == nil {
fmt.Println("redis connection fails")
return nil, false
}
defer close(con)
// log.Println("try to get user from db:", account)
value, err := redis.Bytes(con.Do("GET", account))
if err != nil {
fmt.Println("get account json fail:", err)
return nil, false
}
// fmt.Println("user json value:", string(value))
var object GitHubUser
err = json.Unmarshal(value, &object)
if err != nil {
fmt.Println("convert fail:", err)
}
return &object, true
}