-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
接口数据缓存 #8
Comments
有没有讨论过localstorage的大小限制呢 |
@jasminecjc 如果超过接口大小的话,存储会不成功(相当于无缓存情况),localStorage应该是Mb级别的,对于大多数的接口应该都没问题 |
如果客户端频繁更换登录的账号,估计没多久会超出localStorage的大小限制吧,如果项目较大,缓存的接口数据较多,有没有一些更好的解决方法呢?之前考虑过使用变量对常更新的接口数据进行缓存,但是过程有点繁琐,一直在寻找更好的解决方案。 |
我是 localStorage 存储失败,则使用变量进行缓存。过程还可控,不会太繁琐。 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
场景
用户可能访问的多个页面中有相同的接口请求,该接口的数据更新不会很频繁(时效性要求不高),例如侧边栏数据接口。
为什么要接口缓存
如果每次访问页面都要去请求相同的接口,不仅消耗服务器端资源,而且对网页性能也有损失。
如果可以做到接口数据的缓存,还能让用户以最快时间获得数据。
如何做接口缓存
可以考虑结合现代浏览器中的本地存储方案localStorage来实现接口数据的缓存。
首次请求接口后,将此时的时间戳和接口数据存储到
localStorage
中,再次请求数据时将通过比对时间戳判断是否在缓存时间内(缓存的时间间隔可以自定义,例如五分钟),如果在时间内则直接读取数据,否则将重新发起请求并更新时间戳和接口数据。假设现在需要请求这样一个接口的数据,那么接下来的流程是如何进行的呢?
步骤1 - 需要检测浏览器的支持性(由于
localStorage
只能存储字符串,所以还需要检测对JSON的支持):步骤2.1 - 如果特性检测未通过,则正常发起请求
步骤2.2 - 如果特性检测通过,则获取
localStorage
中存储的时间戳和数据步骤2.2.1 - 如果存在时间戳,且在有效的缓存时间内,则直接使用缓存的接口数据
步骤2.2.2 - 如果不存在时间戳或者不在有效的缓存时间内,则重新发起接口请求,获取数据后更新时间戳和接口数据到
localStorage
组件
具体代码可参考我编写的api-cache组件
The text was updated successfully, but these errors were encountered: