SpringBoot中异步调的使用

文章展示了如何在SpringBoot应用中实现异步调用。通过添加@EnableAsync注解到启动类,声明并实现带有@Async注解的异步方法,可以在不等待方法执行完成的情况下继续执行其他代码,实现了方法的并行处理。在给定的示例中,两个异步方法progressOne和progressTwo被同时调用,证明了异步执行的效果。
摘要由CSDN通过智能技术生成

什么是异步调用?
异步调用无需等待上一步程序执行完成即可执行。在开发项目中可以使用多线程来并行处理或者使用SpringBoot提供的@Async处理。

1、启动类上需要添加@EnableAsync

@SpringBootApplication
@EnableAsync
public class DemoApplication {

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

2、声明异步方法

public interface AsyncService {

	/**
	 * 测试异步执行方法1
	 */
	void progressOne();


	/**
	 * 测试异步方法2
	 */
	void progressTwo();
	
}

3、异步类上加上@Component,异步方法上加上@Async

@Component
public class AsyncServiceImpl implements AsyncService {

	private static final Logger logger = LoggerFactory.getLogger(
			AsyncServiceImpl.class);

	@Override
	@Async
	public void progressOne() {

		long start = System.currentTimeMillis();
		logger.info("=========第一个程序开始执行,开始时间:{}==========", start);

		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		long end = System.currentTimeMillis();
		logger.info("=========第一个程序结束时间:{}==========", end);
		logger.info("=========第一个程序开始结束花费时间:{}==========", (end - start));

	}

	@Override
	@Async
	public void progressTwo() {

		long start = System.currentTimeMillis();
		logger.info("=========第二个程序开始执行时间:{}==========", start);
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		long end = System.currentTimeMillis();
		logger.info("=========第二个程序结束时间:{}==========", end);
		logger.info("=========第二个程序开始结束花费时间:{}==========", (end - start));
	}

}

3、控制类调用异步方法

@RestController
@RequestMapping("demo")
public class AsyncController {
	
	private static final Logger logger = LoggerFactory.getLogger(AsyncController.class);

	@Resource
	AsyncService asyncService;
	
	@GetMapping("/async")
	public String AsyncDemo() {

		long start = System.currentTimeMillis();
		asyncService.progressOne();
		asyncService.progressTwo();
		long end = System.currentTimeMillis();
		logger.info("进程总时间:", (end - start));

		return "OK";
	}

}

4、启动服务,测试执行结果
在这里插入图片描述
执行结果可见,方法1、方法2同时执行(开始时间相同)。即异步执行生效。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值