- 主页 > 生活百科 > >
接口限流还不太明白? 这篇文章可以看懂!( 二 )
这里我们实现的就是每秒产生的速率加上一个桶容量 。但是如何实现呢?这里有几个问题 。 需要保存什么数据在redis中?当前桶的容量,最新的请求时间 以什么数据结构存储?因为是针对接口限流,每个接口的业务逻辑不同,对并发的处理也是不同,因此要细化到每个接口的限流,此时我们选用HashMap的结构,hashKey是接口的唯一id,可以是请求的uri,里面的分别存储当前桶的容量和最新的请求时间 。 如何计算需要放令牌?根据redis保存的上次的请求时间和当前时间比较,如果相差大于的产生令牌的时间(陈某实现的是1秒)则再次产生令牌,此时的桶容量为当前令牌+产生的令牌 如何保证redis的原子性?保证redis的原子性,使用lua脚本即可解决 。 有了上述的几个问题,便能很容易的实现 。开撸1、lua脚本如下:
local ratelimit_info = redis.pcall('HMGET',KEYS[1],'last_time','current_token')local last_time = ratelimit_info[1]local current_token = tonumber(ratelimit_info[2])local max_token = tonumber(ARGV[1])local token_rate = tonumber(ARGV[2])local current_time = tonumber(ARGV[3])if current_token == nil thencurrent_token = max_tokenlast_time = current_timeelselocal past_time = current_time-last_timeif past_time>1000 thencurrent_token = current_token+token_ratelast_time = current_timeend## 防止溢出if current_token>max_token thencurrent_token = max_tokenlast_time = current_timeendendlocal result = 0if(current_token>0) thenresult = 1current_token = current_token-1last_time = current_timeendredis.call('HMSET',KEYS[1],'last_time',last_time,'current_token',current_token)return result - 调用lua脚本出四个参数,分别是接口方法唯一id,桶容量,每秒产生令牌的数量,当前请求的时间戳 。
【接口限流还不太明白? 这篇文章可以看懂!】2、 SpringBoot代码实现
- 采用Spring-data-redis实现lua脚本的执行 。
- Redis序列化配置:
/*** 重新注入模板*/@Bean(value = https://www.isolves.com/it/cxkf/bk/2020-06-12/"redisTemplate")@Primarypublic RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){RedisTemplate template = new RedisTemplate<>();template.setConnectionFactory(redisConnectionFactory);ObjectMApper objectMapper = new ObjectMapper();objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);//设置序列化方式,key设置string 方式,value设置成jsonStringRedisSerializer stringRedisSerializer = new StringRedisSerializer();Jackson2JsonRedisSerializer jsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);jsonRedisSerializer.setObjectMapper(objectMapper);template.setEnableDefaultSerializer(false);template.setKeySerializer(stringRedisSerializer);template.setHashKeySerializer(stringRedisSerializer);template.setValueSerializer(jsonRedisSerializer);template.setHashValueSerializer(jsonRedisSerializer);return template;}/** * @Description 限流工具类 * @Author CJB * @Date 2020/3/19 17:21 */public class RedisLimiterUtils {private static StringRedisTemplate stringRedisTemplate=ApplicationContextUtils.applicationContext.getBean(StringRedisTemplate.class);/*** lua脚本,限流*/private final static String TEXT="local ratelimit_info = redis.pcall('HMGET',KEYS[1],'last_time','current_token')n" +"local last_time = ratelimit_info[1]n" +"local current_token = tonumber(ratelimit_info[2])n" +"local max_token = tonumber(ARGV[1])n" +"local token_rate = tonumber(ARGV[2])n" +"local current_time = tonumber(ARGV[3])n" +"if current_token == nil thenn" +"current_token = max_tokenn" +"last_time = current_timen" +"elsen" +"local past_time = current_time-last_timen" +"n" +"if past_time>1000 thenn" +"tcurrent_token = current_token+token_raten" +"tlast_time = current_timen" +"endn" +"n" +"if current_token>max_token thenn" +"current_token = max_tokenn" +"tlast_time = current_timen" +"endn" +"endn" +"n" +"local result = 0n" +"if(current_token>0) thenn" +"result = 1n" +"current_token = current_token-1n" +"last_time = current_timen" +"endn" +"redis.call('HMSET',KEYS[1],'last_time',last_time,'current_token',current_token)n" +"return result";/*** 获取令牌* @param key 请求id* @param max 最大能同时承受多少的并发(桶容量)* @param rate每秒生成多少的令牌* @return 获取令牌返回true,没有获取返回false*/public static boolean tryAcquire(String key, int max,int rate) {List<String> keyList = new ArrayList<>(1);keyList.add(key);DefaultRedisScript<Long> script = new DefaultRedisScript<>();script.setResultType(Long.class);script.setScriptText(TEXT);return Long.valueOf(1).equals(stringRedisTemplate.execute(script,keyList,Integer.toString(max), Integer.toString(rate),Long.toString(System.currentTimeMillis())));}}
推荐阅读
-
农民工来手机店被女孩瞧不起,接下来农民工的做法让人竖起大拇指
-
『空间站』长征5B首发成功!新一代太空快递船露面,2年后送货直达空间站
-
-
《追风者2》提上日程,六大原班人马回归,宣璐、丁勇岱惊喜加盟
-
央视新闻|必须弹劾!美各界抨击司法部长包庇特朗普 破坏调查
-
「蝴蝶姐姐」37岁蝴蝶姐姐旧照被曝光,“进化史”比周扬青还精彩,罗志祥就好这一口?
-
旅游大视野 未来也一定要用,美国学者预测:即使现在美国不用中国这项技术
-
-
见到|李逵发疯六亲不认,见到这四个人,像个乖顺的小绵羊不敢主动招惹
-
钟楼|跑跑卡丁车高速公路宝藏位置 跑跑卡丁车高速公路宝藏在哪?
-
-
明星八卦|Baby演技首度得到认可,放飞自我后,终于找对戏路了
-
-
最热文■晒爱宠照片,拍猫遛鸟生活惬意,杨幂被传剧组解散后回家
-
-
『呱呱文史』我要给孩子买学区房,把你结婚借的钱还我!你找妈要去!,弟弟
-
电竞龙门阵|曾经888点券没人要,登顶T0后却成绝版,最升值的限定皮肤
-
梦幻西游|梦幻西游:梦幻西游毁人人生?买千亿机会领兽决把房子给搭进去了
-
-