golang 使用 Redis 连接池 - Go语言中文社区

golang 使用 Redis 连接池


package cache

import (
	"3tee_admin/conf"
	"fmt"
	"time"

	"github.com/gomodule/redigo/redis"
	redigo "github.com/gomodule/redigo/redis"
)

var redisPool *redis.Pool

func init() {
	redisPool = PoolInitRedis(fmt.Sprintf("%v:%v", conf.Conf.Redis.Ip, conf.Conf.Redis.Port), conf.Conf.Redis.Password)
}

func PoolInitRedis(server string, password string) *redigo.Pool {
	return &redigo.Pool{
		MaxIdle:     2,
		IdleTimeout: 240 * time.Second,
		MaxActive:   3,
		Dial: func() (redigo.Conn, error) {
			c, err := redigo.Dial("tcp", server)
			if err != nil {
				return nil, err
			}
			if password != "" {
				if _, err := c.Do("AUTH", password); err != nil {
					c.Close()
					return nil, err
				}
			}
			return c, err
		},
		TestOnBorrow: func(c redigo.Conn, t time.Time) error {
			_, err := c.Do("PING")
			return err
		},
	}
}

func Set(key string, value interface{}) error {
	_, err := redisPool.Get().Do("SET", key, value)
	if err != nil {
		return err
	}
	_, err = redisPool.Get().Do("EXPIRE", key, conf.Conf.Redis.TokenExpiresTime)
	return err
}

func GetInt(key string) (int, error) {
	id, err := redigo.Int(redisPool.Get().Do("GET", key))
	return id, err
}

func Del(key string) error {
	_, err := redisPool.Get().Do("DEL", key)
	return err
}
版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_21821091/article/details/120536184
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2023-01-05 03:40:18
  • 阅读 ( 279 )
  • 分类:Redis

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