是否可以在Spring启动控制器中使用缓存控制缓存响应?

时间:2017-09-07 11:36:53

标签: angularjs http caching spring-boot cache-control

我的要求是在浏览器级别重用一些元数据,而不是每次都从服务器请求。我的休息终点是使用spring boot编写的,我已经在我的响应中添加了Cache-control和max-age标头。我把max-age设置为10秒。根据我的理解,我们可以为css和js文件等固定资产执行此操作。是否可以使用对象(响应)。

@CrossOrigin
@RequestMapping(value = "/retrieve/{name}", method = RequestMethod.GET)
public ResponseEntity<Course> getCourses(@PathVariable String name) {
    Course course = new Course();
    HttpHeaders headers = new HttpHeaders();
    try {
        System.out.println("Call is here.");
        course = courseService.getCourse(name);
        headers.add("Cache-control", "private");
        headers.add("max-age", "10");
    } catch (Exception e) {
        return new ResponseEntity<>(course, HttpStatus.BAD_REQUEST);
    }
    return new ResponseEntity<>(course, headers, HttpStatus.OK);
}

但是在前端级别,请求仍然进入服务器并提供新的响应。我使用angualr作为我的客户端框架。我希望在完成响应头中提到的max-age值后清除响应数据。

这是相关的角度分量。

app.component('searchCourseComponent', {
bindings: {
    name: '<',
},
templateUrl: 'components/course-search/course-search.component.html',
controller: function (localStorageService, CourseService) {

    var vm = this;
    vm.searchCourseByName = function (name) {

        if (localStorageService.isSupported) {
            console.log("localStrage is supporting in this browser");
            var course = CourseService.searchCourse(name).then(function (response) {
                localStorageService.set("course", response.data);
            });
        }
        else {
            console.log("Local storage is not supporting");
        }
    };
}

});

3 个答案:

答案 0 :(得分:1)

您可以在angularJs中使用本地存储服务。 这包括index.html

中的以下内容
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-local-storage/0.7.1/angular-local-storage.min.js"></script>

LocalStorageModule注入app.module

angular.module('appName', ['LocalStorageModule'])

并在控制器中使用localStorageService注入控制器并设置您想要存储到本地存储中的值。

例如:localStorageService.set("nameForStoringData",dataToBeSet);

答案 1 :(得分:0)

您可以使用Angualr $ http缓存。它不会再发送相同的请求。

    $http({
            method: type,
            url: url,
            params: params,
            cache: true,
            responseType: responseType
        }).then(function (response) {
           // success response
        }, function (response) {
          // when something went wrong
        });

答案 2 :(得分:0)

更好的方法是,创建servlet filter并添加标题以响应您的需求。

首先创建此配置

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching 
public class CacheConfiguration { 

}

和这个servlet过滤器:

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse; 

public class CachingHttpHeadersFilter implements Filter {

    // We consider the last modified date is the start up time of the server
    private final static long LAST_MODIFIED = System.currentTimeMillis();

    private long CACHE_TIME_TO_LIVE = TimeUnit.DAYS.toMillis(1461L);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        CACHE_TIME_TO_LIVE = TimeUnit.DAYS.toMillis(365); //365 days
    }

    @Override
    public void destroy() {
        // Nothing to destroy
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

        HttpServletResponse httpResponse = (HttpServletResponse) response;

        httpResponse.setHeader("Cache-Control", "max-age=" + CACHE_TIME_TO_LIVE + ", public");
        httpResponse.setHeader("Pragma", "cache");

        // Setting Expires header, for proxy caching
        httpResponse.setDateHeader("Expires", CACHE_TIME_TO_LIVE + System.currentTimeMillis());

        // Setting the Last-Modified header, for browser caching
        httpResponse.setDateHeader("Last-Modified", LAST_MODIFIED);

        chain.doFilter(request, response);
    }
}

并注册此过滤器并添加您需要的urlPatterns:

@Bean
public FilterRegistrationBean cachingHttpHeadersFilter() throws IOException {
    log.info("Registering Caching HTTP Headers Filter");

    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setFilter(new CachingHttpHeadersFilter());
    registration.setDispatcherTypes(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC));
    registration.setName("cachingHttpHeadersFilter");
    List<String> urlPatterns = new ArrayList<>();
    urlPatterns.add("/asset*");
    registration.setUrlPatterns(urlPatterns);
    return registration;
}

注册过滤器将缓存控制标头添加到http requests/asset*的关联