声明:本文纯属个人随手笔记,如果对您有参考价值我十分开心,如果有存在错误,或者有更好的解决办法也麻烦您留言告诉我,大家共同成长,切勿恶言相。 欢迎加入资源共享QQ群:275343679,一起发现知识、了解知识、学习知识、分享知识。网站:www.itlantian.top
=======================================================================
SpringBoot 拦截器和自定义注解进行数据拦截
切面开关配置:
spring.aop.auto: true
spring.aop.proxy-target-class: true
1.实现代码如下:
- 控制层
package com.xxx.product.admin.controller.stocks;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @ClassName StockRedisController
* @Description
* @Author zhangs
* @Date 2018年10月9日 上午11:04:43
*/
@Controller
@RequestMapping("/stockRedis")
public class StockRedisController {
private static final Logger logger = LoggerFactory.getLogger(StockRedisController.class);
@StockAnnotation(modelName = "stockRedis", option = "test")
@RequestMapping("/test")
@ResponseBody
public String test(@RequestBody String param, HttpServletRequest request){
try {
logger.info("request start ..."+param);
Thread.sleep(1000L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.info("request end ..."+param);
return "OK";
}
}
- 定义注解
package com.xxx.common.stock.aop;
import java.lang.annotation.*;
//@Retention: 定义注解的保留策略,
@Retention(RetentionPolicy.RUNTIME)// 注解会在class字节码文件中存在,在运行时可以通过反射获取到
//@Target:定义注解的作用目标
@Target({ElementType.METHOD,ElementType.PARAMETER})// 方法和方法参数
@Inherited//说明子类可以继承父类中的该注解
@Documented//说明该注解将被包含在javadoc中
public @interface StockAnnotation {
/**
* 模块名字
*/
String modelName() default "";
/**
* 操作类型
*/
String option();
}
- 定义切面
package com.xxx.common.stock.interceptor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.xxx.common.stock.aop.StockAnnotation;
import com.xxx.common.utils.mapper.JsonMapper;
import com.xxx.product.stocks.domain.vo.StockPara;
import com.xxx.product.stocks.service.intf.StockService;
/**
* @ClassName StockUpdateAspect
* @Description
* @Author zhangs
* @Date 2018年10月26日 下午3:17:49
*/
@Aspect //将一个类定义为一格切面
@Component //标记切面类的处理优先级,i值越小,优先级别越高。ps:可以注解类,也可以注解到方法上
public class StockUpdateAspect {
private static final Logger logger = LoggerFactory.getLogger(StockUpdateAspect.class);
@Autowired
private StockService stockService;
/**
* 定义Pointcut,Pointcut的名称,此方法不能有返回值,该方法只是一个标示
*/
@Pointcut("@annotation(com.xxx.common.stock.aop.StockAnnotation)")
public void StockAspect (){
System.out.println("一个切入点");
}
/**
* 拦截执行体
* @param pjp
* @param stockAnnotation
* @return
* @throws Throwable
*/
@Around(value = "StockAspect() && @annotation(stockAnnotation)")
public Object doAround(ProceedingJoinPoint pjp, StockAnnotation stockAnnotation) throws Throwable {
Object result = null;
try {
logger.info("数据拦截 >> Name:{} >> Option:{} >> param:{}",stockAnnotation.modelName(),stockAnnotation.option(),Arrays.toString(pjp.getArgs()));
//接收到请求,记录请求内容
//ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
/*logger.info("IP: {} >> URI: {} >> HTTP_METHOD: {} >> CLASS_METHOD: {} >> ARGS: {}",request.getRemoteAddr() ,request.getRequestURI(),request.getMethod(),
pjp.getSignature().getDeclaringTypeName() + "_" + pjp.getSignature().getName(),Arrays.toString(pjp.getArgs()));*/
result =pjp.proceed();
//业务执行代码
String data=JsonMapper.toJsonString(pjp.getArgs()[0]);
logger.info("ARGS对象1:{}", data);
List<StockPara> stockList=new ArrayList<StockPara>();
StockPara stock=null;
String regex="(\"activeCode\":\"|\"goodsSid\":)(.*?)(\"|,|},|}|}]$)";//正则表达式
Matcher matcher = Pattern.compile(regex).matcher(data);
while (matcher.find()) {
logger.info("参数:{} >> 参数名:{} >> 参数值: {}",matcher.group(0),matcher.group(1),matcher.group(2));
stock=new StockPara();
String value=matcher.group(2);
if(!ObjectUtils.isEmpty(matcher.group(2))){
if(matcher.group(1).indexOf("activeCode")>0){
stock.setActiveCode(value);
}else if(matcher.group(1).indexOf("goodsSid")>0){
stock.setGoodsSid(Long.valueOf(value));
}
stockList.add(stock);
}
};
stockRedisService.synUpdateStockForRedis(stockList);
} catch (Exception e) {
// TODO: handle exception
logger.error("数据拦截 >> 模板名称:{} >> 操作类型:{} >> 异常:{}",stockAnnotation.modelName(),stockAnnotation.option(),e.toString());
}
return result;
}
}