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

2020/5/25 11:56:51

本文主要是介绍axios请求的缓存与重复请求过滤的封装(plus),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

前言

网站性能优化是属于每一个网站的必备过程,而最直接简单的就是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;

复制代码

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



这篇关于axios请求的缓存与重复请求过滤的封装(plus)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程