1 Star 1 Fork 0

窦雪峰 / go-utils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
redis.go 1.76 KB
一键复制 编辑 原始数据 按行查看 历史
窦雪峰 提交于 2022-05-28 16:49 . 暴露pool连接池
/*
* @Author: i@douxuefeng.cn
* @Date: 2021-10-31 16:32:16
* @LastEditTime: 2022-05-28 14:23:07
* @LastEditors: i@douxuefeng.cn
* @Description:
* @FilePath: \go-utils\cache\redis.go
*/
package cache
import (
"time"
"github.com/gomodule/redigo/redis"
)
type redisPool struct {
Pool *redis.Pool
}
type RedisOpt struct {
Host string
Password string
Database int
MaxIdle int
MaxActive int
IdleTimeout int //second
}
var client *redisPool
func InitRedis(opt *RedisOpt) {
client = new(redisPool)
client.Pool = &redis.Pool{
MaxIdle: opt.MaxIdle,
MaxActive: opt.MaxActive,
IdleTimeout: time.Duration(opt.IdleTimeout) * time.Second,
Wait: true,
Dial: func() (redis.Conn, error) {
return redis.Dial("tcp", opt.Host,
redis.DialPassword(opt.Password),
redis.DialDatabase(opt.Database),
redis.DialConnectTimeout(time.Duration(opt.IdleTimeout)*time.Second),
redis.DialReadTimeout(time.Duration(opt.IdleTimeout)*time.Second),
redis.DialWriteTimeout(time.Duration(opt.IdleTimeout)*time.Second))
},
}
}
func NewRedisConn() *redisPool {
return client
}
func (r *redisPool) Get(key string) (string, error) {
conn := r.Pool.Get()
defer conn.Close()
return redis.String(conn.Do("GET", key))
}
//Set 设置一个过期时间值
func (r *redisPool) Set(key string, data string, timeout int64) error {
conn := r.Pool.Get()
defer conn.Close()
_, err := conn.Do("SETEX", key, timeout, data)
return err
}
func (r *redisPool) IsExist(key string) bool {
conn := r.Pool.Get()
defer conn.Close()
a, _ := redis.Bool(conn.Do("EXISTS", key))
return a
}
func (r *redisPool) Del(key string) error {
conn := r.Pool.Get()
defer conn.Close()
if _, err := conn.Do("DEL", key); err != nil {
return err
}
return nil
}
// hash
Go
1
https://gitee.com/douxuefeng/go-utils.git
git@gitee.com:douxuefeng/go-utils.git
douxuefeng
go-utils
go-utils
v0.2.6

搜索帮助

53164aa7 5694891 3bd8fe86 5694891