package com.sj.controller;
import com.sj.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@RequestMapping("/hello")
public String hello(){
asyncService.hello();//停止三秒,转圈
return "ok";
}
}
package com.sj.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
//告诉spring这是一个异步的方法
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理...");
}
}
package com.sj;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
//开启异步注解功能
@EnableAsync
@SpringBootApplication
public class SpringbootYibuApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootYibuApplication.class, args);
}
}
在没有添加 @Async @EnableAsync 网页会加载(转圈)三秒,添加之后网页不会加载3秒。因为有@Async标注方法, 它会在调用方的当前线程之外的独立的线程中执行。
网友评论