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.  控制檯打印結果如下:
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章