1、在启动类中添加注解
@SpringBootApplication
@EnableAsync
//@ImportResource(locations = {"classpath:spring/my.xml"})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2、写异步调用的类和方法
@Service
@Slf4j
public class UserService {
@Async
public Future<Integer> sum(Integer a, Integer b){
log.info("sum thread:"+Thread.currentThread().getName());
return new AsyncResult(a+b);
}
@Async
public Future<Integer> count(Integer a,Integer b){
log.info("count thread:"+Thread.currentThread().getName());
return new AsyncResult(a+b);
}
}
3、异步调用
@RequestMapping("/show")
public String show() {
//调用
Future<Integer> sum = userService.sum(10, 10);
Future<Integer> count = userService.count(20, 20);
List<Future> result = new ArrayList<>();
//保存返回
result.add(sum);
result.add(count);
//获取返回值
Integer totleSum = null;
try {
totleSum = (Integer) result.get(0).get();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
Integer totleCount = null;
try {
totleCount = (Integer) result.get(1).get();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
return "env:sum="+totleSum+",count="+totleCount;
}
浙公网安备 33010602011771号