Asynchronous processing
1. First create a springboot project
提示:选择的java版本不要太高
I chose Spring Web here
2.Write AswncService code in the service layer
指定异步内容,在方法上面加注解@Async,为了告诉Spring这是一个异步的方法
/**
* @Author liuyun
* @Date 2023/3/6 9:30
* @Version 1.0
*/
@Service
public class AswncService {
//@Async告诉spring这是一个异步的方法
@Async
public void hello(){
try {
//调取这个方法后让休眠三秒
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理");
}
}
3.Write AswncController code in the controller layer
在该controller上加注解@EnableAsync,也可以加在启动类上,开启异步注解功能
/**
* @Author liuyun
* @Date 2023/3/6 9:30
* @Version 1.0
*/
@EnableAsync//开启异步注解功能
@RestController
public class AswncController {
//引入service
@Autowired
AswncService aswncService;
@RequestMapping("/hello")
public String hello(){
//调取service中的方法
aswncService.hello();
//返回OK
return "OK";
}
}
4. Project start
如果没有启动异步功能,访问页面会等待三秒(转圈),然后才显示;开启异步功能以后则不会受方法影响,直接显示OK
Three seconds later, the method aswncService.hello() called in the background displays the following content:
This is a simple asynchronous processing function; refer to
Hope it helps you