项目解析-spring异步线程池配置与使用

时间:2022-05-20 18:30:46


一、Spring配置

实际项目简单配置

<bean
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="10" />
<property name="maxPoolSize" value="10" />
<property name="queueCapacity" value="1000" />
</bean>

较完整参考

<!-- 异步线程池 -->  
<bean id="threadPool" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<!-- 核心线程数 -->
<property name="corePoolSize" value="3" />
<!-- 最大线程数 -->
<property name="maxPoolSize" value="20" />
<!-- 队列最大长度 >=mainExecutor.maxSize -->
<property name="queueCapacity" value="1000" />
<!-- 线程池维护线程所允许的空闲时间 -->
<property name="keepAliveSeconds" value="300" />
<!-- 线程池对拒绝任务(无线程可用)的处理策略 -->
<property name="rejectedExecutionHandler">
<bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
</property>
</bean>

二、Service中注入

    @Autowired
protected ThreadPoolTaskExecutor taskExecutor;

三、service中方法使用

项目中用来异步记log

public void doSomething(){
threadPool.execute(new Runnable() {

@Override
public void run() {
//异步执行耗时的业务任务
}
});
}
@Transactional    public void logBomInfo(final int loggingKey, final String appId,            final Object bom) {        try {            taskExecutor.execute(new Runnable() {                @Override                public void run() {                    try {                        LogBomInfo logBomInfo = new LogBomInfo();                        logBomInfo.setBomInfoId(loggingKey);                        logBomInfo.setAppId(appId);                        logBomInfo.setBom(jsonMapper.writeValueAsString(bom));                        logBomInfo.setBizkey(getBomBizKey(bom));                        logBomInfoDAO.insertLogBomInfo(logBomInfo);                        if (logger.isDebugEnabled()) {                            logger.debug("保存日志成功, bomInfoId:" + loggingKey);                        }                    } catch (Exception ex) {                        logger.error("保存日志发生错误", ex);                    }                }            });        } catch (Exception ex) {            logger.error("写入日志表失败", ex);        }    }