Golang项目简单初始化缓存池

Golang
333
0
0
2022-04-24
标签   Golang基础

博客:Golang项目中读取配置文件)

package setting

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

var (
   RedisPool *redis.Pool
)
func InitRedisPool() {
    RedisPool = &redis.Pool{
        //最大闲置连接
        MaxIdle: 30,
        //最大活动数
        MaxActive: 30,
        //数据库连接
        Dial: func() (redis.Conn, error) {
            c, err := redis.Dial("tcp", "127.0.0.1:6379")
            if err != nil {
                c.Close()
                fmt.Printf("fail to dial redis: %v\n", err)
                return nil, err
            }
            //密码认证,可填入redisd的连接密码 
            if _, err = c.Do("AUTH", ""); err != nil {
                c.Close()
                fmt.Printf("fail to auth redis: %v\n", err)
                return nil, err
            }

            //redis 缓存数据库认证 
            if _, err = c.Do("SELECT", ""); err != nil {
                c.Close()
                fmt.Printf("fail to SELECT DB redis: %v\n", err)
                return nil, err
            }
            return c, err
        },
        //测试连接是否正常
        TestOnBorrow: func(c redis.Conn, t time.Time) error {
            _, err := c.Do("PING")
            if err != nil {
                c.Close()
                fmt.Printf("fail to ping redis: %v\n", err)
                return err
            }
            return nil
        },
    }
    log.Println("connect redis success")
}

func Get() redis.Conn {
    return RedisPool.Get()
}