SpringBoot 异步调用@Async
2021-02-19 本文已影响0人
CNSTT
一、启动类注解 @EnableAsync
@EnableEurekaClient
@SpringBootApplication(scanBasePackages = {"com.csvw.cloud.**"})
@MapperScan({"com.csvw.cloud.dms.report.mapper","com.csvw.cloud.dms.framework.mapper"})
@EnableSwagger2
@EnableAsync
@EnableFeignClients(basePackages = {"com.csvw.cloud.**"})
@EnableApolloConfig({"application_common","application.yaml","application_basic.yaml"})
public class ReportServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ReportServiceApplication.class, args);
}
}
二、Controller层
/**
* 维修委托书查询(复杂)导出Excel并上传OBS - PC
*
* @param queryRepairOrderComplexPageDTO 查询传参
* @param request request
* @param response response
* @author Tansj
* @since 2020/06/04
*/
@ApiOperation(notes="维修委托书查询(复杂)导出Excel并上传OBS - PC", value="维修委托书查询(复杂)导出Excel并上传OBS - PC")
@ApiImplicitParams({
@ApiImplicitParam(value = "47c163ad2ac34d94808ebbc0f424b566", name = "userId", required = true, dataType = "string", paramType = "header"),
@ApiImplicitParam(value = "76612345", name = "dealerCode", required = true, dataType = "string", paramType = "header")})
@GetMapping("/exportRepairOrderComplexUpload")
public void exportRepairOrderComplexUploadMain(QueryRepairOrderComplexPageDTO queryRepairOrderComplexPageDTO, HttpServletRequest request,
HttpServletResponse response) throws UnsupportedEncodingException, InterruptedException {
long start = System.currentTimeMillis();
repairReportService.exportRepairOrderComplexUpload(queryRepairOrderComplexPageDTO, request, response);
long end = System.currentTimeMillis();
log.info("维修委托书复杂导出异步调用Async:----------------, 耗时[{}]毫秒", end - start);
}
三、ServiceImpl实现类 @Async
/**
* <p>ClassName: RepairReportServiceImpl</p>
* <p>Description: 维修报表ServiceImpl</p>
* <p>Author: Tansj</p>
* <p>Date: 2020年03月12日</p>
*/
@Slf4j
@Service
@EnableAsync
public class RepairReportServiceImpl implements RepairReportService {
/**
* 维修委托书查询(复杂)导出Excel并上传OBS - PC
*
* @param queryRepairOrderComplexPageDTO 查询传参
* @param request request
* @param response response
* @author Tansj
* @since 2020/06/04
*/
@Override
@Async
public void exportRepairOrderComplexUpload(QueryRepairOrderComplexPageDTO queryRepairOrderComplexPageDTO,
HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, InterruptedException {
......
}
}
四、同步接口中的异步调用
// ============Controller层============
/**
* 带有返回值的异步调用 - 测试使用
*
* @return String
* @author Tansj
* @since 2021/04/01
*/
@ApiOperation(notes="带有返回值的异步调用 - 测试使用", value="带有返回值的异步调用 - 测试使用")
@ApiImplicitParams({
@ApiImplicitParam(value = "47c163ad2ac34d94808ebbc0f424b566", name = "userId", required = true, dataType = "string", paramType = "header"),
@ApiImplicitParam(value = "76612345", name = "dealerCode", required = true, dataType = "string", paramType = "header")})
@GetMapping("/getAsyncReturnFunction")
public String getAsyncReturnFunction() {
repairReportService.getAsyncReturnFunction();
return "正在下载中,请稍后...";
}
// ============ServiceImpl层============
/**
* 带有返回值的异步调用 - 测试使用
*
* @return Future<String>
* @author Tansj
* @since 2021/04/01
*/
@Override
@Async
public Future<String> getAsyncReturnFunction() {
log.info("Execute method asynchronously -----------------{}", Thread.currentThread().getName());
try {
long start = System.currentTimeMillis();
Thread.sleep(5000);
long end = System.currentTimeMillis();
log.info("带有返回值的异步调用Async:----------------, 耗时[{}]毫秒", end - start);
return new AsyncResult<>("内部的返回结果");
} catch (Exception e) {
log.error(e.getMessage());
}
return null;
}
直接返回前端结果为【正在下载中,请稍后...】,等待时间10ms。
// ...接上文...
// ============Controller层============
/**
* 同步接口中的异步调用 - 测试使用
*
* @return String
* @author Tansj
* @since 2021/04/01
*/
@ApiOperation(notes="同步接口中的异步调用", value="同步接口中的异步调用")
@ApiImplicitParams({
@ApiImplicitParam(value = "47c163ad2ac34d94808ebbc0f424b566", name = "userId", required = true, dataType = "string", paramType = "header"),
@ApiImplicitParam(value = "76612345", name = "dealerCode", required = true, dataType = "string", paramType = "header")})
@GetMapping("/testAsyncReturnFunction")
public String testAsyncReturnFunction() throws ExecutionException, InterruptedException {
String result = "";
Future<String> future = repairReportService.getAsyncReturnFunction();
while (true) { ///这里使用了循环判断,等待获取结果信息
if (future.isDone()) { //判断是否执行完毕
System.out.println("Result from asynchronous process - " + future.get());
result = future.get();
break;
}
System.out.println("Continue doing something else. ");
Thread.sleep(1000);
}
return result;
}