基於spring boot 2.0.2利用redis實現多主機共享QPS工具類DEMO
網上有很多實現qps的方法,因爲樓主的項目採用的是微服務架構,系統中要請求第三方接口,第三方對同一個key有qps限制,故樓主採用redis來實現多個服務的總請求qps限制。網上相關代碼很多,但基本都經不住測試。故樓主將自己生產上使用的qps限制工具類貼出來,供大家參考學習。如有漏洞,希望大家及時指出。不勝感激!
public class QPS{
@Autowired
private StringRedisTemplate template;
public Object incr(String key){
if(template.opsForValue().setIfAbsent("qps","1")){
template.expire("qps",1,TimeUnit.SECONDS);
}
Long qps = template.opsForValue().increment("qps", 1);
//qps都是從2開始的,如果qps爲1,說明該key是increment時新建的,不是set建的,所以沒有指定過期時間,要重新指定過期時間
if (qps == 1){
template.expire("qps",1,TimeUnit.SECONDS);
}
if (qps > 1000){
try{
//如果qps超過閾值1000,則等待100ms重試。這塊業務代碼可以自己實現。
Thread.sleep(100);
incr(key);
}catch (InterruptedException e){
e.printStackTrace();
}
}
//到了這一步說明qps沒有超限,可以添加自己的業務邏輯。
return template.opsForValue().get("qps");
}
}