-
Notifications
You must be signed in to change notification settings - Fork 0
/
13redis.go
68 lines (59 loc) · 1.54 KB
/
13redis.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
package main
//需要设置gopath
//在gopath下执行 go get github.com/garyburd/redigo/redis
import (
"fmt"
"github.com/garyburd/redigo/redis" //不同的包有不同的api,按文档使用就好了
)
func main() {
c, err := redis.Dial("tcp", "localhost:6379")
if err != nil {
fmt.Println("连接redis失败")
return
}
fmt.Println("连接redis成功")
//需要关闭
defer func(c redis.Conn) {
err := c.Close()
if err != nil {
fmt.Println("关闭失败")
}
}(c)
_, err2 := c.Do("Set", "goTestKey", "hello")
if err2 != nil {
fmt.Println("set失败")
return
}
//返回的是接口类型,需要转成string
goTestKey, _ := redis.String(c.Do("Get", "goTestKey"))
fmt.Println("获取成功,goTestKey:", goTestKey)
PoolTest()
}
// PoolTest 连接池方式
func PoolTest() {
var pool *redis.Pool //Pool是一个结构体,为什么要定义为指针,因为这个包的Get函数跟指针绑定的
pool = &redis.Pool{ //&符号是指针操作,然后初始化结构体
MaxIdle: 10,
MaxActive: 0,
IdleTimeout: 200,
Dial: func() (redis.Conn, error) {
return redis.Dial("tcp", "localhost:6379")
},
}
//从pool中取出一个连接
conn2 := pool.Get()
//需要关闭
defer func(conn2 redis.Conn) {
err := conn2.Close()
if err != nil {
fmt.Println("关闭失败2")
}
}(conn2)
_, err3 := conn2.Do("Set", "goTestKey2", "world")
if err3 != nil {
fmt.Println("set2失败")
return
}
goTestKey2, _ := redis.String(conn2.Do("Get", "goTestKey2"))
fmt.Println("获取成功,goTestKey2:", goTestKey2)
}