互联网产品接口离不开限流:尤其是高并发接口,今天我们分享一下,基于springboot 分享三种方案
一、基于redis 自增原理简单实现
@Autowired
StringRedisTemplate stringRedisTemplate;
/**
* 接口限流策略
*
*/
@Override
public boolean limitKey(HttpServletRequest request) throws UnknownHostException {
InetAddress address = InetAddress.getLocalHost();
String checkedToken = request.getHeader("ND-TOKEN");
Long uid = getUserid(checkedToken);
String hostAddress = address.getHostAddress();
String key = THROTTLE_KEY + hostAddress + "_" + uid + "_";
log.debug("validation start key:" + key);
String minKey = key + "min";
long minTimes = stringRedisTemplate.opsForValue().increment(minKey, 1);
if (minTimes <= 1) {
stringRedisTemplate.expire(minKey, 1, TimeUnit.MINUTES);
}
String hourKey = key + "hour";
long hourTimes = stringRedisTemplate.opsForValue().increment(hourKey, 1);
if (hourTimes <= 1) {
stringRedisTemplate.expire(hourKey, 1, TimeUnit.HOURS);
}
String dayKey = key + "day";
long dayTimes = stringRedisTemplate.opsForValue().increment(dayKey, 1);
if (dayTimes <= 1) {
stringRedisTemplate.expire(dayKey, 1, TimeUnit.DAYS);
}
if (minTimes > 10) {
throw new UnknownHostException();
}
if (hourTimes > 20) {
throw new UnknownHostException();
}
if (dayTimes > 50) {
throw new UnknownHo