实际项目中,好多场景下,接口是需要做限流措施的,读者可能使用很多其他的方式或者组件来做限流措施,如Hystrix、sentinel、或者 gateway等等。但是redis也能做限流,本文先学习下redis的简单限流。
如项目中的一个功能,对顶用户在一分钟内访问不超过3次,用redis如何实现呢?
条件:
1. 一分钟。滑动的时间窗。
2. 次数不超过3次。
可以考虑使用zset类型,zset类型中有个score值可以用来排序和区间查询。对功能定义key:userId:controllerName:methodName,value、score均存当前时间戳。
简单限流思想逻辑:
1. 添加 key=userId:controllerName:methodName 、value=System.currentTimeMillis 、score=System.currentTimeMillis。
2. 根据score删除1min之外的value,key=userId:controllerName:methodName、score=System.currentTimeMillis-1*1000。
3. 通过zcard统计key对应值的数量。
4. 给key 添加过期时间
5. 判断第3步返回的count,看是否大于3,如果大于3,返回不执行以下逻辑,如果小于3,执行后面逻辑。
对应的代码逻辑如下:
//限流器
public void currentLimiter(){
List<Object> objects = redisTemplate.executePipelined(new RedisCallback<Long>() {
@Override
public Long doInRedis(RedisConnection connection) throws DataAccessException {
connection.openPipeline();
//key
String key = "userId:mucontroller:save";
//当前时间
Long time = System.currentTimeMillis();
//限定1min中内的请求
Long period = 1L;
//请求记录
connection.zSetCommands().zAdd(key.getBytes(), time, key.getBytes());
//删除1min之外的请求
connection.zSetCommands().zRemRangeByScore(key.getBytes(), 0.0, Double.valueOf(time - period * 1000));
//统计1min内的记录次数
Long size = connection.zSetCommands().zCard(key.getBytes());
//设置过期时间
connection.expire(key.getBytes(), period);
if(size > 3){
return 0L;
} else {
return 1L;
}
}
});
}
以上代码只是根据简单限流思想逻辑写出了业务流程,具体使用需要读者自己优化。