snippet/redis/redis.go

130 lines
2.5 KiB
Go

package redis
import (
"encoding/json"
"time"
redigo "github.com/gomodule/redigo/redis"
)
var pool *redigo.Pool
//Config 配置
type Config struct {
Host string `yml:"host" json:"host"`
Password string `yml:"password" json:"password"`
Database int `yml:"database" json:"database"`
MaxIdle int `yml:"max_idle" json:"max_idle"`
MaxActive int `yml:"max_active" json:"max_active"`
IdleTimeout int `yml:"idle_timeout" json:"idle_timeout"` //second
}
//Init init
func Init(opts *Config) error {
if opts == nil {
opts = &Config{
Host: "127.0.0.1:6379",
Password: "",
Database: 0,
MaxIdle: 10,
MaxActive: 100,
IdleTimeout: 600,
}
}
pool = &redigo.Pool{
MaxActive: opts.MaxActive,
MaxIdle: opts.MaxIdle,
IdleTimeout: time.Second * time.Duration(opts.IdleTimeout),
Dial: func() (redigo.Conn, error) {
return redigo.Dial("tcp", opts.Host,
redigo.DialDatabase(opts.Database),
redigo.DialPassword(opts.Password),
)
},
TestOnBorrow: func(conn redigo.Conn, t time.Time) error {
if time.Since(t) < time.Minute {
return nil
}
_, err := conn.Do("PING")
return err
},
}
return nil
}
//GetBytes 获取一个字节数组值
func GetBytes(key *string) (*[]byte, error) {
conn := pool.Get()
defer conn.Close()
data, err := redigo.Bytes(conn.Do("GET", *key))
return &data, err
}
//Get 获取一个值
func Get(key string) interface{} {
conn := pool.Get()
defer conn.Close()
var data []byte
var err error
if data, err = redigo.Bytes(conn.Do("GET", key)); err != nil {
return nil
}
var reply interface{}
if err = json.Unmarshal(data, &reply); err != nil {
return nil
}
return reply
}
//Set 设置一个值
func Set(key string, val interface{}, timeout time.Duration) (err error) {
conn := pool.Get()
defer conn.Close()
var data []byte
if data, err = json.Marshal(val); err != nil {
return
}
_, err = conn.Do("SETEX", key, int64(timeout/time.Second), data)
return
}
//IsExist 判断key是否存在
func IsExist(key string) bool {
conn := pool.Get()
defer conn.Close()
a, _ := conn.Do("EXISTS", key)
i := a.(int64)
return i > 0
}
//Delete 删除
func Delete(key string) error {
conn := pool.Get()
defer conn.Close()
if _, err := conn.Do("DEL", key); err != nil {
return err
}
return nil
}
//Expire 失效时间配置
func Expire(key string, t int64) error {
conn := pool.Get()
defer conn.Close()
if _, err := conn.Do("expire", key, t); err != nil {
return err
}
return nil
}