在Spring中为多个RestController端点配置Cache-Control

时间:2018-05-01 00:49:00

标签: spring cache-control spring-restcontroller

我有一个带有Spring 5的Api端点作为@RestController,我想一次为所有端点指定Cache-Control(通过Config或Annotation,......)。

目前我对每种方法都这样做。我还必须使用ResponseEntity来设置Cache-Control,这会使代码更加膨胀。

@RestController
@RequestMapping("/api")
public class MyApi {

    @PostMapping("/search")
    public ResponseEntity<SearchResultDto> search(SearchDto searchDto) {
        // ...
        return ResponseEntity.ok()
                .cacheControl(CacheControl.maxAge(20, TimeUnit.SECONDS))
                .body(searchResultDto);
    }

    @GetMapping("/get")
    public ResponseEntity<EntityDto> get(Long id) {
        // ...
        return ResponseEntity.ok()
                .cacheControl(CacheControl.maxAge(20, TimeUnit.SECONDS))
                .body(entityDto);
    }

    // ... more methods

}
  • 我尝试了Aspects,但是在创建后无法更改http标头。
@Aspect
@Component
public class CacheAspect {

    @Pointcut("within(io.company.MyApi)")
    public void apiMethods() {
    }

    @Around("apiMethods()")
    public Object addCacheControlOnResponseEntity(ProceedingJoinPoint pjp) throws Throwable {
        Object retval = pjp.proceed();

        if (retval instanceof ResponseEntity) {
            ((ResponseEntity) retval).getHeaders().setCacheControl(CacheControl.maxAge(15, TimeUnit.SECONDS));
            // exception is thrown, because map can not be modified anymore
        }

        return retval;
    }
}
  • 我尝试过拦截器(HandlerInterceptor),但这里也是同样的问题,以后不能修改http头。
@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
                response.setHeader(HttpHeaders.CACHE_CONTROL, CacheControl.maxAge(2, TimeUnit.SECONDS).getHeaderValue());
                // header does not get modified
            }

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
                response.setHeader(HttpHeaders.CACHE_CONTROL, CacheControl.maxAge(2, TimeUnit.SECONDS).getHeaderValue());
                // header does not get modified
            }
        });
    }
}
  • 我尝试添加资源处理程序(ResourceHandler)(通常用于静态内容)并为/ api / **设置缓存策略,但未应用。
@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/api/**")
                .setCacheControl(CacheControl.maxAge(10, TimeUnit.SECONDS));
        // didn't had any effect
    }
}

......我没有想法

如何减少重复/样板代码?

0 个答案:

没有答案