啊鑫
5 天以前 1f963e2344833ff02087c05411b112147492bd00
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.gs.xky.config;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
 
/**
 * 异步任务配置类
 * 配置专用线程池处理异步任务,避免阻塞Spring默认线程池
 */
@Configuration
@EnableAsync
public class AsyncConfig {
 
    private static final Logger log = LoggerFactory.getLogger(AsyncConfig.class);
 
    /**
     * 配置采购订单同步任务专用线程池
     * 使用有限的线程数,避免资源竞争
     */
    @Bean(name = "purchaseTaskExecutor")
    public Executor purchaseTaskExecutor() {
        log.info("创建采购订单同步任务专用线程池");
 
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数设置为1,确保同一时间只有一个采购同步任务在执行
        executor.setCorePoolSize(1);
        // 最大线程数设置为2,允许有限的并发
        executor.setMaxPoolSize(2);
        // 队列容量
        executor.setQueueCapacity(5);
        // 线程名称前缀
        executor.setThreadNamePrefix("purchase-task-");
        // 拒绝策略:当线程池已满时,调用者线程执行任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 等待时间(秒)
        executor.setAwaitTerminationSeconds(60);
        // 初始化线程池
        executor.initialize();
 
        return executor;
    }
 
    /**
     * 配置通用异步任务线程池
     * 用于处理其他轻量级异步任务
     */
    @Bean(name = "taskExecutor")
    public Executor taskExecutor() {
        log.info("创建通用异步任务线程池");
 
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数
        executor.setCorePoolSize(5);
        // 最大线程数
        executor.setMaxPoolSize(10);
        // 队列容量
        executor.setQueueCapacity(25);
        // 线程名称前缀
        executor.setThreadNamePrefix("async-task-");
        // 拒绝策略:当线程池已满时,调用者线程执行任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化线程池
        executor.initialize();
 
        return executor;
    }