You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
2.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package RedisUtil
import (
"dsBaseRpc/Const/ErrorConst"
"dsBaseRpc/Utils/ConfigUtil"
"dsBaseRpc/Utils/LogUtil"
"fmt"
"github.com/go-redis/redis/v7"
"time"
)
var (
// 定义redis链接池
RedisClient *redis.Client
)
func init() {
// 从配置文件获取redis的ip以及db
var redisHost = ConfigUtil.RedisIp + ":" + ConfigUtil.RedisPort
//这个是以后项目中广泛使用的redis池
RedisClient = redis.NewClient(&redis.Options{
Addr: redisHost, // Redis地址
Password: "", // Redis账号
DB: 0, // Redis库
DialTimeout: 10 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
PoolSize: 10,
PoolTimeout: 30 * time.Second,
IdleTimeout: time.Minute,
IdleCheckFrequency: 100 * time.Millisecond,
})
_, err := RedisClient.Ping().Result()
if err == redis.Nil {
LogUtil.Error(ErrorConst.CreateRedisError, "Redis异常")
} else if err != nil {
LogUtil.Error(ErrorConst.CreateRedisError, err.Error())
}
}
//======下面的代码由黄海增加于2020-02-18=============================================================
/**
功能:设置指定键值的过期时间
作者:黄海
时间2020-02-18
*/
func DEL(key string) {
RedisClient.Del(key)
}
/**
功能设置一个STRING形式的缓存
作者:黄海
时间2020-02-25
*/
func SET(key string, value string, ttl time.Duration) {
RedisClient.Set(key, value, ttl)
}
/**
功能:将指定的键值增加
*/
func IncrBy(key string, value int64) int64 {
c, err := RedisClient.IncrBy(key, value).Result()
if err != nil {
fmt.Println(err.Error())
}
return c
}
/**
功能获取指定的KEY值
作者:黄海
时间2020-02-25
*/
func GET(key string) (string, error) {
var r = RedisClient.Get(key)
if r.Err() != nil {
return "", r.Err()
} else {
return r.Result()
}
}
/**
功能:判断指定键值是否存在
作者:黄海
时间2021-09-16
*/
func Exist(key string) (bool, error) {
_, err := RedisClient.Get(key).Result()
if err == redis.Nil {
return false, nil
}
return true, nil
}