基于ssm项目自定义AOP注解实现限流步骤
具体操作步骤如下
第一步:定义自定义注解类
添加注解类 new Annotation
具体实现如下
@Target(value = ElementType.METHOD)
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
public @interface InterfaceCustom {
//可定义参数
}
第二步:定义切面类
添加切面类new Class
具体实现如下
@Pointcut("@annotation(com.thunisoft.zbjs.api.metadata.InterfaceCustom)")
public void controllerAspect() {
System.out.println("我是一个切入点");
}
@Around("controllerAspect()")
public Object before(ProceedingJoinPoint joinPoint) throws Throwable {
Object result = null;
try {
if(不满足限流条件){
//执行访问方法
result = joinPoint.proceed();
}else {
Map<String,Object> map = new HashMap<>();
result = map.put("error","请求太过频繁,请稍后重试!");
}
} catch (Throwable e) {
// 异常通知
result = Response.error("请求失败,服务器内部错误!");
throw new RuntimeException(e);
}
// 后置通知
return result;
}
第三步:在xml中配置aop
xml头的位置bean中添加aop配置
具体实现如下
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation最后面添加
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
//下面添加
<aop:aspectj-autoproxy proxy-target-class="true"/>
第四步:在需要的方法上添加注解(本人以controller中方法为例,其他雷同)
xml头的位置bean中添加aop配置
具体实现如下
@InterfaceCustom
@RequestMapping("/")
public Object getTest() {
Object o = null;
return o;
}