|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132 |
- package redis_client
-
- import (
- "code.gitea.io/gitea/modules/labelmsg"
- "fmt"
- "github.com/gomodule/redigo/redis"
- "math"
- "strconv"
- "time"
- )
-
- func Setex(key, value string, timeout time.Duration) (bool, error) {
- redisClient := labelmsg.Get()
- defer redisClient.Close()
-
- seconds := int(math.Floor(timeout.Seconds()))
- reply, err := redisClient.Do("SETEX", key, seconds, value)
- if err != nil {
- return false, err
- }
- if reply != "OK" {
- return false, nil
- }
- return true, nil
-
- }
-
- func Setnx(key, value string, timeout time.Duration) (bool, error) {
- redisClient := labelmsg.Get()
- defer redisClient.Close()
-
- seconds := int(math.Floor(timeout.Seconds()))
- reply, err := redisClient.Do("SET", key, value, "NX", "EX", seconds)
- if err != nil {
- return false, err
- }
- if reply != "OK" {
- return false, nil
- }
- return true, nil
-
- }
-
- func Get(key string) (string, error) {
- redisClient := labelmsg.Get()
- defer redisClient.Close()
-
- reply, err := redisClient.Do("GET", key)
- if err != nil {
- return "", err
- }
- if reply == nil {
- return "", err
- }
- s, _ := redis.String(reply, nil)
- return s, nil
-
- }
-
- func Del(key string) (int, error) {
- redisClient := labelmsg.Get()
- defer redisClient.Close()
-
- reply, err := redisClient.Do("DEL", key)
- if err != nil {
- return 0, err
- }
- if reply == nil {
- return 0, err
- }
- s, _ := redis.Int(reply, nil)
- return s, nil
-
- }
-
- func TTL(key string) (int, error) {
- redisClient := labelmsg.Get()
- defer redisClient.Close()
-
- reply, err := redisClient.Do("TTL", key)
- if err != nil {
- return 0, err
- }
- n, _ := strconv.Atoi(fmt.Sprint(reply))
- return n, nil
-
- }
-
- func IncrBy(key string, n int64) (int64, error) {
- redisClient := labelmsg.Get()
- defer redisClient.Close()
-
- reply, err := redisClient.Do("INCRBY", key, n)
- if err != nil {
- return 0, err
- }
- i, err := strconv.ParseInt(fmt.Sprint(reply), 10, 64)
- return i, nil
-
- }
-
- func Expire(key string, expireSeconds int64) error {
- redisClient := labelmsg.Get()
- defer redisClient.Close()
-
- _, err := redisClient.Do("EXPIRE ", key, expireSeconds)
- if err != nil {
- return err
- }
- return nil
-
- }
-
- //GetInt64 get redis value by Get(key)
- //and then parse the value to int64
- //return {isExist(bool)} {value(int64)} {error(error)}
- func GetInt64(key string) (bool, int64, error) {
- str, err := Get(key)
- if err != nil {
- return false, 0, err
- }
- if str == "" {
- return false, 0, nil
- }
-
- i, err := strconv.ParseInt(str, 10, 64)
- if err != nil {
- return false, 0, err
- }
- return true, i, nil
-
- }
|