본문 바로가기

Web/spring

[Spring framework Web MVC docs] 1.10. HTTP Caching

728x90

https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-caching

 

Web on Servlet Stack

Spring Web MVC is the original web framework built on the Servlet API and has been included in the Spring Framework from the very beginning. The formal name, "Spring Web MVC," comes from the name of its source module (spring-webmvc), but it is more commonl

docs.spring.io

 

틀린 내용은 알려주시면 감사합니다 💐


 

 

1.10. HTTP Caching

 

HTTP 캐싱은 웹 애플리케이션의 성능을 크게 향상시킬 수 있다

HTTP Caching 은 Cache-COntrol response header와 그 후 조건부 요청 헤더(Last-Modified 및 ETag) 를 중심으로 한다

Cache-Control은 개인(브라우저) 및 공용(proxy) 캐시에 응답을 캐시해주고 재사용하는 방법을 알려준다

ETag header는 컨텐츠의 변경이 없을 경우 본문 없이 304(NOT_MODIFIED)가 발생할 수 있는 조건부 요청을 만들 때 사용한다

ETag는 Last-MOdified header보다 더 정교하다

 

 

HTTP Caching 관련 option 을 살펴본다

 

 

1.10.1. CacheControl

CacheControl 은  Cache-Control  header 과 관련된 설정을 지원하고 여러 위치에서 인수로 허용한다

 

 

RFC 7234 는 Cache-COntrol response header에 대해 가능한 많은 describes가 있지만

CacheControl type은 일반적인 시나리오에 포커스된 use case-oriented approch 방식은 취한다

 

 

// Cache for an hour - "Cache-Control: max-age=3600"
CacheControl ccCacheOneHour = CacheControl.maxAge(1, TimeUnit.HOURS);

// Prevent caching - "Cache-Control: no-store"
CacheControl ccNoStore = CacheControl.noStore();

// Cache for ten days in public and private caches,
// public caches should not transform the response
// "Cache-Control: max-age=864000, public, no-transform"
CacheControl ccCustom = CacheControl.maxAge(10, TimeUnit.DAYS).noTransform().cachePublic();

 

WebContentGenerator also accepts a simpler cachePeriod property (defined in seconds) that works as follows:

// 초 단위로 정의되는 cachePeriod 속성도 허용한다

 

  • A -1 value does not generate a Cache-Control response header. > -1은 생성 안함
  • A 0 value prevents caching by using the 'Cache-Control: no-store' directive. > 0은 캐싱방지
  • An n > 0 value caches the given response for n seconds by using the 'Cache-Control: max-age=n' directive. > 주어진 응답을 캐싱

 

1.10.2. Controllers

 

Controller는 HTTP Caching 에 대한 명시적 지원을 추가할 수 있다

Resource의 lastModified 나 ETag 값을 조건부 요청 헤더와 비교하려면 이렇게 작업하면 된다

 

ETag header 및 Cache-Control 설정은 ResponseEntity에 추가한 예제이다 

@GetMapping("/book/{id}")
public ResponseEntity<Book> showBook(@PathVariable Long id) {

    Book book = findBook(id);
    String version = book.getVersion();

    return ResponseEntity
            .ok()
            .cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
            .eTag(version) // lastModified is also available
            .body(book);
}

조건부 요청 헤더와 비교한 결과의 컨텐츠가 변경되지 않았을 경우 (304) 빈 본문과 함께 304(NOT_MODIFIED) response를 보낸다

그렇지 않으면 ETag 및 Cache-Control header에 응답이 추가될 것이다

 

 

아니면 conditional request headers에서 확인할 수도 있다

@RequestMapping
public String myHandleMethod(WebRequest request, Model model) {

    long eTag = ...  // Application-specific calculation. 애플리케이션 마다 계산을 해준다

    if (request.checkNotModified(eTag)) {
    	// The response has been set to 304 (NOT_MODIFIED) — no further processing
        // 304 로 설정되어 처리 안함
        return null; 
    }

	//Continue with the request processing.
    // 요청 처리 계속 진행
    model.addAttribute(...); 
    return "myViewName";
}

There are three variants for checking conditional requests against eTag values, lastModified values, or both. For conditional GET and HEAD requests, you can set the response to 304 (NOT_MODIFIED).

 

For conditional POST, PUT, and DELETE, you can instead set the response to 412 (PRECONDITION_FAILED), to prevent concurrent modification.

 

GET, HEAD 일 경우는 304(NOT_MODIFIED)로 설정할 수 있다

POST, PUT, DELETE 일 경우 412(PRECONDITION_FAILED)로 응답하도록 설정하여 동시 수정을 방지한다

 

 

 

1.10.3. Static Resources

Cache-Control의 성능을 최적화 하기 위해 Conditional response header 에 static resources를 함께 제공해야한다

 

정리된 부분이 있다

1.12.10. Static Resources

https://delightpip.tistory.com/52

 

[Spring framework Web MVC docs] 1.12. MVC Config

https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-config Web on Servlet Stack Spring Web MVC is the original web framework built on the Servlet API and has been included in the Spring Framework from the very beginning. The fo

delightpip.tistory.com

 

 

1.10.4. ETag Filter

ShallowEtagHeaderFilter를 사용하여 response contents 에서 계산된 "shallow" eTag 값을 추가할 수 있다.

대역폭은 절약되지만 CPU 시간은 절약되지 않는다고 한다.

 

정리된 부분이 있다

1.2.3. Shallow ETag

https://delightpip.tistory.com/53

 

[Spring framework Web MVC docs] 1.2. Filters

https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#filters Web on Servlet Stack Spring Web MVC is the original web framework built on the Servlet API and has been included in the Spring Framework from the very beginning. The forma

delightpip.tistory.com

 

728x90