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.

80 lines
1.0 KiB

  1. package redis
  2. import (
  3. "errors"
  4. "strconv"
  5. redisdb "github.com/gomodule/redigo/redis"
  6. )
  7. //监视key递减
  8. func WatchSub(key, value string) (bool, error) {
  9. var err error
  10. c := GetConn()
  11. reply, err := c.Do("WATCH", key)
  12. if err != nil {
  13. c.Do("UNWATCH")
  14. return false, err
  15. }
  16. reply, err = c.Do("GET", key)
  17. if err != nil {
  18. c.Do("UNWATCH")
  19. return false, err
  20. }
  21. stock, err := redisdb.Int64(reply, err)
  22. if err != nil {
  23. c.Do("UNWATCH")
  24. return false, err
  25. }
  26. use, err := strconv.ParseInt(value, 10, 64)
  27. if err != nil {
  28. c.Do("UNWATCH")
  29. return false, err
  30. }
  31. if stock < use {
  32. c.Do("UNWATCH")
  33. return false, errors.New("数量已不足")
  34. }
  35. reply, err = c.Do("MULTI")
  36. if err != nil {
  37. c.Do("UNWATCH")
  38. return false, err
  39. }
  40. num := stock - use
  41. reply, err = c.Do("SET", key, num)
  42. if err != nil {
  43. c.Do("UNWATCH")
  44. return false, err
  45. }
  46. reply, err = c.Do("EXEC")
  47. c.Do("UNWATCH")
  48. CloseConn(c)
  49. if err != nil {
  50. return false, err
  51. }
  52. if reply != nil {
  53. return true, err
  54. }
  55. return false, err
  56. }