美文网首页
SpringBoot整合异步任务

SpringBoot整合异步任务

作者: 任未然 | 来源:发表于2022-01-04 13:38 被阅读0次

一. 概述

参考开源项目https://github.com/xkcoding/spring-boot-demo
本Demo简单使用spring自带的异步任务功能

二. 例子

2.1 依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

2.2 application.yml

spring:
  task:
    execution:
      pool:
        # 最大线程数
        max-size: 16
        # 核心线程数
        core-size: 16
        # 存活时间
        keep-alive: 10s
        # 队列大小
        queue-capacity: 100
        # 是否允许核心线程超时
        allow-core-thread-timeout: true
      # 线程名称前缀
      thread-name-prefix: async-task-

2.3 启动类

@EnableAsync
@SpringBootApplication
public class SpringBootDemoAsyncApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootDemoAsyncApplication.class, args);
    }

}

加上注解@EnableAsync

2.4 异步任务

@Component
@Slf4j
public class TaskFactory {
    @Async
    public Future<Boolean> asyncTask1() throws InterruptedException {
      log.info("{}开始执行,当前线程名称【{}】", taskName, Thread.currentThread().getName());
    }
}

方法加上注解@Async

相关文章

网友评论

      本文标题:SpringBoot整合异步任务

      本文链接:https://www.haomeiwen.com/subject/twjqcrtx.html