복붙노트

[SPRING] 스프링 부트에서 HTTP 응답 캐싱을 사용하는 방법

SPRING

스프링 부트에서 HTTP 응답 캐싱을 사용하는 방법

스프링 부트 1.0.2를 사용하여 REST 서버를 구현했다. HTTP 캐싱을 사용하지 못하게하는 HTTP 헤더를 설정하지 못하게하는 데 문제가 있습니다.

내 컨트롤러는 다음과 같습니다.

@Controller
public class MyRestController {
    @RequestMapping(value = "/someUrl", method = RequestMethod.GET)
    public @ResponseBody ResponseEntity<String> myMethod(
            HttpServletResponse httpResponse) throws SQLException {
        return new ResponseEntity<String>("{}", HttpStatus.OK);
    }
}

모든 HTTP 응답에는 다음 헤더가 포함됩니다.

Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Expires: 0
Pragma: no-cache

나는 그 머리말을 제거하거나 바꾸기 위하여 뒤에 오는 것을 시도했다 :

위의 어떤 것도 효과가 없습니다. Spring Boot의 모든 요청이나 개별 요청에 대해 어떻게 헤더를 비활성화하거나 변경합니까?

해결법

  1. ==============================

    1.no-cache HTTP 헤더는 Spring Security에 의해 설정된다. 이는 http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#headers에서 논의됩니다.

    no-cache HTTP 헤더는 Spring Security에 의해 설정된다. 이는 http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#headers에서 논의됩니다.

    다음은 HTTP 응답 헤더 Pragma : no-cache를 비활성화하지만 문제를 해결하지 않습니다.

    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
    
    @Configuration
    @EnableWebMvcSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            // Prevent the HTTP response header of "Pragma: no-cache".
            http.headers().cacheControl().disable();
        }
    }
    

    위와 같은 클래스에서 다음과 같이 공개 정적 리소스에 대해 Spring Security를 ​​완전히 비활성화했습니다.

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/static/public/**");
    }
    

    이를 위해서는 두 개의 리소스 핸들러를 설정하여 캐시 컨트롤 헤더를 올바르게 설정해야합니다.

    @Configuration
    public class MvcConfigurer extends WebMvcConfigurerAdapter
            implements EmbeddedServletContainerCustomizer {
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            // Resources without Spring Security. No cache control response headers.
            registry.addResourceHandler("/static/public/**")
                .addResourceLocations("classpath:/static/public/");
    
            // Resources controlled by Spring Security, which
            // adds "Cache-Control: must-revalidate".
            registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/")
                .setCachePeriod(3600*24);
        }
    }
    

    Spring Boot & Spring Security 응용 프로그램에서 정적 웹 자원 검색하기를 참조하십시오.

  2. ==============================

    2.나는이 Spring Extension을 발견했다 : https://github.com/foo4u/spring-mvc-cache-control.

    나는이 Spring Extension을 발견했다 : https://github.com/foo4u/spring-mvc-cache-control.

    3 단계 만 수행하면됩니다.

    1 단계 (pom.xml) :

    <dependency>
        <groupId>net.rossillo.mvc.cache</groupId>
        <artifactId>spring-mvc-cache-control</artifactId>
        <version>1.1.1-RELEASE</version>
        <scope>compile</scope>
    </dependency>
    

    2 단계 (WebMvcConfiguration.java) :

    @Configuration
    public class WebMvcConfig extends WebMvcConfigurerAdapter implements WebMvcConfigurer {
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new CacheControlHandlerInterceptor());
        }
    }
    

    3 단계 (컨트롤러) :

    @Controller
    public class MyRestController {
    
        @CacheControl(maxAge=31556926)
        @RequestMapping(value = "/someUrl", method = RequestMethod.GET)
        public @ResponseBody ResponseEntity<String> myMethod(
                HttpServletResponse httpResponse) throws SQLException {
            return new ResponseEntity<String>("{}", HttpStatus.OK);
        }
    }
    
  3. ==============================

    3.나는 비슷한 문제에 부딪친 다. 브라우저에 캐시 된 동적 리소스 (이미지)를 얻고 싶었습니다. 이미지가 바뀌면 (아주 ​​자주는 아님) 나는 uri의 일부를 바꾼다 ... 이것이 나의 해결책이다.

    나는 비슷한 문제에 부딪친 다. 브라우저에 캐시 된 동적 리소스 (이미지)를 얻고 싶었습니다. 이미지가 바뀌면 (아주 ​​자주는 아님) 나는 uri의 일부를 바꾼다 ... 이것이 나의 해결책이다.

        http.headers().cacheControl().disable();
        http.headers().addHeaderWriter(new HeaderWriter() {
    
            CacheControlHeadersWriter originalWriter = new CacheControlHeadersWriter();
    
            @Override
            public void writeHeaders(HttpServletRequest request, HttpServletResponse response) {
                Collection<String> headerNames = response.getHeaderNames();
                String requestUri = request.getRequestURI();
                if(!requestUri.startsWith("/web/eventImage")) {
                    originalWriter.writeHeaders(request, response);
                } else {
                   //write header here or do nothing if it was set in the code
                }       
            }
        });
    
  4. ==============================

    4.

    @Configuration
    @EnableAutoConfiguration
    public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
    
            registry.addResourceHandler("/resources/**")
                    .addResourceLocations("/resources/")
                    .setCachePeriod(31556926);
    
        }
    }
    
  5. ==============================

    5.정적 리소스를 인증 할 필요가 없다면 다음과 같이 할 수 있습니다.

    정적 리소스를 인증 할 필요가 없다면 다음과 같이 할 수 있습니다.

    import static org.springframework.boot.autoconfigure.security.servlet.PathRequest.toStaticResources;
    
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    ...
        @Override
        public void configure(WebSecurity webSecurity) throws Exception {
            webSecurity
                    .ignoring()
                    .requestMatchers(toStaticResources().atCommonLocations());
        }
    ...
    }
    

    그리고 당신의 application.properties :

    spring.resources.cache.cachecontrol.max-age=43200
    

    설정할 수있는 추가 등록 정보는 ResourceProperties.java를 참조하십시오.

  6. from https://stackoverflow.com/questions/24164014/how-to-enable-http-response-caching-in-spring-boot by cc-by-sa and MIT license