1.异步任务(无返回值异步任务调用)
1.spring项目的创建
2.编写异步调用方法
package com.example.demo.nine;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class MyAsyncService {
//使用这个注解将sendSMSd方法标记为异步方法
@Async
public void sendSMS() throws Exception {
System.out.println("调用短信验证码业务方法");
//获取当前时间
Long startTime=System.currentTimeMillis();
Thread.sleep(5000);
Long endTime=System.currentTimeMillis();
System.out.println("短信业务执行完成耗时"+(endTime-startTime));
}
}
3.开启基于注解的异步任务支持
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@EnableAsync
@SpringBootApplication
public class LayuistudyApplication {
public static void main(String[] args) {
SpringApplication.run(LayuistudyApplication.class, args);
}
}
4.编写控制层业务调用方法
package com.example.demo.nine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class MyAsyncController {
@Autowired
private MyAsyncService myService;
@GetMapping("/sendSMS")
public String sendSMS() throws Exception {
Long startTime=System.currentTimeMillis();
myService.sendSMS();
Long endTime=System.currentTimeMillis();
System.out.println("主程序耗时:"+(endTime-startTime));
return "success";
}
}
5.异步任务效果展示:
2.有返回值异步任务调用
1.创建一个类,直接将下面代码写入
@Async
//Future代表未来的结果
public Future<Integer> processA() throws Exception{
System.out.print("开始分析并统计业务A数据");
Long startTime=System.currentTimeMillis();
Thread.sleep(4000);
//定义一个假的统计结果
int count=123456;
Long endTime=System.currentTimeMillis();
System.out.print("业务A数据统计耗时"+(endTime-startTime));
//封装返回的异步结果数据
return new AsyncResult<Integer>(count);
}
@Async
public Future<Integer> processB() throws InterruptedException{
System.out.print("开始分析并统计业务B数据");
Long startTime=System.currentTimeMillis();
Thread.sleep(5000);
//定义一个假的统计结果
int count=654321;
//获取当前的系统时间
Long endTime=System.currentTimeMillis();
System.out.print("业务B数据统计耗时"+(endTime-startTime));
//封装返回的异步结果数据
return new AsyncResult<Integer>(count);
}
2.编写控制层业务调用方法
@Autowired
private MyAsyncService myService;
@GetMapping("/statistics")
public String statistic() throws Exception {
Long startTime=System.currentTimeMillis();
Future<Integer> futureA=myService.processA();
Future<Integer> futureB=myService.processB();
int total=futureA.get()+futureB.get();
System.out.print("异步任务数据统计汇总结果"+total);
Long endTime=System.currentTimeMillis();
System.out.print("主程序耗时"+(endTime-startTime));
return "success";
}
3.异步任务效果测试: