在Java中,您可以使用ResponseEntity對象來設置緩存控制。以下是如何設置緩存控制的示例:
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CacheControlExample {
@GetMapping("/example")
public ResponseEntity<String> example() {
// 創建一個緩存控制對象
CacheControl cacheControl = new CacheControl();
// 設置緩存策略
cacheControl.setCacheable(true); // 允許緩存
cacheControl.setEtag("your-etag-value"); // 設置ETag值
cacheControl.setMaxAge(3600); // 設置緩存最大年齡(單位:秒)
cacheControl.setNoStore(false); // 是否存儲在內存中,設置為false表示存儲在內存中
cacheControl.setNoTransform(false); // 是否允許對響應內容進行轉換,設置為false表示允許轉換
cacheControl.setPrivate(true); // 設置為private,表示響應內容僅客戶端可以緩存
// 創建一個HttpHeaders對象,并設置緩存控制頭
HttpHeaders headers = new HttpHeaders();
headers.setCacheControl(cacheControl);
// 創建一個ResponseEntity對象,并設置狀態碼和響應頭
ResponseEntity<String> responseEntity = new ResponseEntity<>("Hello, this is an example with cache control.", headers, HttpStatus.OK);
return responseEntity;
}
}
在這個示例中,我們創建了一個CacheControl對象,并設置了緩存策略。然后,我們創建了一個HttpHeaders對象,并將緩存控制頭添加到其中。最后,我們創建了一個ResponseEntity對象,并將狀態碼和響應頭設置為相應的值。這樣,當客戶端請求/example端點時,它將收到帶有設置好的緩存控制的響應。