线程池定义 + 使用案例

发布于:2025-02-11 ⋅ 阅读:(48) ⋅ 点赞:(0)

定义线程池:

@Configuration
@EnableAsync
public class ExecutorConfig {

@Bean
public Executor asyncServiceExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    //配置核心线程数
    executor.setCorePoolSize(5);
    //配置最大线程数
    executor.setMaxPoolSize(10);
    //配置队列大小
    executor.setQueueCapacity(400);
    //配置线程池中的线程的名称前缀
    executor.setThreadNamePrefix("thread-");
    // rejection-policy:当pool已经达到max size的时候,如何处理新任务
    // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    //执行初始化
    executor.initialize();
    return executor;
}

}

============================

使用线程池案例:
@Async(“asyncServiceExecutor”)
@Override
public void executeProformaAsync(List invoiceHeadList,List invoiceHeadCommonList, List invoiceHead1010List, RedisLockEntity redisLockEntity, UserInfo userInfo) throws Exception {
String allMsg = “”;
String emailTitle = PROFORMA_SUCCESS_EMAIL_TITLE;
try {
/* 每个线程重新创建 shiro的 subject start*/
Subject subject = new Subject.Builder().buildSubject();
ThreadContext.bind(subject);
SecurityUtils.getSubject().login(new UsernamePasswordToken());
/* 每个线程重新创建 shiro的 subject end*/
SecurityUtils.getSubject().getSession().setAttribute(“userInfo”,userInfo);
LOG.info(“Async Email Session Id:” + JSON.toJSONString(SecurityUtils.getSubject().getSession().getId()));
LOG.info(“Async Email User Info:” + JSON.toJSONString(SecurityUtils.getSubject().getSession().getAttribute(“userInfo”)));
// 更新发票
invoiceHeadMapper.updateBatchInvoiceHead(invoiceHeadList);

        //调用xxx接口
        //通用类型
        iProforma.doLogic(ToolUtil.list2Map(invoiceHeadCommonList));

        //In-House-Part 类型
        iProforma.doLogic(ToolUtil.list2Map(invoiceHead1010List));


        List<String> errorMsg = ThreadLocalUtil.get().getFunctionList();
        StringBuilder msg = new StringBuilder();
        msg.append("The Proforma operation you just executed has completed successfully.");
        Set<String> successTriggerNos = getSuccessTriggerNos(invoiceHeadList, errorMsg);
        if (CollectionUtils.isNotEmpty(successTriggerNos)) {
            msg.append("The Trigger NO. list are ")
                    .append(successTriggerNos.stream().collect(Collectors.joining(",")))
                    .append(";");
        }
        if (CollectionUtils.isNotEmpty(errorMsg)) {
            msg.append("<br/> some errors:");
            for (String s : errorMsg) {
                msg.append("<br/>").append(s);
            }
        }
        allMsg = msg.toString();
    } catch (Exception e) {
        allMsg =  e.getMessage();
        MessageException messageException = new MessageException(e.getMessage(), null, ConstantEntity.ERROR_TYPE_PROFORMA);
        controllerAdice.messageExceptionHandler(messageException);
        emailTitle = PROFORMA_FAIL_EMAIL_TITLE;
    } finally {
        ThreadLocalUtil.get().getFunctionList().clear();
        invoiceHeadList.clear();
        invoiceHeadCommonList.clear();
        invoiceHead1010List.clear();
        // 发送邮件
        sendEmail(ConstantEntity.ERROR_TYPE_PROFORMA, allMsg, emailTitle, redisLockEntity,userInfo);
        ThreadContext.unbindSubject();
    }
}

网站公告

今日签到

点亮在社区的每一天
去签到