异步线程 延迟打印

This commit is contained in:
wangw 2025-09-30 14:43:49 +08:00
parent 6f0601c165
commit b1c6f85e46
2 changed files with 82 additions and 25 deletions

View File

@ -19,10 +19,13 @@ import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
/**
@ -37,6 +40,10 @@ public class PrintMqListener {
private MqLogService mqLogService;
@Resource
private FunUtil funUtil;
// 注入自定义线程池建议单独配置避免使用默认线程池
@Resource
private ThreadPoolTaskExecutor asyncExecutor;
@Lazy
@Resource
private PrinterHandler printerHandler;
@ -59,6 +66,12 @@ public class PrintMqListener {
@RabbitListener(queues = {"${spring.profiles.active}-" + RabbitConstants.Queue.ORDER_MACHINE_PRINT_QUEUE})
public void orderPrint(String req) {
// 使用异步线程池执行延迟任务不阻塞当前消费者线程
CompletableFuture.runAsync(() -> {
try {
// 延迟3秒处理
TimeUnit.SECONDS.sleep(3);
// 执行核心打印逻辑
invokeFun("orderPrint", "java.order", req, (data) -> {
JSONObject jsonObject = JSONObject.parseObject(data);
String orderId = jsonObject.getString("orderId");
@ -71,6 +84,15 @@ public class PrintMqListener {
return null;
}, RedisCst.getLockKey("orderPrint", orderId));
});
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
// 记录中断日志
log.warn("打印任务被中断req:{}", req, e);
} catch (Exception e) {
// 记录业务异常日志
log.error("打印任务处理失败req:{}", req, e);
}
}, asyncExecutor);
}
/**

View File

@ -0,0 +1,35 @@
package com.czg.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @author ww
* @description
*/
@Configuration
public class AsyncConfig {
@Bean
public ThreadPoolTaskExecutor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 核心线程数根据CPU核心数调整一般为CPU核心数 * 2
executor.setCorePoolSize(8);
// 最大线程数
executor.setMaxPoolSize(16);
// 队列容量
executor.setQueueCapacity(1000);
// 线程空闲时间
executor.setKeepAliveSeconds(60);
// 线程名称前缀
executor.setThreadNamePrefix("print-delay-");
// 拒绝策略当任务满时由提交任务的线程执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 初始化线程池
executor.initialize();
return executor;
}
}