[Spring] CacheControl

태량·2023년 7월 11일
0

찾아본 계기

jsp는 css 파일과 같은 정적리소스를 어떻게 효율적으로 처리할지에 대한 궁금증이 생겼다. 그리고 http 캐싱에 대한 생각에 다달았으며, 요청의 캐싱을 응답 서버에선 캐싱처리를 어떻게 하는지 궁금해졌다.

클래스 사용법

Spring http 패키지에 있는 CacheControl을 이용한다.

CacheControl은 생성자가 protected 되어 있기에 CacheControl 클래스의 static 메소드를 통해 객체

를 받아서 사용한다. 받은 객체에 응답 Directive(지시문)값을 설정하고, ResourceHandlerRegistry

컨트롤할 리소스의 경로와 파일이름 그리고 사용자가 설정을 바꾼 CacheControl 객체를 담아

Dispatcher에게 전달하게 된다.

Http cache Directive

요청

Cache-Control: max-age=<seconds>   캐쉬된 리소스의 유통기한.
Cache-Control: max-stale[=<seconds>] 유통기한이 조금 지난 리소스도 seconds초 융통성 있게 봐줄게
Cache-Control: min-fresh=<seconds>  요청자 : 적어도 이정도 유통기한의 리소스를 주라
Cache-control: no-cache
Cache-control: no-store
Cache-control: no-transform
Cache-control: only-if-cached

확장

Cache-control: immutable

Cache-control: max-age 1,stale-while-revalidate=59
- 1초마다 들어오는 리소스는 캐쉬된 놈으로 쓸게, 아 근데 1초 지나고 60초 이전의 요청에선 너가 준 캐쉬를 쓰긴 하는데, 업데이트 된게 있는지 확인은 할꺼야.
- 그리고 어떤 사용자가 60초를 넘겨서 요청을 하면 전에 업데이트 됐다고 한 놈 다시 갱신해줘.

Cache-control: stale-if-error=<seconds>

응답

  1. must-revalidate : 캐시 사용하기전에 반드시 서버에 새로운 것이 있는지 확인하고 써라.
  2. proxy-revalidate : 공유캐시 버전 must-revalidate
  3. immutable : 너한테 준 캐시 안 변할꺼니깐 물어보지말고 계속 써!
Cache-control: must-revalidate 
- 유통기한 지난 캐시 사용하기전에 반드시 서버에 새로운 것이 있는지 확인하고 써라.
Cache-control: no-cache
- 캐쉬 쓸려고 할때마다 서버한테 검사 받아. 0초마다
Cache-control: no-store
- 캐쉬 복사본 저장하지 마!
Cache-control: no-transform
Cache-control: public
Cache-control: private
Cache-control: proxy-revalidate
Cache-Control: max-age=<seconds>
Cache-control: s-maxage=<seconds>

실제 메이저 사이트 응답에서 cache-control: no-cache, no-store, must-revalidate 의 형태로 no-cache 와 must-revalidate를 함께 명시하는 이유

  • 완벽하게 캐쉬를 무효화하기 위함이다.
  • 하지만 오랜된 브라우저와의 호환, 버그, 프록시 캐시 업체들의 존재로 인해 no-store만으로는 캐시 무효화가 적용되지 않을 수 있기에
profile
좋은 영향력과 교류를 위하여

0개의 댓글