SpringBoot @Async实现异步调用

同步方法调用的时候必须是按照顺序执行的,上一行代码执行完,才会执行下一行。而异步方法调用是相当于多个线程执行,不需要等待上一行代码的执行结果。
首先要在启动类上面使用@EnableAsync开始异步方法调用,然后在你要调用的每一个方法上面都要添加@Async,表明异步调用该方法。相当于开启了新的线程,在调用该方法的时候不需要等待上一行代码是否执行完成。同一个类中,一个方法调用另外一个有@Async的方法,注解是不会生效的。
启动类:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
 
@SpringBootApplication
@EnableAsync
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
}

controller

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class TestController {

	@Autowired
	private MyService myService;
	
	@RequestMapping("/test")
	public String getInedx() throws InterruptedException {
		System.out.println("开始访问");
		long l1 = System.currentTimeMillis();
		myService.JobOne();
		myService.JobTwo();
		myService.JobThree();
		long l2 = System.currentTimeMillis();
		
		System.out.println("结束访问,用时"+(l2-l1));
		return "finished";
	}
}

service

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
 
@Service
public class MyService {
 
	@Async
	public void JobOne() throws InterruptedException {
		System.out.println("开始执行任务一");
		long l1 = System.currentTimeMillis();
		Thread.sleep(2000);
		long l2 = System.currentTimeMillis();
		System.out.println("任务一用时"+(l2-l1));
		
	}
	
	@Async
	public void JobTwo() throws InterruptedException {
		System.out.println("开始执行任务二");
		long l1 = System.currentTimeMillis();
		Thread.sleep(2000);
		long l2 = System.currentTimeMillis();
		System.out.println("任务二用时"+(l2-l1));
	}
	
	
	@Async
	public void JobThree() throws InterruptedException {
		System.out.println("开始执行任务三");
		long l1 = System.currentTimeMillis();
		Thread.sleep(2000);
		long l2 = System.currentTimeMillis();
		System.out.println("任务三用时"+(l2-l1));
	}
}

结果:
在这里插入图片描述在这里插入图片描述

发布了31 篇原创文章 · 获赞 5 · 访问量 644

猜你喜欢

转载自blog.csdn.net/qq_37365741/article/details/100133958