Spring Boot中REST架构Cacheable原则的实现及API响应缓存标记方法
REST架构核心原则:Cacheable 与Spring Boot实现方案
Cacheable是REST架构的核心约束之一,要求响应必须隐式或显式标记自身为可缓存/不可缓存;若响应可缓存,客户端有权在指定时段内将其数据复用至等效请求。
下面是在Spring Boot项目的Controller API方法中实现响应缓存标记的几种常用方式:
1. 使用CacheControl工具类(Spring Framework 6+)
Spring 6及以上版本提供了简洁的缓存配置工具,可直接在响应构建器中定义缓存规则:
import org.springframework.http.CacheControl; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.concurrent.TimeUnit; @RestController public class CacheDemoController { @GetMapping("/api/cached-data") public ResponseEntity<String> getCachedResponse() { String responseContent = "这是允许客户端缓存10分钟的响应内容"; return ResponseEntity.ok() // 设置缓存时长10分钟,允许CDN等公共缓存节点存储 .cacheControl(CacheControl.maxAge(10, TimeUnit.MINUTES).cachePublic()) .body(responseContent); } }
2. 手动设置Cache-Control响应头
针对旧版本Spring(低于6.x)或需要自定义复杂缓存指令的场景,可直接构造响应头:
import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class LegacyCacheController { @GetMapping("/api/legacy-cached-data") public ResponseEntity<String> getLegacyCachedResponse() { String responseContent = "兼容旧版本Spring的可缓存响应"; HttpHeaders headers = new HttpHeaders(); // 配置公共缓存,有效期10分钟(600秒) headers.set("Cache-Control", "public, max-age=600"); return ResponseEntity.ok() .headers(headers) .body(responseContent); } }
3. 标记响应不可缓存
如果API返回实时敏感数据,需要明确禁止任何缓存存储,可设置no-store指令:
@GetMapping("/api/non-cacheable-data") public ResponseEntity<String> getNonCacheableResponse() { String responseContent = "此响应禁止任何缓存存储"; return ResponseEntity.ok() .cacheControl(CacheControl.noStore()) .body(responseContent); }
内容的提问来源于stack exchange,提问作者dataminers
相关产品推荐
相关产品推荐

