axios请求的缓存与重复请求过滤的封装plus

26次阅读

共计 7781 个字符,预计需要花费 20 分钟才能阅读完成。

前言

网站性能优化是属于每一个网站的必备过程,而最直接简单的就是 http 请求的优化,包含了减少 http 请求的数量,加快 http 请求的速度。
而本篇文章,将从http 请求数量进行入手,将无用、无效请求全部过滤掉

开始

本篇将基于 axios 开源库,对 http 请求进行封装,包含 请求的缓存、重复请求的过滤 两个小优化。

第一步

首先建立一个 http-helper.js 文件,里面将 基于 axios进行上述相关功能的封装
首先里面的内容大概是这样的:

import axios from 'axios';

const http = axios.create();

export default http

上述就是简单地导出了一个 axios 实例,供项目使用

增加请求缓存功能

那么有了缓存功能,就要对 缓存命中 进行定义,我定义的缓存命中是指:http 请求的 url 相同、请求参数相同、请求类型相同 ,以上三者都相同的情况下,就视为缓存允许命中,最后根据 缓存过期时间 ,判断是否获取最新数据,还是从缓存中取。
下面理一下流程:

  1. 发起请求,设置请求是否缓存,缓存多长时间
  2. axios 请求拦截,判断该请求是否设置缓存,是?则判断是否缓存命中、是否过期,否?则继续发起请求
  3. axios 响应拦截,判断该请求结果是否缓存,是?则缓存数据,并设置 key 值、过期时间

针对上面的流程,需要有几点确认一下:

  1. 当缓存命中时,如何终止请求
    axios 中,可以为每一个请求设置一个 cancleToken,当调用请求取消方法的时候,则请求终止,并将终止的消息通过reject 回传给请求方法。
  2. 当缓存命中时,并 将缓存的数据通过 resolve()返回给请求方法,而不是在 reject 中获取缓存数据

那么具体的代码可以是这样的:

// http-helper.js
import axios from 'axios';

const http = axios.create();

http.interceptors.request.use((config) => {
    /**
     * 为每一次请求生成一个 cancleToken
     */
    const source = axios.CancelToken.source();
    config.cancelToken = source.token;
    /**
     * 尝试获取缓存数据
     */
    const data = storage.get(cryptoHelper.encrypt(config.url + JSON.stringify(config.data) + (config.method || ''),
    ));
    /** 
    * 判断缓存是否命中,是否未过期
    */
    if (data && (Date.now() <= data.exppries)) {console.log(` 接口:${config.url} 缓存命中 -- ${Date.now()} -- ${data.exppries}`);
        /**
        * 将缓存数据通过 cancle 方法回传给请求方法
        */
        source.cancel(JSON.stringify({
            type: CANCELTTYPE.CACHE,
            data: data.data,
        }));
    }
    return config;
});

