前后端分离:后端如何刷新 Next.js 缓存?(续)
Spring Boot 中的实现思路完全一样,只是语言和 HTTP 客户端不同:
// service/CacheRevalidationService.java
@Service
public class CacheRevalidationService {
private final WebClient webClient;
@Value("${nextjs.url}")
private String nextjsUrl;
@Value("${nextjs.revalidation-secret}")
private String revalidationSecret;
public CacheRevalidationService(WebClient.Builder webClientBuilder) {
this.webClient = webClientBuilder.build();
}
public void revalidateCache(List<String> tags) {
webClient.post()
.uri(nextjsUrl + "/api/revalidate")
.header("Authorization", "Bearer " + revalidationSecret)
.bodyValue(Map.of("tags", tags))
.retrieve()
.bodyToMono(String.class)
.doOnError(e -> log.warn("Cache revalidation failed: {}", e.getMessage()))
.onErrorComplete() // 不阻塞业务逻辑
.subscribe();
}
}