温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

springboot 中如何配置线程池

发布时间:2021-06-18 17:33:47 来源:亿速云 阅读:257 作者:Leah 栏目:大数据

springboot 中如何配置线程池,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

1.添加config
import lombok.extern.slf4j.Slf4j;
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
@Slf4j
public class ExecutorConfig {

    @Bean("taskExecutor")
    public Executor asyncServiceExecutor() {
        log.info("---创建线程池---");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程数
        executor.setCorePoolSize(10);
        //最大线程数
        executor.setMaxPoolSize(20);
        //队列大小
        executor.setQueueCapacity(200);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix("async-method-");
        /*
        rejection-policy:当pool已经达到max size的时候,如何处理新任务
        线程池对拒绝任务的处理策略:此处采用了CallerRunsPolicy策略,
        当线程池没有处理能力的时候,该策略会直接在execute方法的调用线程中运行被拒绝的任务;
        如果执行程序已被关闭,则会丢弃该任务
        */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        //设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以确保应用最后能够被关闭,而不是阻塞住
        executor.setAwaitTerminationSeconds(60);

        //执行初始化
        executor.initialize();
        return executor;
    }
}
2.定义异步方法
/**
 * 异步调用测试接口
 */
public interface IAsyncService {

    void testAsyncMethod() throws Exception;
}


@Service
@Slf4j
public class AsyncServiceImpl implements IAsyncService {

	//此处taskExecutor和 config中@bean保持一致
    @Async("taskExecutor")
    @Override
    public void testAsyncMethod() throws Exception{
        log.info("异步方法,走起---");
        long start = System.currentTimeMillis();
        Thread.sleep(5000);
        long end = System.currentTimeMillis();
        log.info("异步方法,结束:" + (end - start) + "毫秒");
    }
}

3.测试

	public Result<?> test() {

		System.out.println("1=====================");
		System.out.println("2=====================");

		try {
			asyncService.testAsyncMethod();
		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println("3=====================");
		System.out.println("4=====================");
		
		return Result.ok("测试成功!");
	}

控制台打印如下:

springboot 中如何配置线程池

备注:

如果发现启动项目报错:

springboot 中如何配置线程池

解决方案:yml中添加配置

spring:
  main:
    allow-bean-definition-overriding: true

看完上述内容,你们掌握springboot 中如何配置线程池的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI