如何将 API 数据预先加载到 Model 中,再由模板渲染,而不是在模板中发起请求?
解读
面试官真正想确认的是:
- 你是否理解“服务端渲染”与“客户端渲染”的边界——Thymeleaf 的价值就在于前者;
- 你是否熟悉 Spring MVC 与 Thymeleaf 的协作链路,能把 REST 数据在“进入模板之前”就准备好;
- 你是否具备实际工程意识:超时、线程池、缓存、事务边界、N+1 查询、SEO 友好、首屏性能等国内生产环境必考项。
一句话:让数据“躺着”进模板,而不是让模板“跪着”去求数据。
知识点
- Spring Boot 控制器层:@Controller、@GetMapping、@RequestParam、@PathVariable
- 远程调用:RestTemplate、WebClient、OpenFeign、Retrofit,以及各自的超时、重试、熔断配置(国内常用 Sentinel、Hystrix)
- 异步编排:@Async、CompletableFuture、自定义 ThreadPoolTaskExecutor,防止 Tomcat 线程被阻塞
- 缓存层:Spring Cache(@Cacheable)、Caffeine、Redis 二级缓存,解决高频 API 穿透
- 领域转换:DTO → VO,使用 MapStruct 或 BeanUtils,避免把第三方 JSON 直接塞进 Model
- Thymeleaf 上下文:Model、ModelMap、ModelAndView,以及 Spring 表达式工具对象 #uris、#dates、#numbers
- 异常处理:@ControllerAdvice + @ExceptionHandler,保证 API 异常能降级,模板依旧可渲染兜底数据
- 国内部署细节:阿里云 ECS 内网 SLB 调用 API、Nginx 反向代理加缓存头、HTTPS 证书带来的 SNI 问题
- SEO 与首屏:服务端直出 HTML,避免 Ajax 二次请求,提升熊掌号、微信爬虫、头条蜘蛛的收录率
- 安全:防 SSRF 白名单、Token 传递、敏感字段脱敏,满足国内等保 2.0 要求
答案
步骤一:在 Controller 中一次性把数据拉齐
@Controller
@RequiredArgsConstructor
public class GoodsPageController {
private final GoodsRemoteService goodsRemoteService; // OpenFeign 客户端
private final ThreadPoolTaskExecutor executor; // 自定义线程池
@GetMapping("/goods/{goodsId}")
public String detail(@PathVariable Long goodsId, Model model) throws Exception {
// 1. 异步并发拉取 3 组数据,避免串行等待
CompletableFuture<GoodsDetailDTO> goodsFuture = CompletableFuture
.supplyAsync(() -> goodsRemoteService.getGoods(goodsId), executor);
CompletableFuture<List<CommentDTO>> commentFuture = CompletableFuture
.supplyAsync(() -> goodsRemoteService.listComments(goodsId), executor);
CompletableFuture<PromoDTO> promoFuture = CompletableFuture
.supplyAsync(() -> goodsRemoteService.getPromo(goodsId), executor);
// 2. 等待全部完成,设置统一超时 800ms(国内生产一般 500~1000ms)
CompletableFuture.allOf(goodsFuture, commentFuture, promoFuture).get(800, TimeUnit.MILLISECONDS);
// 3. 领域转换 → 模板安全 VO
GoodsPageVO vo = GoodsPageVO.builder()
.goods(convert(goodsFuture.get()))
.comments(convert(commentFuture.get()))
.promo(convert(promoFuture.get()))
.build();
// 4. 塞进 Model,属性名与 Thymeleaf 保持一致
model.addAttribute("page", vo);
return "goods/detail"; // 视图名,对应 templates/goods/detail.html
}
}
步骤二:Thymeleaf 模板只负责“填充”,不再发任何 HTTP 请求
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="${page.goods.title}+' - 某某电商'">商品标题</title>
<meta name="keywords" th:content="${page.goods.keywords}"/>
</head>
<body>
<h1 th:text="${page.goods.title}">标题占位</h1>
<section th:replace="~{fragments/comment :: list(comments=${page.comments})}">评论区域</section>
<div th:replace="~{fragments/promo :: bar(promo=${page.promo})}">促销条</div>
</body>
</html>
步骤三:兜底与降级
- 任何远程调用超时或熔断,catch 后填充空对象或默认文案,保证模板不报错,用户依旧看到骨架屏;
- 使用 Spring Cache 把热点商品缓存 30s,单机 Caffeine + 分布式 Redis 双层,防止大促把内部 API 打挂;
- 对外网关层加 CDN,缓存最终 HTML,TTL 10s,兼顾实时性与并发量,满足国内“618”“双11”峰值。
拓展思考
- 如果页面需要个性化(如用户昵称、推荐商品),可把“公共数据”服务端渲染,“私有数据”片段化异步加载,国内叫“同构渲染”或“孤岛架构”,兼顾 SEO 与体验。
- 对于需要多端复用的场景,可把上述逻辑下沉到 BFF(Backend-for-Frontend)层,使用 Spring Cloud Gateway + WebFlux,非阻塞 IO 把 RT 降到 50ms 以内。
- 数据聚合层再往前一步就是 GraphQL,国内阿里、美团内部叫“奇门”或“通天塔”,解决前端“字段冗余”和“多次往返”痛点,但引入 Node 中间层要注意 JVM 与 V8 的线程模型差异。
- 监控:在 Controller 方法上加 @Timed(Micrometer)把“API 拉取耗时”与“整体渲染耗时”分别上报到 Prometheus,Grafana 大盘实时告警,防止“模板等数据”把整体 TTFB 拖垮。