Springmvc线程池配置和使用

1.Springmvc线程池配置:

在spring上下文文件ApplicationContext.xml中添加

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

 

2.线程池的使用:

在需要调用的业务service调用线程

1)先定义引用

@Autowired
    private ThreadPoolTaskExecutor taskExecutor;

2)我这边操作的业务是给图片压缩 (这里的picList是图片集合,这里当参数传给线程类)

 

 private void uploadPic(){
	//图片集合
	List<String> picList=new ArrayList<String>();
	//上传图片业务逻辑
	...
	 //处理压缩图片任务
	 intLogger.info("DiseaseCourseInterface|uploadPic 当前线程数:"+taskExecutor.getActiveCount());
	 Schedule schedule=new Schedule(picList);
	 taskExecutor.execute(schedule);
 }

 3)创建一个线程类Schedule,处理压缩图片任务

public class Schedule implements Runnable{
    //日志
	protected Logger logger = Logger.getLogger(this.getClass());
	//参数处理
	private List<String> picList;
	

    public Schedule(List<String> picList) {
        this.picList = picList;
     }
    
    

    @Override
    public void run() {
    	logger.info("[Schedule][execute]method begin ...");
        try {
        	if(null!=picList&&picList.size()>0){
        		for (String pic : picList) {
        			//可直接获得图片list,这里处理压缩图片业务
				...
                }
    		}
         } catch (Exception e) {
        	 logger.error("[Schedule][execute]method error...");
        }
        logger.info("[Schedule][execute]method end ...");
    }
  }  

 

### Spring MVC 中线程池配置方法 在 Spring MVC 应用程序中,可以通过 `ThreadPoolTaskExecutor` 来配置线程池。这种线程池允许开发者自定义核心线程数、最大线程数以及其他相关参数,从而优化应用程序性能并提高资源利用率。 以下是具体的配置方式以及代码示例: #### 1. XML 配置方式 如果项目基于传统的 XML 配置,则可以在 Spring 的配置文件中引入 `<task:annotation-driven />` 并声明一个 Bean 定义来管理线程池。 ```xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd"> <!-- 开启异步支持 --> <task:annotation-driven /> <!-- 配置线程池 --> <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> <property name="corePoolSize" value="5" /> <property name="maxPoolSize" value="10" /> <property name="queueCapacity" value="25" /> <property name="keepAliveSeconds" value="30" /> <property name="threadNamePrefix" value="AsyncThread-" /> </bean> </beans> ``` 上述配置中设置了线程池的核心大小为 5,最大线程数量为 10,并且队列容量设置为 25[^2]。 #### 2. Java Config 方式 对于现代 Spring 应用程序,推荐使用基于 Java 注解的方式来进行配置。这种方式更加灵活且易于维护。 ```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; @Configuration @EnableAsync // 启用异步功能 public class ExecutorConfig { @Bean(name = "taskExecutor") public Executor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); // 设置核心线程数 executor.setMaxPoolSize(10); // 设置最大线程数 executor.setQueueCapacity(25); // 设置队列容量 executor.setKeepAliveSeconds(30); // 空闲线程存活时间 executor.setThreadNamePrefix("AsyncThread-"); // 线程名称前缀 executor.initialize(); // 初始化线程池 return executor; } } ``` 在此配置中,同样设定了线程池的相关属性,包括核心线程数、最大线程数、队列容量等[^1]。 #### 3. 使用线程池执行任务 一旦完成线程池配置,在业务逻辑中可以利用 `@Async` 注解标记的方法实现异步调用。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class TaskService { private final Executor taskExecutor; @Autowired public TaskService(Executor taskExecutor) { this.taskExecutor = taskExecutor; } @Async("taskExecutor") // 指定使用线程池 public void executeAsyncTask(String message) { System.out.println("Executing async task with message: " + message); } } ``` 当调用 `executeAsyncTask` 方法时,它将在单独的线程中运行而不会阻塞主线程。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值