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.

76 lines
1.4 KiB

3 years ago
  1. package redis
  2. import (
  3. "errors"
  4. redisdb "github.com/gomodule/redigo/redis"
  5. )
  6. //取值
  7. func Get(key string) (string, error) {
  8. c := pool.Get()
  9. defer c.Close()
  10. return redisdb.String(c.Do("get", key))
  11. }
  12. /*
  13. * 存值,
  14. * args,范围(key, value)(key, value,expire)
  15. * 2020/06/06
  16. */
  17. func Set(args ...interface{}) (interface{}, error) {
  18. c := pool.Get()
  19. defer c.Close()
  20. if len(args) < 2 {
  21. return nil, errors.New("参数错误,至少需两个参数")
  22. }
  23. var err error
  24. var reply interface{}
  25. if len(args) > 2 {
  26. reply, err = c.Do("SET", args[0], args[1], "EX", args[2]) //设置过期时间
  27. } else {
  28. reply, err = c.Do("SET", args[0], args[1])
  29. }
  30. return reply, err
  31. }
  32. /**
  33. * 删除key
  34. */
  35. func Del(key string) (int,error){
  36. c := pool.Get()
  37. defer c.Close()
  38. var err error
  39. var reply interface{}
  40. reply, err = c.Do("DEL", key)
  41. return redisdb.Int(reply, err)
  42. }
  43. /**
  44. * 设锁
  45. * 2020/01/15
  46. */
  47. func SetLock(args ...interface{}) (bool,error){
  48. c := pool.Get()
  49. defer c.Close()
  50. if len(args) < 2 {
  51. return false, errors.New("参数错误,至少需两个参数")
  52. }
  53. var err error
  54. var result interface{}
  55. if len(args) > 2 {
  56. result, err = c.Do("SETNX", args[0], args[1], "EX", args[2]) //设置过期时间
  57. } else {
  58. result, err = c.Do("SETNX", args[0], args[1])
  59. }
  60. if err != nil{
  61. return false,err
  62. }
  63. if result.(int) == 1{
  64. return true, nil
  65. } else{
  66. return false, nil
  67. }
  68. }