php - RESTful 缓存的工作原理(和使用)

标签 php rest

我开发了一个非常小的REST API(使用PHP),它提供有关用户的信息(还更新和创建用户,但这对问题来说并不重要)。只是为了显示可用的调用(顺便说一下,JSON 输出):

/api/users/54216

/api/users/54216?fields=id,name

/api/users/54216/photos

54216 是一个示例用户 ID。

直到今天,我只使用缓存来保存要显示的 html 页面,真的并不复杂 - 从未使用缓存来只保存数据。

我应该怎么做才能保存这些调用,然后如何使用它?我的目标是(我认为..)在 X 分钟一次将数据保存到 JSON 文件中,并在需要时获取文件缓存并对其进行解码

另外,您建议我如何缓存用户的特定信息?因为调用 no.1 输出所有信息,调用 no.2 只输出特定字段,所以我不想使用 2 个缓存文件,因为它确实没有效果。

我从来没有参与过这个部分(缓存[json]数据和REST API,这是我第一次),所以我很困惑。

编辑:

我说的是服务器端缓存。

最佳答案

我建议您阅读HTTP Cache

The first important principal is to understand how HTTP Caching Works, there are basically two parts, TTL (Cache-Control) and Stale Check (ETag). When a resource is generated by an origin server you need to think of it is gone. You no longer have control over it, you only get to make suggestions to the client what to do with it. The two mechanism you have are TTL (which is how long the client should keep the object in cache before checking back) and Stale Check (which is a version of the resource that was returned) that can be sent with a new GET request to the origin server, to say "Hey I have this version is it still good". Giving the Origin server the opportunity to say yep, keeping using that one and provide a new TTL, if it is still valid.

You need to use these two controls in different ways to get the effects you want. For instance when serving files that will never change (like the css for a build) you can set a really long TTL, and no etag. For something that doesn't change very often, but when it does change needs to be quick (like the party members on a reservation) you would set a low TTL (like 1 minute) and an ETag. In this second example you set a low TTL of 1 minute to help with bursts from clients to not overwhelem the origin server (scale) and the ETag allows the Origin server to skip the construction of the reservation object, if it has a way to verify what the current valid ETag is faster than constructing the entire reservation. Another example would be something that doesn't change often and when it does, it can propagate slowly (like a user's ad recommendation profile) You can set a higher TTL (like 6 hours) and not worry so much about an ETag (although it would still be useful). REf: https://groups.google.com/d/msg/api-craft/YJMH0XMQJIM/HtdAPEXbQLMJ

或者,如果您想在服务器端缓存,请查看 memcached ( tutorial )

还可以查看反向代理缓存解决方案,例如 varnish等等

关于php - RESTful 缓存的工作原理(和使用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14391824/

相关文章:

python - 使用 HTTP Digest 身份验证保护 REST 端点

php - 打印嵌套数组 PHP

php - MYSQLi 多条记录输出重复项

javascript - 如何在 for 循环中调用 custom.js 文件,我想用这个 js 传递一些参数

java - 这个在 Spring 中处理 POST 请求的 REST 方法到底是如何工作的?

rest - Grails rest 插件 SSLexception 奇怪的域名比较 (domainname/ip-address)

php - 缓存问题 MySQL 或 Filesystem

php - 添加 MCrypt 的 AES-CBC 加密后数据未保存到数据库或未正确解密

wcf - 除了 RESTful HTTP 之外,我还应该支持其他任何东西吗?

spring - 如何使用 REST-ful URL 创建 Spring 3 + Tiles 2 webapp?