123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- package limit
- import (
- "gd_auth_check/common.in/cache"
- "gd_auth_check/common.in/config"
- "github.com/go-redis/redis"
- "github.com/google/uuid"
- )
- const (
- releaseScript = `
- local ext = redis.call("exists", KEYS[1])
- if ext == 1 then
- local token_key = redis.call("get", KEYS[1])
- if token_key and #token_key > 0 then
- redis.call("hincrby", token_key, "used", -1)
- redis.call("del", KEYS[1])
- end
- elseif ext == 0 then
- local used = redis.call("hget", KEYS[2], "used")
- if used - 1 >= 0 then
- redis.call("hincrby", KEYS[2], "used", -1)
- end
- end`
- redisUsedTokenKey = "rate_limit:used_token:"
- )
- func getToken(from string) string {
- return uuid.New().String() + "-" + from
- }
- func getTokenfrom(token string) string {
- return token[len(token)-1:]
- }
- func storeToken(store *cache.RedisCache, pre, tokenKey, token string) {
- expire, _ := config.Conf.RateLimit.RescueTickerTime.Int64()
- _, _ = store.SetEx(redisUsedTokenKey+tokenKey+":"+token, expire, pre+tokenKey)
- }
- func releaseToken(store *cache.RedisCache, pre, tokenKey, token string) bool {
- _, err := store.Eval(releaseScript, []string{
- redisUsedTokenKey + tokenKey + ":" + token,
- pre + tokenKey,
- }, []string{})
- // err == redis.Nil -> success
- if err != redis.Nil {
- // 报错
- // TODO
- return false
- }
- return true
- }
|