JS之给频繁的请求结果增加缓存

由于后端限制不能频繁请求,所以500ms内的二次请求会返回服务器繁忙,请稍后再试,但是业务需要对同一接口频繁进行多次请求,因此,可以通过给请求结果增加缓存来解决。

request.js修改:增加adapter配置

import axios from 'axios'
import cacheAdapterEnhancer from './axiosCacheAdapter';

// create an axios instance
const service = axios.create({
  adapter: cacheAdapterEnhancer,
  baseURL: import.meta.env.VITE_APP_BASE_API, // api 的 base_url
  withCredentials: true // 跨域请求时发送 cookies
})

axiosCacheAdapter.js:

import axios from 'axios';

const cache = new Map();
const EXPIRATION_TIME_MS = 1 * 600; // 缓存过期时间

const cacheAdapterEnhancer = async (config) => {

  const { url, method, params, data, isCached } = config;
  if (!isCached) {
    return axios.defaults.adapter(config);
  }
  const cacheKey = JSON.stringify({ url, method, params, data });

  if (cache.has(cacheKey)) {
    const cachedResult = cache.get(cacheKey);
    if (Date.now() - cachedResult.timestamp < EXPIRATION_TIME_MS) {
      return Promise.resolve(cachedResult.data);
    } else {
      cache.delete(cacheKey);
    }
  }

  const response = await axios.defaults.adapter(config);
  const cacheValue = {
    timestamp: Date.now(),
    data: response,
  };
  cache.set(cacheKey, cacheValue);

  return response;
};

export default cacheAdapterEnhancer;

给需要缓存的接口增加isCached的配置。

// 查询表结构(表头)
getSheetCols(id) {
    return request({
        url: `/field/getSheetCols/${id}`,
        method: 'get',
        isCached: true
    })
}

即可。

posted @ 2025-04-13 12:53  罗毅豪  阅读(34)  评论(0)    收藏  举报