SpringBoot——集成异步线程(Executor)

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

     

  2. AsyncTask.java
    package com.hahashujia.config;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.scheduling.annotation.AsyncResult;
    import org.springframework.stereotype.Component;
    
    import java.util.concurrent.Future;
    
    /**
     * @author hahashujia
     * @description
     * @date 2019/5/8 0008 17:01
     */
    @Component
    public class AsyncTask {
        private static final Logger logger = LoggerFactory.getLogger(AsyncTask.class);
    
        @Async
        public Future<String> doTask1() throws InterruptedException{
            logger.info("Task1 started.");
            long start = System.currentTimeMillis();
            Thread.sleep(5000);
            long end = System.currentTimeMillis();
    
            logger.info("Task1 finished, time elapsed: {} ms.", end-start);
    
            return new AsyncResult<>("Task1 accomplished!");
        }
    
        @Async
        public Future<String> doTask2() throws InterruptedException{
            logger.info("Task2 started.");
            long start = System.currentTimeMillis();
            Thread.sleep(3000);
            long end = System.currentTimeMillis();
    
            logger.info("Task2 finished, time elapsed: {} ms.", end-start);
    
            return new AsyncResult<>("Task2 accomplished!");
        }
    }
    

     

  3. ExecutorConfig.java
    package com.hahashujia.config;
    
    import org.springframework.beans.factory.annotation.Value;
    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;
    
    /**
     * @author hahashujia
     * @description
     * @date 2019/10/24
     */
    @Configuration
    @EnableAsync
    public class ExecutorConfig {
    
        @Value("${async.executor.thread.core_pool_size}")
        private int corePoolSize;
        @Value("${async.executor.thread.max_pool_size}")
        private int maxPoolSize;
        @Value("${async.executor.thread.queue_capacity}")
        private int queueCapacity;
        @Value("${async.executor.thread.name.prefix}")
        private String namePrefix;
    
        @Bean(name = "asyncServiceExecutor")
        public Executor asyncServiceExecutor() {
    
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            //配置核心线程数
            executor.setCorePoolSize(corePoolSize);
            //配置最大线程数
            executor.setMaxPoolSize(maxPoolSize);
            //配置队列大小
            executor.setQueueCapacity(queueCapacity);
            //配置线程池中的线程的名称前缀
            executor.setThreadNamePrefix(namePrefix);
    
            // rejection-policy:当pool已经达到max size的时候,如何处理新任务
            // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
            executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
            //执行初始化
            executor.initialize();
            return executor;
        }
    }
    

     

  4. 线程调用NoticeService.java
    package com.hahashujia.service.notice;
    
    import lombok.extern.log4j.Log4j;
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.stereotype.Service;
    
    /**
     * @author hahashujia
     * @description
     * @date 2019/5/9
     */
    @Service
    @Log4j
    public class NoticeService {
    
        /**
         * 小明回家吃饭了
         *
         * @return
         */
        @Async("asyncServiceExecutor")
        public void notice() throws InterruptedException {
    
            Thread.sleep(5000);
            log.info("小明该回家吃饭了");
            Thread.sleep(5000);
            log.info("小明不吃饭就没饭吃了");
            Thread.sleep(5000);
            log.info("饭只剩一半了");
            Thread.sleep(5000);
            log.info("饭吃完了,你可以不用回来了");
    
        }
    }
    

     

  5.  Controller调用:
    package com.hahashujia.controller.notice;
    
    import com.hahashujia.basic.annotation.ApiType;
    import com.hahashujia.config.Swagger2Config;
    import com.hahashujia.service.NoticeService;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * 异步线程调用
     *
     * @author hahashujia
     */
    @ApiType(apiTypeValue = Swagger2Config.BusinessGroup.BANK_STATEMENT)
    @Api(description = "异步线程调用")
    @RestController
    @RequestMapping("/notice")
    @Slf4j
    public class NoticeController {
    
        @Autowired
        private NoticeService noticeService;
    
        @GetMapping("/dinner")
        @ApiOperation(value = "吃饭", notes = "吃饭")
        public String dinner() throws InterruptedException {
            noticeService.notice();
            log.info("通知已下达");
            return "ok";
        }
    
    }
    

     

  6.  控制台打印结果如下:
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中,可以使用`ThreadPoolTaskExecutor`类来初始化一个Executor。下面是一个简单的示例: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @Configuration public class ExecutorConfig { @Bean public ThreadPoolTaskExecutor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); //设置核心线程executor.setMaxPoolSize(20); //设置最大线程executor.setQueueCapacity(100); //设置队列容量 executor.setThreadNamePrefix("MyExecutor-"); //设置线程名称前缀 executor.initialize(); //初始化Executor return executor; } } ``` 在上面的示例中,我们定义了一个`taskExecutor()`方法,用于初始化`ThreadPoolTaskExecutor`对象。我们可以通过调用`setCorePoolSize()`、`setMaxPoolSize()`和`setQueueCapacity()`方法来设置线程池的一些属性。最后,调用`initialize()`方法来完成Executor的初始化。 注意,我们需要将`@Configuration`注解添加到我们的配置类上,以便Spring Boot能够自动扫描并加载该类。另外,我们还需要将初始化后的Executor注入到需要使用的类中,例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.stereotype.Component; @Component public class MyService { @Autowired private ThreadPoolTaskExecutor taskExecutor; public void doSomething() { taskExecutor.execute(() -> { //执行具体的任务 }); } } ``` 在上面的示例中,我们使用`@Autowired`注解将初始化后的Executor注入到`MyService`类中。然后,我们可以在`doSomething()`方法中使用`taskExecutor`来执行具体的任务。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值