Skip to content
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

Open
tjuking opened this issue Nov 3, 2015 · 4 comments
Open

接口数据缓存 #8

tjuking opened this issue Nov 3, 2015 · 4 comments

Comments

@tjuking
Copy link
Owner

tjuking commented Nov 3, 2015

场景

用户可能访问的多个页面中有相同的接口请求,该接口的数据更新不会很频繁(时效性要求不高),例如侧边栏数据接口。

为什么要接口缓存

如果每次访问页面都要去请求相同的接口,不仅消耗服务器端资源,而且对网页性能也有损失。

如果可以做到接口数据的缓存,还能让用户以最快时间获得数据。

如何做接口缓存

可以考虑结合现代浏览器中的本地存储方案localStorage来实现接口数据的缓存。

首次请求接口后,将此时的时间戳和接口数据存储到localStorage中,再次请求数据时将通过比对时间戳判断是否在缓存时间内(缓存的时间间隔可以自定义,例如五分钟),如果在时间内则直接读取数据,否则将重新发起请求并更新时间戳和接口数据。

假设现在需要请求这样一个接口的数据,那么接下来的流程是如何进行的呢?

步骤1 - 需要检测浏览器的支持性(由于localStorage只能存储字符串,所以还需要检测对JSON的支持):

    //是否支持localStorage的特性检测
    function supportStorage() {
        try {
            localStorage.setItem("storageSupport", "1");
            localStorage.removeItem("storageSupport");
            return true;
        } catch (e) {
            return false;
        }
    }

        //是否支持JSON的检测
    function supportJson() {
        return window.JSON && JSON.stringify && typeof JSON.stringify == "function" && JSON.parse && typeof JSON.parse == "function";
    }

步骤2.1 - 如果特性检测未通过,则正常发起请求

步骤2.2 - 如果特性检测通过,则获取localStorage中存储的时间戳和数据

步骤2.2.1 - 如果存在时间戳,且在有效的缓存时间内,则直接使用缓存的接口数据

步骤2.2.2 - 如果不存在时间戳或者不在有效的缓存时间内,则重新发起接口请求,获取数据后更新时间戳和接口数据到localStorage

组件

具体代码可参考我编写的api-cache组件

@jasminecjc
Copy link

有没有讨论过localstorage的大小限制呢

@tjuking
Copy link
Owner Author

tjuking commented Mar 13, 2017

@jasminecjc 如果超过接口大小的话,存储会不成功(相当于无缓存情况),localStorage应该是Mb级别的,对于大多数的接口应该都没问题

@Sniper-2
Copy link

如果客户端频繁更换登录的账号,估计没多久会超出localStorage的大小限制吧,如果项目较大,缓存的接口数据较多,有没有一些更好的解决方法呢?之前考虑过使用变量对常更新的接口数据进行缓存,但是过程有点繁琐,一直在寻找更好的解决方案。

@lazy-b
Copy link

lazy-b commented Nov 3, 2019

我是 localStorage 存储失败,则使用变量进行缓存。过程还可控,不会太繁琐。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants