簡體   English   中英

如何在使用 angular7 和 springboot 構建的 Web 應用程序中使瀏覽器緩存無效

[英]How to invalidate browser cache in a web application built with angular7 and springboot

我正在開發一個 web 應用程序,使用 springboot 為后端服務 rest API 和 Angular7 為前端。

我的應用程序需要很長時間才能加載,因為它必須在服務器上執行大量處理,所以我決定通過存儲緩存數據來提高性能,以便首先加載頁面並最終在處理結束時更新數據。

這可行,但我遇到了一個問題:當我在 Angular 中更新數據時,這些數據通常保存在我的數據庫中,但如果我更新頁面,我看不到更改,因為瀏覽器繼續訪問舊的緩存數據而不是獲取新的修改。

有沒有辦法在修改瀏覽器緩存中的某些數據時使其無效?

彈簧靴:

我的休息控制器端點類似於:

  @GetMapping(value = "/users")
  public Iterable<User> getAllUsers(HttpServletResponse response) {
    response.setHeader("Cache-Control", "max-age=3600");
    return this.userService.findAll());
  }

我的服務:

  @Cacheable("users")
  public Iterable<User> findAll() {
    return this.userRepository.findAll();
  }

我的角度服務:

  getUsers(): Observable<User[]> {
    return this.http.get<User[]>(`<ip>' + '/users');
  }

我可以看到您正在服務器端進行緩存,您可以通過調用帶有@CacheEvict注釋的方法以及您要驅逐的密鑰來驅逐緩存:

@CacheEvict(value = "users", allEntries = true)

或者您可以使用CacheManager以編程方式執行此操作:

@Autowired
CacheManager cacheManager;

public void evictSingleCacheValue(String cacheName, String cacheKey) {
    cacheManager.getCache(cacheName).evict(cacheKey);
}

您可以通過輕量級請求檢查服務器端基於時間或基於內容的控件是否有任何更改。

基於時間 => 您可以在標題中使用 Last=Modified

基於內容 => 你可以使用 Etag

請檢查這兩個鏈接; https://devcenter.heroku.com/articles/increasing-application-performance-with-http-cache-headers

https://www.logicbig.com/quick-info/web/last-modified-and-if-modified-since.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM