使用场景, 发短信,发送邮件,APP消息推送
A.启动类:
@EnableAsync 注解主要是为了扫描范围包下的所有 @Async注解
package springboot_async;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableAsync
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
B.使用异步回调:
在controller中无限循环判断异步方法是否执行完成。
在service的方法中返回Future值。
controller:
package springboot_async.async_test;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
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, ExecutionException {
System.out.println("开始访问");
long l1 = System.currentTimeMillis();
Future<String> r1 = myService.JobOne();
Future<String> r2 = myService.JobTwo();
Future<String> r3 = myService.JobThree();
while(true) {//死循环,每隔2000ms执行一次,判断一下这三个异步调用的方法是否全都执行完了。
if(r1.isDone() && r2.isDone() && r3.isDone()) {//使用Future的isDone()方法返回该方法是否执行完成
//如果异步方法全部执行完,跳出循环
break;
}
Thread.sleep(2000);//每隔2000毫秒判断一次
}
long l2 = System.currentTimeMillis();//跳出while循环时说明此时三个异步调用的方法都执行完成了,此时得到当前时间
String result = r1.get();
System.out.println("结束访问,用时"+(l2-l1));
System.out.println("使用get方法获得的返回内容:"+result);
return "finished";
}
}
C.service :
package springboot_async.async_test;
import java.util.concurrent.Future;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
@Service
public class MyService {
@Async
public Future<String> JobOne() throws InterruptedException {
System.out.println("开始执行任务一");
long l1 = System.currentTimeMillis();
Thread.sleep(2000);
long l2 = System.currentTimeMillis();
System.out.println("任务一用时"+(l2-l1));
return new AsyncResult<String>("任务一完成");//可以使用try,catch定义在正常完成时返回一个success信息,出现异常时返回error信息。
}
@Async
public Future<String> JobTwo() throws InterruptedException {
System.out.println("开始执行任务二");
long l1 = System.currentTimeMillis();
Thread.sleep(2000);
long l2 = System.currentTimeMillis();
System.out.println("任务二用时"+(l2-l1));
return new AsyncResult<String>("任务二完成");
}
@Async
public Future<String> JobThree() throws InterruptedException {
System.out.println("开始执行任务三");
long l1 = System.currentTimeMillis();
Thread.sleep(2000);
long l2 = System.currentTimeMillis();
System.out.println("任务三用时"+(l2-l1));
return new AsyncResult<String>("任务三完成");
}
}