基于Redis的限流器的实现(示例讲解)
1 概述
系统中的接口通常都有限流,比如 70次/秒 ,如何保证我们的接口的调用次数在超过第三方接口限流的时候快速失败呢?这时候就需要限流器了。下面是笔者用redis实现限流器的流程图。
2 代码
/** * 获取限流权限 * @param key * @param millisecond 毫秒数 * @param limitCount 限流次数 * @return */ public static boolean getCurrentLimiting(String key, Long millisecond, Integer limitCount){ try { boolean currentLimitingLock = RedisDistributeLockUtil.lock(key); if(currentLimitingLock){ Long llen = RedisClient.llen(getCurrentLimitingRedisKey(key)); if(llen < limitCount){ RedisClient.lpush(getCurrentLimitingRedisKey(key), DateUtil.current(false) + ""); return true; }else{ Long lastTime = Long.parseLong(RedisClient.lindex(getCurrentLimitingRedisKey(key), -1)); if((DateUtil.current(false) - lastTime) >= millisecond){ RedisClient.lpush(getCurrentLimitingRedisKey(key), DateUtil.current(false) + ""); RedisClient.ltrim(getCurrentLimitingRedisKey(key), 0, limitCount); return true; } } } }finally { RedisDistributeLockUtil.unlock(key); } return false; }
相关推荐
王道革 2020-11-25
wangdonghello 2020-11-03
Langeldep 2020-11-16
chenhualong0 2020-11-16
聚合室 2020-11-16
koushr 2020-11-12
MRFENGG 2020-11-11
guoyanga 2020-11-10
fackyou00 2020-11-10
Orangesss 2020-11-03
dongCSDN 2020-10-31
rainandtear 2020-10-30
Quietboy 2020-10-30
liuyulong 2020-10-29
fansili 2020-10-29
温攀峰 2020-10-23
jackbon 2020-10-19
kaixinfelix 2020-10-04