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

client.go 1.6 kB

3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package redis_client
  2. import (
  3. "code.gitea.io/gitea/modules/labelmsg"
  4. "fmt"
  5. "github.com/gomodule/redigo/redis"
  6. "math"
  7. "strconv"
  8. "time"
  9. )
  10. func Setex(key, value string, timeout time.Duration) (bool, error) {
  11. redisClient := labelmsg.Get()
  12. defer redisClient.Close()
  13. seconds := int(math.Floor(timeout.Seconds()))
  14. reply, err := redisClient.Do("SETEX", key, seconds, value)
  15. if err != nil {
  16. return false, err
  17. }
  18. if reply != "OK" {
  19. return false, nil
  20. }
  21. return true, nil
  22. }
  23. func Setnx(key, value string, timeout time.Duration) (bool, error) {
  24. redisClient := labelmsg.Get()
  25. defer redisClient.Close()
  26. seconds := int(math.Floor(timeout.Seconds()))
  27. reply, err := redisClient.Do("SET", key, value, "NX", "EX", seconds)
  28. if err != nil {
  29. return false, err
  30. }
  31. if reply != "OK" {
  32. return false, nil
  33. }
  34. return true, nil
  35. }
  36. func Get(key string) (string, error) {
  37. redisClient := labelmsg.Get()
  38. defer redisClient.Close()
  39. reply, err := redisClient.Do("GET", key)
  40. if err != nil {
  41. return "", err
  42. }
  43. if reply == nil {
  44. return "", err
  45. }
  46. s, _ := redis.String(reply, nil)
  47. return s, nil
  48. }
  49. func Del(key string) (int, error) {
  50. redisClient := labelmsg.Get()
  51. defer redisClient.Close()
  52. reply, err := redisClient.Do("DEL", key)
  53. if err != nil {
  54. return 0, err
  55. }
  56. if reply == nil {
  57. return 0, err
  58. }
  59. s, _ := redis.Int(reply, nil)
  60. return s, nil
  61. }
  62. func TTL(key string) (int, error) {
  63. redisClient := labelmsg.Get()
  64. defer redisClient.Close()
  65. reply, err := redisClient.Do("TTL", key)
  66. if err != nil {
  67. return 0, err
  68. }
  69. n, _ := strconv.Atoi(fmt.Sprint(reply))
  70. return n, nil
  71. }