springboot启用线程池

本文详细介绍了如何在Spring Boot应用中配置线程池,包括在application.properties文件中设置线程池参数,创建线程池配置类实现异步任务处理,并通过实例展示了线程池的正确使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、在application.properties中配置线程池

server.port=8088

#线程池配置
task.queue.corePoolSize=10
task.queue.maxPoolSize=30
task.queue.queueCapacity=8
task.queue.keepAlive=60

baseurl=http://localhost:8080
#login
login_url=/sys/login/restful.do
logout_url=/logout
updateUserSessionByusername_url=/updateUserSessionByusername.do
syslogin_url=/sys/login.do

shuiyin_url=/yisheng/getUserWaterMark.do
currentpermission_url=/permissions/current.do

#kaosheng
kaosheng_infoByCode_url=/kaosheng/infoByCode
kaosheng_updateFenzuByKsIds=/kaosheng/updateFenzuByKsIds
kaosheng_zuChengYuanByZuCode_url=/access/kaosheng/zuChengYuanByZuCode

#fenzu
fenzu_getZuList_url=/fenzu/getZuList.do

#xuexiao
xuexiao_getShengShiQuXueXiao_url=/xuexiao/getShengShiQuXueXiao

#user
updatePass_url=/users/updatePass.do

2、创建线程池配置类:

package com.zr.gktjweb.aspect;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置、启用异步
 *
 * @author liugh
 */
//开启异步
@EnableAsync(proxyTargetClass = true)
@Configuration
public class AsycTaskExecutorConfig {

    @Value("${task.queue.corePoolSize}")
    private int corePoolSize;//线程池维护线程的最少数量
    @Value("${task.queue.maxPoolSize}")
    private int maxPoolSize;//线程池维护线程的最大数量
    @Value("${task.queue.queueCapacity}")
    private int queueCapacity; //缓存队列
    @Value("${task.queue.keepAlive}")
    private int keepAlive;//允许的空闲时间

    @Bean
    public Executor taskQueueExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(corePoolSize);
        // 设置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        // 设置队列容量
        executor.setQueueCapacity(queueCapacity);
        // 设置默认线程名称
        executor.setThreadNamePrefix("taskQueueExecutor-");
        //对拒绝task的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(keepAlive);
        executor.initialize();
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
}

3、添加线程异步:参照https://blog.youkuaiyun.com/aiyongbo123456/article/details/86635455

4、访问controller层,结果如下:

成功调用线程池中创建的线程。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值