代码拉取完成,页面将自动刷新
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()
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。