Spring 在有事务的方法上使用日志切面

Extents:https://blog.csdn.net/lr131425/article/details/77567827

问题描述,在servic事务方法中记录日志时候,在方法上加上自定义日志注解横切面,日志切面使用Around环绕通知记录日志

事务配置都是正确配置,当去除@MethodLog日志注解时候,事务是可以正常回滚的

如果加上日志注解@MethodLog事务会失效,不回滚。

自定义注解

@Target({ElementType.METHOD, ElementType.TYPE })  
@Retention(RetentionPolicy.RUNTIME)  
@Documented
public @interface MethodLog {
    String module();
    String funtion();
}

service类

@Service
public class UserServiceImpl implements UserService{
 
    @Autowired
    private UserMapper userMapper;
    
    @MethodLog(module="用户",funtion="添加用户")
    @Transactional
    @Override
    public void insert123(User user) throws Exception {
        // TODO Auto-generated method stub
        userMapper.insert(user);
        throw new NullPointerException("nullpoint exception!!!!!");
        
    }
    }

切面实现类

package com.kerry.aop;
 
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
 
import javax.servlet.http.HttpServletRequest;
 
import org.apache.log4j.Logger;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
 
import com.kerry.model.AppLog;
import com.kerry.service.AppLogService;
 
 
 
/**
 * 用户操作日志管理
 * @author lenovo
 */
@Component
@Aspect
public class AppLogAdvice {
    private Logger log=Logger.getLogger(AppLogAdvice.class);
    
    @Autowired
    private AppLogService logService;
 
    
    private NamedThreadLocal  startTimeThreadLocal =new NamedThreadLocal("StopWatch-StartTime");
    
    @Pointcut("@annotation(com.kerry.aop.MethodLog)")
    private void pointcut() {}
    
    
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        AppLog logEntity=new AppLog();
        long beginTime = System.currentTimeMillis();//1、开始时间
        startTimeThreadLocal.set(beginTime);//线程绑定变量(该数据只有当前请求的线程可见)
        logEntity.setId(UUID.randomUUID().toString().replace("-", ""));
        ServletRequestAttributes attributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attributes.getRequest();
        
        StringBuffer paramStr=new StringBuffer();
        Enumeration nameList=request.getParameterNames();
        while(nameList.hasMoreElements()){
            String name = nameList.nextElement();
            paramStr.append(name).append("=").append(request.getParameter(name)).append("&");
        }
        Map map = getMethodLog(point);  
        logEntity.setPath(request.getRequestURI());
        if(paramStr.length()>0){
            logEntity.setParam(paramStr.substring(0,paramStr.length()-1));
        }
        logEntity.setModule(map.get("module"));
        logEntity.setFunction(map.get("function"));
        Object object = null;
        try{
            object=point.proceed();
            logEntity.setStatus("0");
            logEntity.setRemark("成功");
            return object;
        }catch(Exception e){
            e.printStackTrace();
            logEntity.setStatus("1");
            logEntity.setRemark("程序出异常");
            if(e!=null){
                logEntity.setException(getExceptionTrace(e));
            }
        }finally{
            long endTime = System.currentTimeMillis();//1结束时间
            long time=endTime-startTimeThreadLocal.get();
            logEntity.setConsumeTime(String.valueOf(time));
            log.info("Msg:开始写入日志...");
            logService.addAppLog(logEntity);
            log.info("Msg:日志写入结束");
        }
        return object;
    }
    
    /**
     * 获取日志注解标注信息  
     * @param joinPoint
     * @return
     * @throws Exception
     */
    public static Map getMethodLog(ProceedingJoinPoint joinPoint)  
            throws Exception {
        Map map=new HashMap();
        String targetName = joinPoint.getTarget().getClass().getName();  
        String methodName = joinPoint.getSignature().getName();  
        
        @SuppressWarnings("rawtypes")
        Class targetClass = Class.forName(targetName);  
        Method[] method = targetClass.getMethods();  
        for (Method m : method) {  
            if (m.getName().equals(methodName)) {  
                MethodLog methodCache = m.getAnnotation(MethodLog.class);  
                if (methodCache != null) {  
                    map.put("module", methodCache.module());  
                    map.put("function", methodCache.funtion());
                }  
                break;  
            }  
        }  
        return map;  
    }  
    /**
     * 获取异常信息
     * @param e
     * @return
     */
    public static String getExceptionTrace(Throwable e){
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        pw.flush();
        pw.close();
        return sw.toString();
    }
}



当调用userServiceImpl中事务方法 insert123(User user)时候,,方法中抛出异常按照spring事务管理会回滚事务

