如何将缓存控制添加到@RepositoryRestResource

时间:2017-01-17 14:31:59

标签: spring-boot

我有一个存储库,我需要添加HTTP缓存标头(缓存控制:max-age = 12000,eTag:" 123"。

@RepositoryRestResource(path = "locations")
public interface LocationRepository extends PagingAndSortingRepository{
    @Query(value = "from Location WHERE (LOWER(name) LIKE LOWER(:locationName) OR LOWER(alias1) LIKE LOWER(:locationName) OR LOWER(alias2) LIKE LOWER(:locationName)) and active = 1")
    List findByName(@Param("locationName") String locationName,
              @PageableDefault(page = 0, size = 5) Pageable pageable);

1 个答案:

答案 0 :(得分:1)

只需添加一个过滤器,该过滤器将添加标题并将其映射到您想要的网址格式:

public class CacheControlFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
            response.addHeader("Cache-Control", "max-age=12000, eTag:\"123\"");

            filterChain.doFilter(request, response);
    }

}

您的配置中的某处:

@Bean
public FilterRegistrationBean cacheControlFilter() {
    FilterRegistrationBean registration = new FilterRegistrationBean();
    Filter filter = new CacheControlFilter();
    registration.setFilter(filter);
    registration.addUrlPatterns("/whatever/*");
    return registration;
}