redis操作
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.

107 lines
1.8 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. package redis
  2. import (
  3. "errors"
  4. "git.tetele.net/tgo/helper"
  5. redisdb "github.com/gomodule/redigo/redis"
  6. )
  7. //取值
  8. func GetString(key string) (string, error) {
  9. c := GetConn()
  10. str, err := redisdb.String(c.Do("get", key))
  11. CloseConn(c)
  12. return str, err
  13. }
  14. /*
  15. * 存值,
  16. * args,范围(key, value)(key, value,expire)
  17. * 2020/06/06
  18. */
  19. func Set(args ...interface{}) (string, error) {
  20. c := GetConn()
  21. if len(args) < 2 {
  22. return "", errors.New("参数错误,至少需两个参数")
  23. }
  24. var err error
  25. var reply interface{}
  26. if len(args) > 2 && helper.ToInt(args[2]) > 0 {
  27. reply, err = c.Do("SET", args[0], args[1], "EX", args[2]) //设置过期时间
  28. } else {
  29. reply, err = c.Do("SET", args[0], args[1])
  30. }
  31. CloseConn(c)
  32. if err != nil {
  33. return "", err
  34. }
  35. ret, err := redisdb.String(reply, err)
  36. return ret, err
  37. }
  38. /**
  39. * 删除key
  40. */
  41. func Del(key string) (int64, error) {
  42. c := GetConn()
  43. var err error
  44. var reply interface{}
  45. reply, err = c.Do("DEL", key)
  46. CloseConn(c)
  47. if err != nil {
  48. return 0, err
  49. }
  50. ret, err := redisdb.Int64(reply, err)
  51. return ret, err
  52. }
  53. /**
  54. * 设锁
  55. * 2020/01/15
  56. */
  57. func SetNx(args ...interface{}) (int64, error) {
  58. c := GetConn()
  59. if len(args) < 2 {
  60. return 0, errors.New("参数错误,至少需两个参数")
  61. }
  62. var err error
  63. var result interface{}
  64. if len(args) > 2 && helper.ToInt(args[2]) > 0 {
  65. result, err = c.Do("SET", args[0],args[1],"EX",args[2],"NX") //设置过期时间
  66. } else {
  67. result, err = c.Do("SETNX", args[0], args[1])
  68. }
  69. if err != nil {
  70. return 0, err
  71. }
  72. CloseConn(c)
  73. if helper.ToStr(result) == "OK"{
  74. return 1, nil
  75. }
  76. return 0,nil
  77. }
  78. /**
  79. * key是否存在
  80. */
  81. func Exists(key string) (int64, error) {
  82. c := GetConn()
  83. var err error
  84. var reply interface{}
  85. reply, err = c.Do("Exists", key)
  86. CloseConn(c)
  87. if err != nil {
  88. return 0, err
  89. }
  90. ret, err := redisdb.Int64(reply, err)
  91. return ret, err
  92. }