但是,事务方法上也注解自定义的日志注解,此时会发现 方法中insert语句成功插入数据库,而且切面中的日志也成功插入数据库,

而我们要的是 当事务方法异常时候,应该会回滚事务, 日志切面不管事务方法是否异常都要记录日志

思考:一个事务方法上有多个切面横切,会导致事务失效?? 自定义切面影响了spring事务的切面?

解决思路: 是不是自定义切面中try catch了事务方法的exception, 删除 AppLogAdvice 的around方法的try catch 语句试试

注释掉try catch finally 语句块

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        AppLog logEntity=new AppLog();
        long beginTime = System.currentTimeMillis();//1、开始时间
        startTimeThreadLocal.set(beginTime);//线程绑定变量(该数据只有当前请求的线程可见)
        logEntity.setId(UUID.randomUUID().toString().replace("-", ""));
        ServletRequestAttributes attributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attributes.getRequest();
        
        StringBuffer paramStr=new StringBuffer();
        Enumeration nameList=request.getParameterNames();
        while(nameList.hasMoreElements()){
            String name = nameList.nextElement();
            paramStr.append(name).append("=").append(request.getParameter(name)).append("&");
        }
        Map map = getMethodLog(point);  
        logEntity.setPath(request.getRequestURI());
        if(paramStr.length()>0){
            logEntity.setParam(paramStr.substring(0,paramStr.length()-1));
        }
        logEntity.setModule(map.get("module"));
        logEntity.setFunction(map.get("function"));
        Object object = null;
//        try{
            object=point.proceed();
            logEntity.setStatus("0");
            logEntity.setRemark("成功");
//          return object;
//        }catch(Exception e){
//          e.printStackTrace();
//          logEntity.setStatus("1");
//          logEntity.setRemark("程序出异常");
//          if(e!=null){
//              logEntity.setException(getExceptionTrace(e));
//          }
//        }finally{
            long endTime = System.currentTimeMillis();//1结束时间
            long time=endTime-startTimeThreadLocal.get();
            logEntity.setConsumeTime(String.valueOf(time));
            log.info("Msg:开始写入日志...");
            logService.addAppLog(logEntity);
            log.info("Msg:日志写入结束");
//      }
        return object;
    }

执行结果: user,和log 数据都被回滚了?
为什么都被回滚了? 难道是spring事务传播 导致的, 而我们logService方法并没有开启事务 为何?

@Service
public class AppLogServiceImpl implements AppLogService{
    private Logger log=Logger.getLogger(AppLogServiceImpl.class);
    
    @Autowired
    private AppLogDao dao;
 
    public void addAppLog(AppLog logEntity) {
        log.info("写入日志");
        dao.addAppLog(logEntity);
    }
}

实验试试,在addApplog上加入不支持事务或者强制新启一个事务

@Transactional(propagation=Propagation.REQUIRES_NEW)
    public void addAppLog(AppLog logEntity) {
 
@Transactional(propagation=Propagation.NOT_SUPPORTED)
    public void addAppLog(AppLog logEntity) {

结果,user,log数据还是都会被回滚, 但是我们想要的是log日志不要被回滚。
为啥log日志也被回滚

统计下以上测试结果,, 如果around通知中,有try catch掉service 的执行方法,会发现 事务失效不会回滚, 去掉try catch 事务会回滚,但是日志记录也被回滚了

发现不对为啥日志会被回滚,也不是事务传播属性导致的,到底是啥的,,接着看了下控制台日志,发现原来当去除 try catch 块时候,切面中执行到 object=point.proceed(); 这里的时候,就会抛出异常, 这句代码下面的日志记录不会被执行的,所以日志代码那压根就没执行,所以没记录入库。

综合统计以上:去除自定义日志的try catch事务会回滚, 也就是在自定义切面的时候,不能try catch 执行的事务方法,

问题:业务中就要这么干啊,不管事务方法是否异常都要执行日志记录。

回到上面,在日志切面实现类中放开around方法中的try catch 语句块,寻找为啥事务没生效,没回滚原因。

猜想:是不是切面执行顺序问题,一个类被多个切面横切,那个先执行,那个后执行或者是交替执行?

继续测试

around环绕通知, 此时通知又try catch掉service执行代码 ,控制台记录:


2017-08-25 14:08:40.160  INFO 4068 --- [nio-8080-exec-1] com.kerry.aop.AppLogAdvice               : AppLogAdvice Exception...... 
2017-08-25 14:08:40.161  INFO 4068 --- [nio-8080-exec-1] com.kerry.aop.AppLogAdvice               : Msg:开始写入日志...
2017-08-25 14:08:40.171  INFO 4068 --- [nio-8080-exec-1] c.kerry.service.impl.AppLogServiceImpl   : 写入日志
2017-08-25 14:08:40.174  INFO 4068 --- [nio-8080-exec-1] com.kerry.aop.AppLogAdvice               : Msg:日志写入结束

应该执行的service内的方法后在执行切面类的 ,所以顺序是先执行的事务切面,再是自定义日志切面
此时我们手动改变下顺序, 使用@order注解日志切面

@Component
@Aspect
@Order(0)
public class AppLogAdvice {

测试日志 
2017-08-25 14:17:04.595  INFO 4068 --- [nio-8080-exec-1] com.kerry.aop.AppLogAdvice               : AppLogAdvice Exception...... 
2017-08-25 14:17:04.596  INFO 4068 --- [nio-8080-exec-1] com.kerry.aop.AppLogAdvice               : Msg:开始写入日志...
2017-08-25 14:17:04.604  INFO 4068 --- [nio-8080-exec-1] c.kerry.service.impl.AppLogServiceImpl   : 写入日志
2017-08-25 14:17:04.606  INFO 4068 --- [nio-8080-exec-1] com.kerry.aop.AppLogAdvice               : Msg:日志写入结束
null
org.springframework.transaction.UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:724)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:487)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:291)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy235.insert123(Unknown Source)
    at com.kerry.web.UserController.save(UserController.java:43)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:89)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Transaction rolled back because it has been marked as rollback-only
