token.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package limit
  2. import (
  3. "gd_auth_check/common.in/cache"
  4. "gd_auth_check/common.in/config"
  5. "github.com/go-redis/redis"
  6. "github.com/google/uuid"
  7. )
  8. const (
  9. releaseScript = `
  10. local ext = redis.call("exists", KEYS[1])
  11. if ext == 1 then
  12. local token_key = redis.call("get", KEYS[1])
  13. if token_key and #token_key > 0 then
  14. redis.call("hincrby", token_key, "used", -1)
  15. redis.call("del", KEYS[1])
  16. end
  17. elseif ext == 0 then
  18. local used = redis.call("hget", KEYS[2], "used")
  19. if used - 1 >= 0 then
  20. redis.call("hincrby", KEYS[2], "used", -1)
  21. end
  22. end`
  23. redisUsedTokenKey = "rate_limit:used_token:"
  24. )
  25. func getToken(from string) string {
  26. return uuid.New().String() + "-" + from
  27. }
  28. func getTokenfrom(token string) string {
  29. return token[len(token)-1:]
  30. }
  31. func storeToken(store *cache.RedisCache, pre, tokenKey, token string) {
  32. expire, _ := config.Conf.RateLimit.RescueTickerTime.Int64()
  33. _, _ = store.SetEx(redisUsedTokenKey+tokenKey+":"+token, expire, pre+tokenKey)
  34. }
  35. func releaseToken(store *cache.RedisCache, pre, tokenKey, token string) bool {
  36. _, err := store.Eval(releaseScript, []string{
  37. redisUsedTokenKey + tokenKey + ":" + token,
  38. pre + tokenKey,
  39. }, []string{})
  40. // err == redis.Nil -> success
  41. if err != redis.Nil {
  42. // 报错
  43. // TODO
  44. return false
  45. }
  46. return true
  47. }