Spring Boot 2 异步执行任务

  • Goal:
    spring boot 2 使用 @Async 注解来异步执行任务

  • Code:

    启动类view raw
    1
    2
    3
    4
    5
    6
    7
    @SpringBootApplication
    public class WebApplicationBooter {
    public static void main(String[] args) throws InterruptedException {
    SpringApplication.run(WebApplicationBooter.class, args);
    }

    }
    连接池配置类view raw
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    @Configuration
    @EnableAsync
    public class TaskExecutorConfig {
    private static final int TASK_POOL_SIZE = 32;
    private static final int MAX_POOL_SIZE = 256;
    private static final int QUEUE_SIZE = 16384;

    @Bean(name = "taskExecutor")
    public static Executor taskExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(TASK_POOL_SIZE);
    executor.setMaxPoolSize(MAX_POOL_SIZE);
    executor.setQueueCapacity(QUEUE_SIZE);
    executor.setThreadNamePrefix("TaskPool-");
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    executor.setAllowCoreThreadTimeOut(true);
    executor.initialize();
    return executor;
    }

    }
    异步任务类view raw
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    @Component
    public class AsyncTask {
    private static final Logger logger = LoggerFactory.getLogger(AsyncTask.class);

    @Async
    public void test() {
    logger.info("In Async Task");
    logger.info("Async Task Before");
    try {
    Thread.sleep(2000L);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    logger.info("Async Task After");
    }

    }
    REST服务类view raw
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    @RestController
    public class WebService {
    private static final Logger logger = LoggerFactory.getLogger(WebService.class);

    @Autowired
    private AsyncTask task;

    @GetMapping("/")
    public String helloWorld() {
    logger.info("helloWorld");
    return "Hello World";
    }

    @GetMapping("/async")
    public String helloWorldAsync() {
    logger.info("helloWorldAsync");
    task.test();
    return "async: Hello World";
    }

    }