go-redisの使用(ハッシュタイプデータ)
2806 ワード
package redisdb
import (
"fmt"
"github.com/go-redis/redis" // redis
"tbkt/config"
"tbkt/logger"
"time"
)
// redis
var client *redis.Client
// redis
func init(){
client = redis.NewClient(&redis.Options{
Addr: config.RedisAddr, // Redis
Password: config.RedisPwd, // Redis
DB: config.RedisDB, // Redis
PoolSize: config.PoolSize, // Redis
MaxRetries: 3, //
IdleTimeout: 10*time.Second, //
})
pong, err := client.Ping().Result()
if err == redis.Nil {
logger.Info("Redis ")
} else if err != nil {
logger.Info(" :", err)
} else {
logger.Info(pong)
}
}
// key hash field
func HashSet(key, field string, data interface{}) {
err := client.HSet(key, field, data)
if err != nil {
logger.Error("Redis HSet Error:", err)
}
}
// key hash field
func BatchHashSet(key string, fields map[string]interface{}) string {
val, err := client.HMSet(key, fields).Result()
if err != nil {
logger.Error("Redis HMSet Error:", err)
}
return val
}
// key hash
func HashGet(key, field string) string {
result := ""
val, err := client.HGet(key, field).Result()
if err == redis.Nil {
logger.Info("Key Doesn't Exists:", field)
return result
}else if err != nil {
logger.Info("Redis HGet Error:", err)
return result
}
return val
}
// key hash
func BatchHashGet(key string, fields ...string) map[string]interface{} {
resMap := make(map[string]interface{})
for _, field := range fields {
var result interface{}
val, err := client.HGet(key, fmt.Sprintf("%s", field)).Result()
if err == redis.Nil {
logger.Info("Key Doesn't Exists:", field)
resMap[field] = result
}else if err != nil {
logger.Info("Redis HMGet Error:", err)
resMap[field] = result
}
if val != "" {
resMap[field] = val
}else {
resMap[field] = result
}
}
return resMap
}
// ID
func Incr(key string) int {
val, err := client.Incr(key).Result()
if err != nil {
logger.Error("Redis Incr Error:", err)
}
return int(val)
}
//
func SetAdd(key, val string){
client.SAdd(key, val)
}
//
func SetGet(key string)[]string{
val, err := client.SMembers(key).Result()
if err != nil{
logger.Error("Redis SMembers Error:", err)
}
return val
}