SpringBoot中的线程池,你真的会

全国治白癜风最好医院 https://m-mip.39.net/nk/mipso_4792767.html

来源:blog.csdn.net/m0_/article/details/

前言

前两天做项目的时候,想提高一下插入表的性能优化,因为是两张表,先插旧的表,紧接着插新的表,一万多条数据就有点慢了

后面就想到了线程池ThreadPoolExecutor,而用的是SpringBoot项目,可以用Spring提供的对ThreadPoolExecutor封装的线程池ThreadPoolTaskExecutor,直接使用注解启用

使用步骤

先创建一个线程池的配置,让SpringBoot加载,用来定义如何创建一个ThreadPoolTaskExecutor,要使用

Configuration和

EnableAsync这两个注解,表示这是个配置类,并且是线程池的配置类

Configuration

EnableAsyncpublicclassExecutorConfig{privatestaticfinalLoggerlogger=LoggerFactory.getLogger(ExecutorConfig.class);

Value("{async.executor.thread.core_pool_size}")privateintcorePoolSize;

Value("{async.executor.thread.max_pool_size}")privateintmaxPoolSize;

Value("{async.executor.thread.queue_capacity}")privateintqueueCapacity;

Value("{async.executor.thread.name.prefix}")privateStringnamePrefix;

Bean(name="asyncServiceExecutor")publicExecutorasyncServiceExecutor(){logger.info("startasyncServiceExecutor");ThreadPoolTaskExecutorexecutor=newThreadPoolTaskExecutor();//配置核心线程数executor.setCorePoolSize(corePoolSize);//配置最大线程数executor.setMaxPoolSize(maxPoolSize);//配置队列大小executor.setQueueCapacity(queueCapacity);//配置线程池中的线程的名称前缀executor.setThreadNamePrefix(namePrefix);//rejection-policy:当pool已经达到maxsize的时候,如何处理新任务//CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行executor.setRejectedExecutionHandler(newThreadPoolExecutor.CallerRunsPolicy());//执行初始化executor.initialize();returnexecutor;}}Value是我配置在application.properties,可以参考配置,自由定义

#异步线程配置#配置核心线程数async.executor.thread.core_pool_size=5#配置最大线程数async.executor.thread.max_pool_size=5#配置队列大小async.executor.thread.queue_capacity=#配置线程池中的线程的名称前缀async.executor.thread.name.prefix=async-service-

创建一个Service接口,是异步线程的接口

publicinterfaceAsyncService{/***执行异步任务*可以根据需求,自己加参数拟定,我这里就做个测试演示*/voidexecuteAsync();}

实现类

ServicepublicclassAsyncServiceImplimplementsAsyncService{privatestaticfinalLoggerlogger=LoggerFactory.getLogger(AsyncServiceImpl.class);

Override

Async("asyncServiceExecutor")publicvoidexecuteAsync(){logger.info("startexecuteAsync");System.out.println("异步线程要做的事情");System.out.println("可以在这里执行批量插入等耗时的事情");logger.info("endexecuteAsync");}}

将Service层的服务异步化,在executeAsync()方法上增加注解

Async("asyncServiceExecutor"),asyncServiceExecutor方法是前面ExecutorConfig.java中的方法名,表明executeAsync方法进入的线程池是asyncServiceExecutor方法创建的。(搜索



转载请注明地址:http://www.sanbaicaoasb.com/scls/8577.html
  • 上一篇文章:
  • 下一篇文章: 没有了
  • 热点文章

    • 没有热点文章

    推荐文章

    • 没有推荐文章