9 Star 44 Fork 6

kelvins-io / g2cache

Create your Gitee Account
Explore and code with more than 6 million developers,Free private repositories !:)
Sign up
Clone or download
redis_helper.go 2.11 KB
Copy Edit Web IDE Raw Blame History
Bleem authored 2021-04-23 22:52 . !1 out cache是Redis时启动检查
package g2cache
import (
"github.com/gomodule/redigo/redis"
"time"
)
func RedisPublish(channel, message string, pool *redis.Pool) error {
conn, err := getRedisConn(pool)
if err != nil {
return err
}
defer conn.Close()
_, err = conn.Do("PUBLISH", channel, message)
return err
}
func RedisSetString(key, value string, ttl int, pool *redis.Pool) error {
conn, err := getRedisConn(pool)
if err != nil {
return err
}
defer conn.Close()
_, err = conn.Do("SETEX", key, ttl, value)
return err
}
func RedisGetString(key string, pool *redis.Pool) (string, error) {
conn, err := getRedisConn(pool)
if err != nil {
return "", err
}
defer conn.Close()
v, err := redis.String(conn.Do("GET", key))
if err != nil {
return "", err
}
return v, nil
}
func RedisDelKey(key string, pool *redis.Pool) error {
conn, err := getRedisConn(pool)
if err != nil {
return err
}
defer conn.Close()
_, err = conn.Do("DEL", key)
return err
}
func getRedisConn(pool *redis.Pool) (redis.Conn, error) {
conn := pool.Get()
if err := conn.Err(); err != nil {
conn.Close()
return nil, err
}
return conn, nil
}
func GetRedisPool(conf *RedisConf) (*redis.Pool,error) {
pool := &redis.Pool{
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", conf.DSN)
if err != nil {
return nil, err
}
if conf.Pwd != "" {
if _, err := c.Do("AUTH", conf.Pwd); err != nil {
errC := c.Close()
if errC != nil {
return nil, errC
}
return nil, err
}
}
if conf.DB > 0 {
if _, err := c.Do("SELECT", conf.DB); err != nil {
errC := c.Close()
if errC != nil {
return nil, errC
}
return nil, err
}
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
MaxIdle: conf.MaxConn,
MaxActive: conf.MaxConn,
IdleTimeout: 300 * time.Second,
Wait: true,
MaxConnLifetime: 30 * time.Minute,
}
//ping
conn, err := pool.Dial()
if err != nil {
return nil, err
}
err = pool.TestOnBorrow(conn, time.Now())
if err != nil {
return nil, err
}
return pool, nil
}

Comment ( 0 )

Sign in for post a comment

Go
1
https://gitee.com/kelvins-io/g2cache.git
git@gitee.com:kelvins-io/g2cache.git
kelvins-io
g2cache
g2cache
release

Search