Spring Boot传递异步数据给view



我的Spring Boot应用程序有一个小问题。我尝试使用WebClient进行异步API调用,但我如何从异步响应传递数据到html视图?

这是我的控制器代码:

@Controller
@RequiredArgsConstructor
public class HomeController {
private final WebClient.Builder webBuilder;
@GetMapping("/")
public String getHomepage() {
return "homepage";
}
@GetMapping("/api")
public String getApiResponse() {
webBuilder.build()
.get()
.uri("https://api.github.com/users/microsoft/repos")
.retrieve()
.bodyToMono(String.class)
.subscribe(response -> {
// Async Response pass data to view
});
return "apitest";
}
}

我试着这样想:

Map<String, Object> models = new HashMap<>();
Mono<List<GithubRepo>> listMono = webBuilder.build()
.get()
.uri("https://api.github.com/users/microsoft/repos")
.retrieve()
.bodyToMono(new ParameterizedTypeReference<>() {});
CompletableFuture<List<GithubRepo>> listCompletableFuture = listMono.toFuture();
List<GithubRepo> repos = listCompletableFuture.join();
models.put("json", repos);
return new ModelAndView("apitest", models);

它是正确的web应用程序?

我做了2次测试。一个使用block()函数,一个使用这个方法,这个方法比block()快,但我不知道它是正确的方法。

编辑:使用上面的方法,我的TTFB在第一次启动后是1秒,但刷新后它在40ms和100ms之间。

也许是更好的方法?

最新更新