1 Star 0 Fork 0

rio / mouse-core

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
redis.go 2.18 KB
一键复制 编辑 原始数据 按行查看 历史
duanbin 提交于 2021-08-06 14:57 . update dir
package redis
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/go-redis/redis/v8"
"strings"
"time"
)
//document https://redis.uptrace.dev/
var (
rc *Client
)
type Client struct {
Host string
Password string
DB int
redisConn *redis.Client
}
type Option func(*Client)
func DB(db int) Option {
return func(c *Client) {
c.DB = db
}
}
func Password(password string) Option {
return func(c *Client) {
c.Password = password
}
}
// NewRedisClientPool Setup Initialize the Redis instance
func NewRedisClientPool(host string, options ...Option) (*Client, error) {
rc = &Client{
Host: host,
Password: "",
DB: 0,
}
for _, option := range options {
option(rc)
}
if rc.Host == "" {
return nil, errors.New("invalid host")
}
rdb := redis.NewClient(&redis.Options{
Addr: rc.Host,
Password: rc.Password, // no password set
DB: rc.DB, // use default DB
})
rc.redisConn = rdb
return rc, nil
}
func GetRedisClientPool() (*Client, error) {
if rc == nil {
return nil, errors.New("redis client not init")
}
return rc, nil
}
func (p *Client) Conn() *redis.Client {
return p.redisConn
}
// Set a key/value
func (p *Client) Set(key string, data interface{}, time time.Duration) error {
value, err := json.Marshal(data)
if err != nil {
return err
}
result, err := p.redisConn.Set(context.Background(), key, value, time).Result()
if err != nil {
return err
}
if strings.ToLower(result) == "ok" {
return nil
}
return errors.New(fmt.Sprintf("set key %s failed", key))
}
// Exists check a key
func (p *Client) Exists(key string) bool {
val, err := p.redisConn.Exists(context.Background(), key).Result()
if err != nil {
return false
}
if val == 1 {
return true
} else {
return false
}
}
// Get get a key
func (p *Client) Get(key string) (string, error) {
val, err := p.redisConn.Get(context.Background(), key).Result()
switch {
case err == redis.Nil:
return "", errors.New("key does not exist")
case err != nil:
return "", err
default:
fmt.Println(val)
return val, nil
}
}
// Delete delete a kye
func (p *Client) Delete(key string) (int64, error) {
return p.redisConn.Del(context.Background(), key).Result()
}
1
https://gitee.com/rio-studio/mouse-core.git
git@gitee.com:rio-studio/mouse-core.git
rio-studio
mouse-core
mouse-core
v0.0.11

搜索帮助

53164aa7 5694891 3bd8fe86 5694891