GO语言-Redis 连接池

大兔子大兔子 提交于 2021-01-03 17:30:17

自留笔记:从beego中分离出来的

//file name: redis.go

package conn

import (
//	"fmt"
	"github.com/garyburd/redigo/redis"
)
var MAX_POOL_SIZE = 20

var redisPool chan redis.Conn

func putRedis(conn redis.Conn) {
	if redisPool == nil {
		redisPool = make(chan redis.Conn, MAX_POOL_SIZE)
	}
	if len(redisPool) >= MAX_POOL_SIZE {
		conn.Close()
		return
	}
	redisPool <- conn
}

func InitRedis(network, address string) redis.Conn {
	redisPool = make(chan redis.Conn, MAX_POOL_SIZE)
	if len(redisPool) == 0 {
		go func() {
			for i := 0; i < MAX_POOL_SIZE/2; i++ {
				c, err := redis.Dial(network, address)
				if err != nil {
					panic(err)
				}
				putRedis(c)
			}
		}()
	}
	return <-redisPool
}
test:
package main

import (
	"code.google.com/p/go-uuid/uuid"
	"fmt"
	"github.com/garyburd/redigo/redis"
	"time"
	"conn"
)

func main() {
	fmt.Println()

	c := conn.InitRedis("tcp", "127.0.0.1:6379")
	
	//test uuid
	fmt.Println(time.Now())
	startTime := time.Now()
	
	var Success, Failure int
	for i := 0; i < 100000; i++ {
		if ok, _ := redis.Bool(c.Do("HSET", "payVerify:session", uuid.New(), "aaaa")); ok {
			Success++
			// break
		} else {
			Failure++
		}
	}
	fmt.Println(time.Now())
	fmt.Println("用时:", time.Now().Sub(startTime), "总计:100000,成功:", Success, "失败:", Failure)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!