java 接口防刷_java轻量级接口限流/防刷插件
簡介
call-limit提供接口限流、防刷的功能,插件基于spring開發,在應用應用的任何一個邏輯層皆可使用(web、service、dao),
插件支持單機應用下的限流和分布式應用的限流(分布式應用限流需要依賴redis),在簡單業務場景下插件可為大家提供輕量
無邏輯侵入的限流、防刷的支持。
maven坐標
top.xiemingmin
call-limit
1.0.1-SNAPSHOT
目前SNAPSHOT版本只能發布到第三方倉庫,如需使用請在maven配置中增加第三方repository
sonatype-nexus-snapshots
Sonatype Nexus Snapshots
https://oss.sonatype.org/content/repositories/snapshots/
用法
在項目中添加插件maven依賴
在spring xml配置中配置相關的bean
單機場景:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mm="http://www.xiemingmin.top/schema/mm"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.xiemingmin.top/schema/mm
http://www.xiemingmin.top/schema/mm.xsd">
分布式場景:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mm="http://www.xiemingmin.top/schema/mm"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.xiemingmin.top/schema/mm
http://www.xiemingmin.top/schema/mm.xsd">
3.實現用戶信息接口(top.xiemingmin.call.limit.intf.UserInfoSupport)
返回每個請求線程的用戶唯一標識,可使用請求的客戶端ip,插件中會調用次接口判斷是否同一用戶的請求。
ps:可將用戶信息放入ThreadLocal在此方法中直接取值
package com.xiemingmin.service;
import org.springframework.stereotype.Service;
import top.xiemingmin.call.limit.intf.UserInfoSupport;
@Service
public class UserInfoServiceImpl implements UserInfoSupport {
@Override
public String currentUserKey() {
return LoginContext.getUserId();
}
}
4.在需要限流或防刷的方法上添加top.xiemingmin.call.limit.annotation.CallLimit注解
參數說明:
time:單位時間內值允許調用1次
timeUnit:時間單位
onLimitException: 觸發限流拋出的異常
如下配置表示30秒內值允許調用一次
@GetMapping("/getPerson/{name}")
@CallLimit(time = 30, timeUnit = TimeUnit.SECONDS)
public Result> getPerson(@PathVariable String name){
return personService.findPersonByName(name);
}
效果
第一次調用(成功)
調用成功
第二次調用(被限制)
被限制
總結
以上是生活随笔為你收集整理的java 接口防刷_java轻量级接口限流/防刷插件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java queue源码_java源码解
- 下一篇: java打包维护_java打包详解