上代码,单服务器可以用本地缓存:
/**
* @author changwensong
* @data 2019/11/6 0006 -上午 11:47
* TODO 自定义重复提交注解
*/
@Inherited
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LocalLock {
String key() default "";
//过期时间,使用本地缓存可以忽略,如果使用redis做缓存就需要
int expire() default 5;
}
package com.chunxiao.sportsbureau.config.customComment;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
/**
* @author changwensong
* @data 2019/11/6 0006 -上午 11:50
* 防止用户重复提交 实现本地锁
*/
@Aspect
@Configuration
public class LockMethodInterceptor{
//定义缓存,设置最大缓存数及过期日期
private static final Cache<String,Object> CACHE = CacheBuilder.newBuilder().maximumSize(1000).expireAfterWrite(20, TimeUnit.SECONDS).build();
@Around("execution(public * *(..)) && @annotation(com.chunxiao.sportsbureau.config.customComment.LocalLock)")
public Object interceptor(ProceedingJoinPoint joinPoint){
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
LocalLock localLock = method.getAnnotation(LocalLock.class);
String key = getKey(localLock.key(),joinPoint.getArgs());
if(!StringUtils.isEmpty(key)){
if(CACHE.getIfPresent(key) != null){
throw new RuntimeException("请勿重复请求!");
}
CACHE.put(key,key);
}
try{
return joinPoint.proceed();
}catch (Throwable throwable){
throw new RuntimeException("服务器异常");
}finally {
}
}
private String getKey(String keyExpress, Object[] args){
for (int i = 0; i < args.length; i++) {
keyExpress = keyExpress.replace("arg[" + i + "]", args[i].toString());
}
return keyExpress;
}
}
用:controller 接口上 加 @LocalLock(key = "localLock:test:arg[0]")
分布式可用redis缓存,未测试网上找的:
import java.lang.annotation.*;
@Inherited
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SameUrlData {
/**
* 接口限制时间
* @return
*/
long value() default 1000;
}
import com.alibaba.fastjson.JSONObject;
import com.twomantech.caiyuan.common.annotation.SameUrlData;
import com.twomantech.caiyuan.common.enums.ResultCode;
import com.twomantech.caiyuan.common.service.impl.RedisServiceImpl;
import com.twomantech.caiyuan.common.utils.ResultMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
/**
* @Title: 防止用户重复提交数据拦截器
* @Description: 将用户访问的uri和参数结合token存入redis,每次访问进行验证是否重复请求接口
*/
@Component
public class SameUrlDataInterceptor extends HandlerInterceptorAdapter {
private static Logger LOG = LoggerFactory.getLogger(SameUrlDataInterceptor.class);
private static RedisServiceImpl redisServiceImpl;
/**
* 是否阻止提交,fasle阻止,true放行
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
SameUrlData annotation = method.getAnnotation(SameUrlData.class);
if (annotation != null) {
if(repeatDataValidator(request,annotation.value())){
//请求数据相同
LOG.warn("please don't repeat submit,url:"+ request.getServletPath());
JSONObject result = new JSONObject();
result.put("statusCode","500");
result.put("message","请勿重复请求");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
response.getWriter().write(result.toString());
response.getWriter().close();
return false;
}else {
//如果不是重复相同数据
return true;
}
}
return true;
} else {
return super.preHandle(request, response, handler);
}
}
/**
* 验证同一个url数据是否相同提交,相同返回true
*/
public boolean repeatDataValidator(HttpServletRequest request, long time){
if(redisServiceImpl == null){
WebApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
redisServiceImpl = applicationContext.getBean(RedisServiceImpl.class);
}
String redisKey = request.getRequestURI() + request.getHeader("token");
String preUrlParams = redisServiceImpl.get(redisKey);
if(StringUtils.isBlank(preUrlParams)){
//如果上一个数据为null,表示还没有请求
redisServiceImpl.set(redisKey,"yes",time,TimeUnit.MILLISECONDS);
return false;
}else{
//否则,已经有过请求
return true;
}
}
}
拦截器
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new SameUrlDataInterceptor());//添加防止重复提交拦截器
}
}
用法 :
在防止重复请求的方法上加 @SameUrlData(毫秒值)