xuefei
2020-12-12 160487aedf89e2aea61f043c7a5c3d211ed19798
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package cn.cetc54.platform.core.common.limit;
 
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
 
import java.util.concurrent.TimeUnit;
 
/**
 * 令牌桶算法限流
 * @author Exrick
 */
@Slf4j
@Component
public class RedisRaterLimiter {
 
    @Autowired
    private StringRedisTemplate redisTemplate;
 
    public String acquireToken(String point, Integer limit, Long timeout) {
 
        String maxCountKey = "BUCKET:MAX_COUNT:" + point;
 
        String currCountKey = "BUCKET:CURR_COUNT:" + point;
 
        try {
            // 令牌值
            String token = "T";
            // 无效的限流值 返回token
            if(limit<=0||timeout<=0){
                return token;
            }
            // maxCount为主要判断标志
            String maxCount = redisTemplate.opsForValue().get(maxCountKey);
            String currCount = redisTemplate.opsForValue().get(currCountKey);
            // 初始
            if(StrUtil.isBlank(maxCount)){
                // 初始计数为1
                redisTemplate.opsForValue().set(currCountKey, "1", timeout, TimeUnit.MILLISECONDS);
                // 总数
                redisTemplate.opsForValue().set(maxCountKey, limit.toString(), timeout, TimeUnit.MILLISECONDS);
                return token;
            } else if (StrUtil.isNotBlank(maxCount)&&StrUtil.isNotBlank(currCount)){
                // 判断是否超过限制
                if(Integer.valueOf(currCount)<Integer.valueOf(maxCount)){
                    // 计数加1
                    redisTemplate.opsForValue().set(currCountKey, String.valueOf(Integer.valueOf(currCount)+1), timeout, TimeUnit.MILLISECONDS);
                    return token;
                }
            } else {
                // currCount变量先失效(几乎不可能) 返回token
                return token;
            }
        } catch (Exception e) {
            log.error("限流出错,请检查Redis运行状态\n"+e.toString());
        }
        return null;
    }
}