Spring 中线程池的原理

分类:N07_Java

标签:

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;

@Configuration
@EnableAsync // 1. 开启异步处理
public class AsyncPoolConfig {

    @Bean(name = "customTaskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);        // 核心线程数
        executor.setMaxPoolSize(10);        // 最大线程数
        executor.setQueueCapacity(100);     // 队列容量
        executor.setThreadNamePrefix("MyAsync-");
        executor.setKeepAliveSeconds(60);
        // 拒绝策略:如果线程池和队列都满了,由调用者线程执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}


import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncTaskService {

    // 3. 标记为异步方法,并指定使用自定义线程池
    @Async("customTaskExecutor")
    public void processReport(String reportId) {
        String threadName = Thread.currentThread().getName();
        System.out.println(threadName + " 开始处理报告: " + reportId);
        try {
            Thread.sleep(2000); // 模拟耗时任务
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(threadName + " 完成处理报告: " + reportId);
    }
}

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TaskController {

    @Autowired
    private AsyncTaskService asyncTaskService;

    @GetMapping("/process")
    public String submitTasks() {
        // 模拟同时来了15个报告处理请求
        for (int i = 1; i <= 15; i++) {
            String reportId = "Report-" + i;
            asyncTaskService.processReport(reportId);
        }
        return "所有报告已提交处理!";
    }
}


修改内容