beego使用redis线程池来操作数据

使用beego的链接redis

package models

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

var(
	pool *redis.Pool
	redisHost = beego.AppConfig.String("reids_host")
	redisPass = beego.AppConfig.String("redis_passwd")
)

//newRedisPool:创建redis连接池
func newRedisPool()*redis.Pool{
	return &redis.Pool{
		MaxIdle:50,
		MaxActive:30,
		IdleTimeout:300*time.Second,
		Dial: func() (redis.Conn,  error) {
			c,err := redis.Dial("tcp",redisHost,redis.DialPassword(redisPass))
			if err != nil {
				fmt.Println(err)
				return nil,err
			}
			//2、访问认证
			//if _, err =c.Do("AUTH",redisPass);err!=nil{
			//	c.Close()
			//	return nil,err
			//}
			return c,nil
		},
		//定时检查redis是否出状况
		TestOnBorrow: func(conn redis.Conn, t time.Time) error {
			if time.Since(t)<time.Minute{
				return nil
			}
			_,err := conn.Do("PING")
			return err
		},
	}
}

//初始化redis连接池
func init(){
	pool = newRedisPool()
}

//对外暴露连接池
func RedisPool()*redis.Pool{
	return pool
}

操作具体数据

	rc := models.RedisPool().Get()
	//注意close()
	defer rc.Close()
	beego.Info(redis.PoolStats{})
	//默认不选库操作的是0
	rc.Do("select",2)
	_, err :=rc.Do("set","wohao",234234)
	// 写入值10S后过期
	_, err = c.Do("SET", "password", "123456", "EX", "10")
	if err != nil {
		beego.Info(err.Error())
	}

你可能感兴趣的:(beego,redis)