How to proper design a restful API to invalidate a cache?

后端 未结 2 1362
长情又很酷
长情又很酷 2021-02-13 14:53

I have an Application which requires data from Service2, which will return the same answer for a given request, forever, unless its backing database is updated. The database is

2条回答
  •  眼角桃花
    2021-02-13 15:43

    This might not answer your question directly but you may also want to look into HTTP ETags, which are well suited for caching in RESTful designs.

    The idea would be that Application would GET a resource from Service2, which would return the resource along with a ETag header (it could be a last modified timestamp or a hash). Application would then cache that resource along with the ETag.

    When Application needs to work with the resource again, it can send a HTTP GET to Service2 with the ETag header it has in cache.

    • If Service2 finds that the resource has not been changed since it was returned to Application the first time, it returns an empty response with HTTP status 304 (not modified) indicating that Application can use the data in cache.
    • If the data has been updated, Service2 returns the new resource with a new ETag header (and HTTP status 200).

    This approach works well if you don't mind the HTTP GET to see if the resource changed and if it's easy to Service2 can determine whether the resource has changed (without having to load it).

    The advantage is that Service2 doesn't have to invalidate the cache of it clients (Application), which might not be a very good practice (and could be hard to do if you have a lot of clients).

提交回复
热议问题