Personal blog address :http://alexaccele.github.io/
stay springboot Using simple asynchronous tasks
Synchronous situation
First, let’s look at the code in the case of synchronization , stay service Added a thread wait method in
@Service
public class AsyncService {
public void asyncHello(){
try {
Thread.sleep(3000);
}catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("hello...");
}
}
stay controller Received by Zhongdang “/” When asked , Will execute service Medium asyncHello() Method returns success;
@RestController
public class AsyncController {
@Autowired
private AsyncService asyncService;
@GetMapping("/")
public String asyncHello(){
asyncService.asyncHello();
return "success";
}
}
The execution result is Page loading 3 Seconds later Only show success, Console output at the same time “hello…”
Asynchronous situation
On the application entry class add to @EnableAsync Annotations enable asynchrony
@EnableAsync
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
stay service Of Method plus @Async annotation
@Service
public class AsyncService {
@Async
public void asyncHello(){
try {
Thread.sleep(3000);
}catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("hello...");
}
}
After the above modifications , The running result becomes Return immediately success, Waiting for the 3 Seconds later , Console printing “hello…”