一、业务需求
最近做的项目录单时候总会出现重复生成单据的情况,遂计划要在控制层添加注解,在规定时间内,第二次请求过来的时候拦截,返回响应信息。
方案:采用SpringAop切面+自定义注解+redis
二、示例代码
(1)自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface LimitSubmit {
String key() ;
/**
* 默认 10s
*/
int limit() default 10;
/**
* 请求完成后 是否一直等待
* true则等待
* @return
*/
boolean needAllWait() default true;
}
(2)注解业务代码
@Component
@Aspect
public class LimitSubmitAspect {
@Resource
private RedisUtil redisUtil;
@Pointcut("@annotation(com.XXX.submitlimit.LimitSubmit)")
private void pointcut() {
System.out.println("我是一个切入点");
}
@Around("pointcut()")
public Object handleSubmit(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("---------------------------");
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
//获取注解信息
LimitSubmit limitSubmit = method.getAnnotation(LimitSubmit.class);
int submitTimeLimiter = limitSubmit.limit();
String redisKey = limitSubmit.key();
boolean needAllWait = limitSubmit.needAllWait();
String key = getRedisKey(joinPoint, redisKey);
Object result = redisUtil.get(key);
if (result != null) {
throw new CoreServiceException("请勿重复访问!");
}
redisUtil.set( key, "123456",submitTimeLimiter);
try {
Object proceed = joinPoint.proceed();
return proceed;
} catch (Throwable e){
throw e;
}finally {
if(!needAllWait) {
redisUtil.del(redisKey);
}
}
}
private String getRedisKey(ProceedingJoinPoint joinPoint ,String key ){
System.out.println("---------------------------");
if(key.contains("%s")) {
key = String.format(key, "123456");
}
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
String[] parameterNames = discoverer.getParameterNames(method);
if (parameterNames != null) {
for (int i=0; i < parameterNames.length; i++ ) {
String item = parameterNames[i];
if(key.contains("#"+item)){
key = key.replace("#"+item, joinPoint.getArgs()[i].toString());
}
}
}
return key.toString();
}
(3)控制层
@RequestMapping(value = "/test", method = {RequestMethod.GET})
@CrossOrigin
@ApiOperation(value = "测试",notes = "测试接口",response = RespResult.class)
@LimitSubmit(key = "testLimit:#orderId",needAllWait = true)
public RespResult testApi(@RequestParam(name = "orderId",defaultValue = "1374774774")String orderId) {
//commService.test(orderId);
redisUtil.set("cesy",orderId);
return RespResult.ok();
}
三、排查配置(重要)
<!-- 启用 aspectj 方式 AOP-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
如果该配置在你的项目里已经有了,但是还是不生效,那么需要检查你的配置是否像我的项目一样,采用的Spring.xm分开的配置
如果是分开的写的,就要根据你的需要,在哪个文件添加,我的需求是在controller层添加注解,处理提交重复的方案,所以我需要在springmvc.xml里面添加上面的配置;但是如果你是要在service层添加注解,就要在xxx-service.xml添加配置
然后测试成功
缓存也有了
四、注意事项
(1)启用 aspectj 方式 AOP 注意相应的代码要在对应的扫描包下面;比如自定义的注解放在扫描包的下面,否则也不生效;