項目在運行時期,訪問時會因爲網絡卡頓等原因造成重複點擊,多次提交的問題。
嘗試在前端做過限制,之後覺得使用redis 更爲簡單。
1. redis 可以 設置過期時間,符合需求
2.使用spring aop,只需要配置第一次,之後不需要更改
實現思路,用戶10秒內不能執行第二次新增方法,以用戶ID 作爲 key。
AOP
@Aspect
@Component
public class FlowRateLimit {
@Resource(name="RedisServiceImpl")
private RedisService redisService;
//配置哪些方法需要攔截
public static final String POINT = "execution (* com.sub.serviceimpl.ProcessSaveStartServiceImpl.*(..))";
@Before(POINT)
public void saveLimit(JoinPoint point) {
String key = GlobalConstant.RedisTool.SAVELIMIT + SessionContext.get().getAd_user_id();
String s = redisService.get(key);
//查詢redis 中是否存在此key 無則添加,有則拋出異常
if (StringUtils.isBlank(s)){
redisService.addIncludeTime(key, GlobalConstant.RedisTool.INITIALVALUE,10);
}else {
throw new MyException("操作頻率過快");
}
}
}
redis
@Resource(name="redisTemplate")
private RedisTemplate redisTemplate;
@Override
public void add(String key, String value) {
redisTemplate.opsForValue().set(key,value);
}
@Override
public void addIncludeTime(String key, String value, Integer time) {
redisTemplate.opsForValue().set(key,value,time, TimeUnit.SECONDS);
}
@Override
public String get(String key) {
String s = null;
try {
s = (String) redisTemplate.opsForValue().get(key);
}catch (Exception e){
e.printStackTrace();
}
return s;
}