响应正文为空,因为在
@AsyncUserRepository类的findEmail方法中使用了注释,这意味着没有数据返回到下面的句子,
Useruser =userRepository.findByEmail(email);因为findByEmail方法正在其他线程上运行,并且将返回null而不是List对象。
@Async当您声明该注释
@EnableAsync仅在使用时才发生时
@EnableAsync,便启用了该注释,因为它激活了findEmail方法的@Async以便在其他线程上运行它。
该方法
returnuserService.findByEmail(email);将返回
CompletableFuture从
UserService类创建的对象。
与第二个方法调用的不同之处在于,该
thenApplyAsync方法将创建一个
CompletableFuture与前一个方法完全不同的新方法,
userService.findByEmail(email)并且仅返回第一个方法的用户对象
CompletableFuture。
return userService.findByEmail(email).thenApplyAsync(user -> { return user; })如果要获得预期的结果,只需
@Async从findByEmail方法中删除注释,最后添加
@EnableAsync注释
如果您需要澄清如何使用异步方法的想法,可以说您必须调用三个方法,每个方法需要2秒钟才能完成,在正常情况下,您将其称为method1,然后称为method2,最后称为method3。整个请求将花费6秒。激活异步方法后,您可以调用其中三个,而只需等待2秒钟而不是6秒钟。
将此长方法添加到用户服务中:
@Asyncpublic CompletableFuture<Boolean> veryLongMethod() { try { Thread.sleep(2000L); } catch (InterruptedException e) { e.printStackTrace(); } return CompletableFuture.completedFuture(true);}然后从Controller调用它三遍
@RequestMapping(value = "test") public @ResponseBody CompletableFuture<User> test(@RequestParam(value = "email", required = true) String email) throws InterruptedException { CompletableFuture<Boolean> boolean1= siteService.veryLongMethod(); CompletableFuture<Boolean> boolean2= siteService.veryLongMethod(); CompletableFuture<Boolean> boolean3= siteService.veryLongMethod(); CompletableFuture.allOf(boolean1,boolean2,boolean3).join(); return userService.findByEmail(email); }最后测量响应所花费的时间,如果花费了6秒钟以上,则说明您未运行Async方法,如果花费了2秒钟,则说明您成功了。
另请参阅以下文档:@Async
Annotation,Spring异步方法,CompletableFuture类
希望对您有所帮助。