http.interceptors.response.use((res) => {if (res.data && res.data.type === 0) {if (res.config.data) {
            /**
            * 获取请求体参数
            */
            const dataParse = JSON.parse(res.config.data);
            if (dataParse.cache) {if (!dataParse.cacheTime) {dataParse.cacheTime = 1000 * 60 * 3;}
                /**
                * 加密
                * 缓存
                */
                storage.set(cryptoHelper.encrypt(res.config.url + res.config.data + (res.config.method || '')), {
                    data: res.data.data, // 响应体数据
                    exppries: Date.now() + dataParse.cacheTime, // 设置过期时间});
                console.log(` 接口:${res.config.url} 设置缓存,缓存时间: ${dataParse.cacheTime}`);
            }
        }
        return res.data.data;
    } else {return Promise.reject('接口报错了!');
    }
});

/**
 * 封装 get、post 请求
 * 集成接口缓存过期机制
 * 缓存过期将重新请求获取最新数据,并更新缓存
 * 数据存储在 localstorage
 * {
 *      cache: true
 *      cacheTime: 1000 * 60 * 3  -- 默认缓存 3 分钟
 * }
 */
const httpHelper = {get(url, params) {return new Promise((resolve, reject) => {http.get(url, params).then(async (res) => {resolve(res);
            }).catch((error) => {if (axios.isCancel(error)) {const cancle = JSON.parse(error.message);
                    if (cancle.type === CANCELTTYPE.REPEAT) {return resolve([]);
                    } else {return resolve(cancle.data);
                    }
                } else {return reject(error);
                }
            });
        });
    },
    post(url: string, params: any) {return new Promise((resolve, reject) => {http.post(url, params).then(async (res) => {resolve(res);
            }).catch((error: AxiosError) => {if (axios.isCancel(error)) {const cancle = JSON.parse(error.message);
                    if (cancle.type === CANCELTTYPE.REPEAT) {return resolve(null);
                    } else {return resolve(cancle.data);
                    }
                } else {return reject(error);
                }
            });
        });
    },
};
export default httpHelper

上面代码中,有些东西没有解释到:

  1. 其中 storage 是自己封装的缓存数据类,可以有 .get、.set 等方法,cryptoHelper是封装的 MD5 加密库,主要是 通过 MD5 加密请求 url、请求数据、请求类型等拼接的字符串,通过加密后的 key 来获取缓存中的数据(因为拼接后的字符串太长,通过 MD5 加密一下,会短很多)
  2. 为什么要单独封装一个 httpHelper, 因为 axios.CancelToken.source().cancle(***) 中的信息,只能在 reject 中取到,为了缓存命中时,仍然能在 then 中获取到正确的数据,则需要单独处理一下这个情况。

增加重复请求过滤功能

规则:以最新的请求为主,即最新的重复请求,会将之前的重复请求中断掉
大概流程如下:

  1. 发起请求
  2. axios 请求拦截,判断请求列表数组中,是否存在相同的请求,是?终止之前所有重复请求,否?将当次请求添加进请求数组中,最终都继续会请求
  3. axios 响应拦截器,将当次请求从请求数组中删除

具体代码如下:

// http-helper.js
import axios from 'axios';

const http = axios.create();

const pendingRequests = [];

http.interceptors.request.use((config) => {
    /**
     * 为每一次请求生成一个 cancleToken
     */
    const source = axios.CancelToken.source();
    config.cancelToken = source.token;
    // .... 省略部分代码
    /**
     * 重复请求判断
     * 同 url,同请求类型判定为重复请求
     * 以最新的请求为准
     */
    const md5Key = cryptoHelper.encrypt(config.url + (config.method || ''));
    /**
     * 将之前的重复且未完成的请求全部取消
     */
    const hits = pendingRequests.filter((item) => item.md5Key === md5Key);
    if (hits.length > 0) {hits.forEach((item) => item.source.cancel(JSON.stringify({
            type: CANCELTTYPE.REPEAT,
            data: '重复请求,以取消',
        })));
    }
    /**
     * 将当前请求添加进请求对列中
     */
    pendingRequests.push({
        md5Key,
        source,
    });
    return config;
});

http.interceptors.response.use((res) => {
    /**
     * 不论请求是否成功,* 将本次完成的请求从请求队列中移除
     */
    // 以同样的加密方式 (MD5) 获取加密字符串
    const md5Key = cryptoHelper.encrypt(res.config.url + (res.config.method || ''));
    const index = pendingRequests.findIndex((item) => item.md5Key === md5Key);
    if (index > -1) {pendingRequests.splice(index, 1);
    }
    // .... 省略部分代码
});

// .... 省略部分代码

其实逻辑很简单,通过一个数组去维护请求列表即可

最终成果物

是用 ts 写的,需要使用可以改成 js
由于缓存和终止重复请求,都需要用到 source.cancle,因此需要一个 type 值, 区分是缓存命中终止,还是重复请求终止 ,代码中是CANCELTTYPE 常量。
http-helper.ts

import axios, {CancelTokenSource, AxiosResponse, AxiosRequestConfig, AxiosError} from 'axios';
import Storage from './storage-helper';
import CryptoHelper from './cryptoJs-helper';

const CANCELTTYPE = {
    CACHE: 1,
    REPEAT: 2,
};

interface ICancel {
    data: any;
    type: number;
}

interface Request {
    md5Key: string;
    source: CancelTokenSource;
}
const pendingRequests: Request[] = [];

const http = axios.create();
const storage = new Storage();
const cryptoHelper = new CryptoHelper('cacheKey');

http.interceptors.request.use((config: AxiosRequestConfig) => {
    /**
     * 为每一次请求生成一个 cancleToken
     */
    const source = axios.CancelToken.source();
    config.cancelToken = source.token;
    /**
     * 缓存命中判断
     * 成功则取消当次请求
     */
    const data = storage.get(cryptoHelper.encrypt(config.url + JSON.stringify(config.data) + (config.method || ''),
    ));
    if (data && (Date.now() <= data.exppries)) {console.log(` 接口:${config.url} 缓存命中 -- ${Date.now()} -- ${data.exppries}`);
        source.cancel(JSON.stringify({
            type: CANCELTTYPE.CACHE,
            data: data.data,
        }));
    }
    /**
     * 重复请求判断
     * 同 url,同请求类型判定为重复请求
     * 以最新的请求为准
     */
    const md5Key = cryptoHelper.encrypt(config.url + (config.method || ''));
    /**
     * 将之前的重复且未完成的请求全部取消
     */
    const hits = pendingRequests.filter((item) => item.md5Key === md5Key);
    if (hits.length > 0) {hits.forEach((item) => item.source.cancel(JSON.stringify({
            type: CANCELTTYPE.REPEAT,
            data: '重复请求,以取消',
        })));
    }
    /**
     * 将当前请求添加进请求对列中
     */
    pendingRequests.push({
        md5Key,
        source,
    });
    return config;
});

http.interceptors.response.use((res: AxiosResponse) => {
    /**
     * 不论请求是否成功,* 将本次完成的请求从请求队列中移除
     */
    // 以同样的加密方式 (MD5) 获取加密字符串
    const md5Key = cryptoHelper.encrypt(res.config.url + (res.config.method || ''));
    const index = pendingRequests.findIndex((item) => item.md5Key === md5Key);
    if (index > -1) {pendingRequests.splice(index, 1);
    }
    if (res.data && res.data.type === 0) {if (res.config.data) {const dataParse = JSON.parse(res.config.data);
            if (dataParse.cache) {if (!dataParse.cacheTime) {dataParse.cacheTime = 1000 * 60 * 3;}
                storage.set(cryptoHelper.encrypt(res.config.url + res.config.data + (res.config.method || '')), {
                    data: res.data.data,
                    exppries: Date.now() + dataParse.cacheTime,});
                console.log(` 接口:${res.config.url} 设置缓存,缓存时间: ${dataParse.cacheTime}`);
            }
        }
        return res.data.data;
    } else {return Promise.reject('接口报错了!');
    }
});

/**
 * 封装 get、post 请求
 * 集成接口缓存过期机制
 * 缓存过期将重新请求获取最新数据,并更新缓存
 * 数据存储在 localstorage
 * {
 *      cache: true
 *      cacheTime: 1000 * 60 * 3  -- 默认缓存 3 分钟
 * }
 */
const httpHelper = {get(url: string, params: any) {return new Promise((resolve, reject) => {http.get(url, params).then(async (res: AxiosResponse) => {resolve(res);
            }).catch((error: AxiosError) => {if (axios.isCancel(error)) {const cancle: ICancel = JSON.parse(error.message);
                    if (cancle.type === CANCELTTYPE.REPEAT) {return resolve([]);
                    } else {return resolve(cancle.data);
                    }
                } else {return reject(error);
                }
            });
        });
    },
    post(url: string, params: any) {return new Promise((resolve, reject) => {http.post(url, params).then(async (res: AxiosResponse) => {resolve(res);
            }).catch((error: AxiosError) => {if (axios.isCancel(error)) {const cancle: ICancel = JSON.parse(error.message);
                    if (cancle.type === CANCELTTYPE.REPEAT) {return resolve(null);
                    } else {return resolve(cancle.data);
                    }
                } else {return reject(error);
                }
            });
        });
    },
};

export default httpHelper;

cryptoJs-helper.ts

import cryptoJs from 'crypto-js';

class CryptoHelper {
    public key: string;
    constructor(key: string) {
        /**
        * 如需秘钥,可以在实例化时传入
        */
        this.key = key;
    }
    /**
     * 加密
     * @param word
     */
    public encrypt(word: string | undefined): string {if (!word) {return '';}
        const encrypted = cryptoJs.MD5(word);
        return encrypted.toString();}
}

export default CryptoHelper;

storage-helper.ts

class Storage {public get(key: string | undefined) {if (!key) {return;}
        const text = localStorage.getItem(key);
        try {if (text) {return JSON.parse(text);
            } else {localStorage.removeItem(key);
                return null;
            }
        } catch {localStorage.removeItem(key);
            return null;
        }
    }
    public set(key: string | undefined, data: any) {if (!key) {return;}
        localStorage.setItem(key, JSON.stringify(data));
    }
    public remove(key: string | undefined) {if (!key) {return;}
        localStorage.removeItem(key);
    }
}

export default Storage;

如有问题,希望指正,感谢!

正文完
 0