SpringBoot异步任务@EnableAsync

本文详细介绍如何在SpringBoot项目中使用@EnableAsync开启异步任务,包括异步任务的定义、使用@Component标记组件、异步方法上@Async注解的使用,以及如何处理异步任务的返回结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、启动类加注解@EnableAsync开启异步任务,自动扫描:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@EnableAsync //开启异步
public class Application {

    public static void main(String[] args) {
        final SpringApplication application = new SpringApplication(com.xxx.xxx.Application.class);
        application.run(args);
    }
}

2、定义异步任务并使用@Component标记组件被容器扫描,异步方法加上@Async

注意:

1)要把异步任务封装到类里面,不能直接写到Controller;

2)增加Future<String>返回结果AsyncResult<String>("task执行完成")

3)如果需要拿到结果,需要判断全部的task.isDone();

4)通过注入方式,注入到Controller里面,如果改为同步任务需要把@Async注释掉;

4)异步任务无返回结果。

异步任务业务类:

// 异步任务业务类
@Component
@Async
public class AsyncTask {

	public void task1() throws InterruptedException {
		long begin = System.currentTimeMillis();
		TimeUnit.SECONDS.sleep(1);
		long end = System.currentTimeMillis();
		System.out.println("任务1耗时=" + (end - begin));
	}

	public void task2() throws InterruptedException {
		long begin = System.currentTimeMillis();
		TimeUnit.SECONDS.sleep(2);
		long end = System.currentTimeMillis();
		System.out.println("任务2耗时=" + (end - begin));
	}

	public void task3() throws InterruptedException {
		long begin = System.currentTimeMillis();
		TimeUnit.SECONDS.sleep(3);
		long end = System.currentTimeMillis();
		System.out.println("任务3耗时=" + (end - begin));
	}

}

测试类:

@RestController
@RequestMapping("/api/v1")
public class UserController {
	@Autowired
	private AsyncTask asyncTask;

	@RequestMapping("async_task")
	public String exeTask() throws InterruptedException {
		long begin = System.currentTimeMillis();
		asyncTask.task1();
		asyncTask.task2();
		asyncTask.task3();
		long end = System.currentTimeMillis();
		System.out.println("执行总耗时=" + (end - begin));
		return "success";
	}
}

运行结果:

执行总耗时=0
任务1耗时=1001
任务2耗时=2000
任务3耗时=3000

 

异步任务存在返回结果:

// 异步任务业务类
@Component
@Async
public class AsyncTask {

	public Future<String> task1() throws InterruptedException {
		long begin = System.currentTimeMillis();
		TimeUnit.SECONDS.sleep(1);
		long end = System.currentTimeMillis();
		System.out.println("任务1耗时=" + (end - begin));
		return new AsyncResult<String>("任务1");
	}

	public Future<String> task2() throws InterruptedException {
		long begin = System.currentTimeMillis();
		TimeUnit.SECONDS.sleep(2);
		long end = System.currentTimeMillis();
		System.out.println("任务2耗时=" + (end - begin));
		return new AsyncResult<String>("任务2");
	}

	public Future<String> task3() throws InterruptedException {
		long begin = System.currentTimeMillis();
		TimeUnit.SECONDS.sleep(3);
		long end = System.currentTimeMillis();
		System.out.println("任务3耗时=" + (end - begin));
		return new AsyncResult<String>("任务3");
	}

}

测试类:

@RestController
@RequestMapping("/api/v1")
public class UserController {
	@Autowired
	private AsyncTask asyncTask;

	@RequestMapping("async_task")
	public String exeTask() throws InterruptedException {
		long begin = System.currentTimeMillis();
		Future<String> task1 = asyncTask.task1();
		Future<String> task2 = asyncTask.task2();
		Future<String> task3 = asyncTask.task3();
		for (;;) {
			if (task1.isDone() && task2.isDone() && task3.isDone()) {
				break;
			}
		}
		long end = System.currentTimeMillis();
		System.out.println("执行总耗时=" + (end - begin));
		return "success";
	}
}

运行结果:

任务1耗时=1000
任务2耗时=2001
任务3耗时=3001
执行总耗时=3001

 

PS:需要异步执行的方法,不能和调用它的方法在一个类中,否则异步不生效。

 

 

 

 

如果我的文章有帮助到您,欢迎打赏一下鼓励博主。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值