/
redis.go
101 lines (80 loc) · 2.29 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
package hub
import (
"fmt"
"ueligo/global"
"ueligo/area"
"time"
"github.com/garyburd/redigo/redis"
)
var (
Pool *redis.Pool
RedisConn *redis.Conn
)
func RedisInit() {
fmt.Println(global.Config.Object.RedisPort)
RedisConn, err := redis.Dial("tcp", global.Config.Object.RedisHost+`:`+string(global.Config.Object.RedisPort))
//defer RedisConn.Close()
if err != nil {
fmt.Println("Redis server connect failed,", err.Error())
return
}
//n, err := RedisConn.Do("Set", "aaa", "vvvvvvvvv")
//fmt.Println(n, err)
data := &area.Session{
``,
"{}",
true, // 登录成功
false, // 是否被踢出
``,
time.Now().Unix(), //加入时间
time.Now().Unix(),
}
RedisConn.Do("Set", "111", data)
v1, err := redis.String(RedisConn.Do("Get", "111"))
fmt.Println(v1, err)
v, err := redis.String(RedisConn.Do("Get", "aaa"))
fmt.Println(v, err)
Pool = NewPool(global.Config.Object.RedisHost+":"+string(global.Config.Object.RedisPort), global.Config.Object.RedisPassword)
cc := Pool.Get()
fmt.Println("cc:", cc)
v2, err := redis.String(cc.Do("Get", "aaa"))
fmt.Println(v2, err)
}
func NewPool(server, password string) *redis.Pool {
return &redis.Pool{
MaxIdle: 3,
IdleTimeout: 30 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", server)
if err != nil {
return nil, err
}
if password != "" {
if _, err := c.Do("AUTH", password); err != nil {
c.Close()
return nil, err
}
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
}
func Set(key string, args ...interface{}) (bool, error) {
Pool = NewPool(global.Config.Object.RedisHost+":"+string(global.Config.Object.RedisPort), global.Config.Object.RedisPassword)
cc := Pool.Get()
return redis.Bool(cc.Do("Set", `ueli/`+key, args))
}
func Get(key string) (string, error) {
Pool = NewPool(global.Config.Object.RedisHost+":"+string(global.Config.Object.RedisPort), global.Config.Object.RedisPassword)
cc := Pool.Get()
return redis.String(cc.Do("Get", `ueli/`+key))
}
func _Delete(key string) (bool, error) {
Pool = NewPool(global.Config.Object.RedisHost+":"+string(global.Config.Object.RedisPort), global.Config.Object.RedisPassword)
cc := Pool.Get()
return redis.Bool(cc.Do("Delete", `ueli/`+key))
}