YouChuKoffee/app/utils/redis/redis.go

54 lines
1.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package redis
import (
"context"
"fmt"
"github.com/qit-team/snow-core/redis"
"time"
)
// AcquireLock 尝试获取分布式锁
func AcquireLock(key string, expired time.Duration) (bool, error) {
ctx := context.Background()
client := redis.GetRedis()
// 设置锁的值这里可以是一个随机的UUID用于检测是否是同一个客户端持有的锁锁
lockValue := fmt.Sprintf("%d", time.Now().UnixNano())
result := client.SetNX(ctx, key, lockValue, expired)
return result.Val(), result.Err()
}
func Del(key string) error {
client := redis.GetRedis()
result := client.Del(context.Background(), key)
return result.Err()
}
func Set(key string, value interface{}, expired time.Duration) error {
client := redis.GetRedis()
return client.Set(context.Background(), key, value, expired).Err()
}
func Get(key string) (string, error) {
client := redis.GetRedis()
result := client.Get(context.Background(), key)
return result.Result()
}
func Decr(key string) (int64, error) {
client := redis.GetRedis()
result := client.Decr(context.Background(), key)
return result.Result()
}
func Incr(key string) (int64, error) {
client := redis.GetRedis()
result := client.Incr(context.Background(), key)
return result.Result()
}
func SetNX(key string, value interface{}, expired time.Duration) (bool, error) {
client := redis.GetRedis()
result := client.SetNX(context.Background(), key, value, expired)
return result.Result()
}