在 一个项目中, 我看 到 了 使用 aop 来进行 记录日志, 可是有一个 项目 使用了 多线程 来记录日志。 所以就了解了一下 。 使用 多线程 记录日志 , 就是 所谓的 异步 延迟 记录日志, 可以 提高 项目的 性能和 响应速度。
可以参考: http://blog.youkuaiyun.com/liuchuanhong1/article/details/52042520
https://www.oschina.net/question/87799_11230
经过测试 确实是 可以 的, 这样 主线程可以不用 理会 aop的日志了,或者是 多线程的 情况了, 可以 直接 反应给前端。 同时 不要在 多线程里面 写其他 无关代码,因为 是 没有 事务控制的,而且 就算有事务控制,因为在多线程 也是没有用的。而且容易出现 事务无效的 问题。
在 使用的时候,如果我们 要在 多线程的执行代码里面 获取 spring 的 bean 常规的方式 是不可以的。 会爆错,提示 bean 对象 为 null 或者 application 对象为 null 的 。
可以参考: http://blog.youkuaiyun.com/jueshengtianya/article/details/47439983
package com.stylefeng.guns.core.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* Spring的ApplicationContext的持有者,可以用静态方法的方式获取spring容器中的bean
*
* @author fengshuonan
* @date 2016年11月27日 下午3:32:11
*/
@Component
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextHolder.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
assertApplicationContext();
return applicationContext;
}
/**
* 请尽量在 方法里面使用,否则容易报错
* @param beanName
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String beanName) {
assertApplicationContext();
return (T) applicationContext.getBean(beanName);
}
/**
* 请尽量在 方法里面使用,否则容易报错
* @param beanName
* @return
*/
public static <T> T getBean(Class<T> requiredType) {
assertApplicationContext();
return applicationContext.getBean(requiredType);
}
private static void assertApplicationContext() {
if (SpringContextHolder.applicationContext == null) {
throw new RuntimeException("applicaitonContext属性为null,请检查是否注入了SpringContextHolder!");
}
}
}
总结
在多线程的情况下, 尽量不要 使用事务。 特别在 特别重要的 业务里面, 更加不要随便 引入多线程。 1, 容易出现数据不一致性的情况。 2, 特别是 对于 引入了 第三方的 插件 ,框架的情况下, 就算 当前代码没有问题, 第三方插件和框架也 容易出现问题,,,因此 尽量避免使用多线程。