2017-08-25 14:17:04.694  WARN 4068 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.transaction.UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only

通过以上日志我们发现先执行的日志切面,再执行的service方法。
查看数据库发现 user 和 log 都被回滚了,日志显示事务会回滚了, 但是为毛把log也回滚了? 事务传播搞的鬼?
为了验证猜想,那就继续更改spring事务传播属性,更改日志记录的service方法

@Transactional(propagation=Propagation.NOT_SUPPORTED)
    public void addAppLog(AppLog logEntity) {
        log.info("写入日志");
        dao.addAppLog(logEntity);
    }

设置为不支持事务
测试结果 通过, user插入失败,日志插入成功 ,

接着测试,写入日志不使用上面的service ,新起一个thread类,插入日志

public class LogThread extends Thread {
    
    
    private AppLogService logService;
    private AppLog log;
 
    public LogThread(AppLogService logService,AppLog log) {
        this.logService = logService;
        this.log = log;
    }
 
    @Override
    public void run() {
        logService.addAppLog(log);
    }

切面类插入日志更改成新启线程插入,同时去除logService.addAppLog方法上设置的事务

    }finally{
            long endTime = System.currentTimeMillis();//1结束时间
            long time=endTime-startTimeThreadLocal.get();
            logEntity.setConsumeTime(String.valueOf(time));
            log.info("Msg:开始写入日志...");
//          logService.addAppLog(logEntity);
            new LogThread(logService, logEntity).start();
            log.info("Msg:日志写入结束");
        }

测试结果发现, user插入失败, log插入成功 符合预期结果

此时可以确定应该是事务传播引起的导致user,和log都回滚了。 当分来开不同事务线程 就可以得到正确答案。

综上所述: 在使用事务切面的方法上使用自定义切面 并且使用around环绕通知时候, 当try catch掉被执行事务方法时候,事务会失效,

解决方法

方法1 : 不要try catch 被执行事务方法

方法2 : springmvc 中使用try catch,但是设置自定义切面执行顺序更 高优先级

如: spring mvc中 被切面类

@Component
@Aspect
@Order(0)
public class AppLogAdvice {

注解事务设置 order(2)


    

方法3 springboot中,使用try catch 的 around方法时候 ,除了要设置自定义切面的优选顺序高还得设置 日志插入的方法不支持事务或者自己强制新启一个事务


@Component
@Aspect
@Order(0)
public class AppLogAdvice {

//@Transactional(propagation=Propagation.NOT_SUPPORTED)
    @Transactional(propagation=Propagation.REQUIRES_NEW)
    public void addAppLog(AppLog logEntity) {
        log.info("写入日志");
        dao.addAppLog(logEntity);
    }

或者 使用新建Thread类处理插入日志

        log.info("Msg:开始写入日志...");
//          logService.addAppLog(logEntity);
            new LogThread(logService, logEntity).start();
            log.info("Msg:日志写入结束");

你可能感兴趣的:(Spring 在有事务的方法上使用日志切面)