Golang操作Redis连接池

package main

import (
	"fmt"
	"github.com/garyburd/redigo/redis"
)

var pool *redis.Pool
// 程序启动时,初始化连接池
func init() {
	pool = &redis.Pool{
		MaxIdle: 8, // 最大空闲连接数
		MaxActive: 0, // 数据库最大连接数,0表示不限制
		IdleTimeout: 100, // 最大空闲时间
		Dial: func() (redis.Conn, error){ // 初始化连接的代码
			return redis.Dial("tcp", "localhost:6379")
		},
	}
}
func main() {
	// 先从pool取出一个连接, 一定要保证连接池是没有关闭的
	conn := pool.Get()
	defer pool.Close()
	_, err := conn.Do("Set", "name", "Tom")
	if err != nil {
		fmt.Println("conn.Do ", err)
		return
	}
	// 取出
	r, err := redis.String(conn.Do("Get", "name"))
	if err != nil {
		fmt.Println("conn error ", err)
	}
	
	fmt.Println("r=", r)
}

猜你喜欢

转载自blog.csdn.net/qq2942713658/article/details/113576123