简体   繁体   中英

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

I'm developing a web application using springboot for the backend serving rest API and Angular7 for the frontend.

my application takes so much time to load because it has to perform a lot of processing on the server, so I decided to improve the performance by storing the cached data in order to load the page first and eventually update the data when processing ends.

This works but I'm having a problem: When I update data in Angular these are normally saved in my database but if I update the page I don't see the changes because the browser continues to access the old cached data rather than getting the new ones modified.

Is there a way to invalidate certain data in the browser cache when they are modified?

Springboot:

My rest controller endpoint are similar to that:

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

My service:

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

My angular service:

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

I can see you're caching on the server side, you can evict cache by calling method annotated with @CacheEvict with the key you want to evict:

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

Or you can do this programmatically by using CacheManager :

@Autowired
CacheManager cacheManager;

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

You can check if there is any changes in your server side Time-based or Content-based controls by lightweight requests.

Time-based => your can use Last=Modified in the header

Content-based => you can use Etag

please check these two links; 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM