0%

redigo 连接池

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
package main

import (
"flag"
"fmt"
"github.com/gomodule/redigo/redis"
"time"
)

//声明一些全局变量
var (
pool *redis.Pool
redisServer = flag.String("redisServer", ":6379", "")
redisPassword = flag.String("redisPassword", "123456", "")
)

//初始化一个pool
func newPool(server, password string) *redis.Pool {
return &redis.Pool{
MaxIdle: 3,
MaxActive: 5,
IdleTimeout: 300 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", server,
redis.DialConnectTimeout(1 * time.Second),
redis.DialReadTimeout(1 * time.Second),
redis.DialWriteTimeout(1 * time.Second))
if err != nil {
return nil, err
}
if _, err := c.Do("AUTH", password); err != nil {
c.Close()
return nil, err
}
return c, err
},
// Use the TestOnBorrow function to check the health of an idle connection
// before the connection is returned to the application.
TestOnBorrow: func(c redis.Conn, t time.Time) error {
if time.Since(t) < time.Minute {
return nil
}
_, err := c.Do("PING")
return err
},
// If Wait is true and the pool is at the MaxActive limit,
// then Get() waits for a connection to be returned to the pool before returning
Wait: true,

}
}

func main() {
flag.Parse()
pool = newPool(*redisServer, *redisPassword)

conn := pool.Get()
defer conn.Close()
//redis操作
v, err := conn.Do("SET", "pool", "test")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(v)
v, err = redis.String(conn.Do("GET", "pool"))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(v)

}

参考文档:

https://www.jianshu.com/p/aeb27a6aa42d