Springboot使用@EnableAsync和 @Async实现异步调用

在日常开发中,我们有时会遇到在调用一次接口后,其后台的业务逻辑比较复杂,需要处理多个阶段,这个时候如果使用同步串行的方式,也就是单线程的方式来执行的话,前端需要等待较长时间,也可能会出现请求超时,这个时候,如果任务的下一个阶段不依赖上一个阶段的结果我们就可以使用异步的方式来并行执行此任务以提高响应效率

示例

1、@EnableAsync

在异步方法对应的类上加上@EnableAsync注解以开启异步调用方式

@Component
@EnableAsync
public class CommonTestServiceImpl implements CommonTestService {
	...

也可以加在启动类上,这样别的类中也有异步方法时就不

@SpringBootApplication
@EnableCaching
@EnableAsync
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
2、定义相关测试类

业务接口及实现类

public interface CommonTestService {

	/**
	 * 异步方法测试
	 */
	void asyncTest(List<Integer> ids);

	/**
	 * 同步测试,对比异步结果
	 */
	void syncTest(List<Integer> ids);
}

@Component
@EnableAsync
public class CommonTestServiceImpl implements CommonTestService {

	@Async
	@Override
	public void asyncTest(List<Integer> ids) {
		try {
			Thread.sleep(300);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		ids.add(3);
	}

	@Override
	public void syncTest(List<Integer> ids) {
		ids.add(3);
	}
}

rest接口类

@RestController
@RequestMapping("/test")
public class CommonTestController {

	@Autowired
	private CommonTestService commonTestService;

	@GetMapping("/async")
	public List<Integer> asyncRequest() {
		List<Integer> ids = new ArrayList<>();
		ids.add(1);
		commonTestService.asyncTest(ids);
		ids.add(2);
		try {
			Thread.sleep(1000); // 睡会,以保证返回前台时异步方法中的3已入列
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return ids;
	}

	@GetMapping("/sync")
	public List<Integer> syncRequest() {
		List<Integer> ids = new ArrayList<>();
		ids.add(1);
		commonTestService.syncTest(ids);
		ids.add(2);
		return ids;
	}
}
3、测试结果

调用同步接口名,我们可以看到值时一个个按照代码顺序串行入列的
在这里插入图片描述
而调用异步接口,2比3先入列,其实和多线程一个效果,主线程先执行的,而子线程后执行
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值