【发布时间】:2019-11-09 17:02:25
【问题描述】:
我是 Spring Boot 新手,想了解更多有关 DeferredResult 和 @Async 方法的信息。我在控制器中创建了一个方法,如下所示,它运行良好。
@GetMapping("/temp/{id}")
public DeferredResult<ResponseEntity<?>> findByIdTemp(@PathVariable Long id) throws InterruptedException {
System.out.println("Request received : "+Thread.currentThread().getName());
final DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>();
ForkJoinPool.commonPool().submit(() -> {
System.out.println("Processing in separate thread");
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
}
deferredResult.setResult(ResponseEntity.ok("ok"));
});
System.out.println("Thread freed : " +Thread.currentThread().getName());
return deferredResult;
}
以下是我收到的输出。
Request received : http-nio-8080-exec-1
Thread freed : http-nio-8080-exec-1
Processing in separate thread
然后我在服务类中创建@Async 方法并在配置类中启用异步。
@Configuration
@EnableAsync
public class ThreadPoolConfiguration {
@Autowired
private ExecutorConfiguration configuration;
@Bean(name = "threadPool")
public Executor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
threadPool.setCorePoolSize(configuration.getDnCallBackPoolSize());
return threadPool;
}
}
@Async("threadPool")
public Future<String> getResult() throws InterruptedException {
System.out.println("Separate thread : "+Thread.currentThread().getName());
Thread.sleep(6000);
return new AsyncResult<>("Success");
}
然后我从控制器类中调用了服务方法
@GetMapping("/temp/{id}")
public DeferredResult<ResponseEntity<?>> findByIdTemp(@PathVariable Long id) {
System.out.println("Request received : "+Thread.currentThread().getName());
final DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>();
ResponseDTO responseDTO = null;
try {
responseDTO = ResponseDTO.builder()
.status(HttpStatus.OK.toString())
.body(productService.getResult().get()).build();
ResponseEntity responseEntity = ResponseEntity.ok(responseDTO);
deferredResult.setResult(responseEntity);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
} catch (ExecutionException e) {
System.out.println(e.getMessage());
}
System.out.println("Thread freed : " +Thread.currentThread().getName());
return deferredResult;
}
但我得到的结果不一样
Request received : http-nio-8080-exec-1
Separate thread : dnCallBackPool-1
Thread freed : http-nio-8080-exec-1
控制器方法似乎正在等待服务方法的响应。谁能告诉我如何正确使用 DeferredResult 和 @Async 方法。
【问题讨论】:
标签: java spring spring-boot