Web本地缓存的正确使用

最终答案:

1.将缓存localStorage、sessionStorage放在VueX中统一进行维护

2.要对本地缓存做时效处理

3.要对缓存做加密处理

4.根据版本生成缓存键

export const LOCALE_KEY = 'LOCALE__';
// 生成缓存配置,主要包含过期时间、是否加密、根据版本生成缓存键
const createOption = createOptions(localStorage,{TimeOut:24*60*60*7})
const ls = createStorage(createOption);
const lsLocaleSetting = ls.get(LOCALE_KEY) || localeSetting;

export const useLocaleStore = define({
    id: 'app-locale',
    state: (): LocaleState => ({
        // 缓存信息
        localInfo: lsLocaleSetting,
    }),
    getters:{},
    actions:{
        // 同步修改本地、VueX的缓存信息
        setLocaleInfo(info) {
             this.localInfo = { ...this.localInfo, ...info };
             ls.set(LOCALE_KEY, this.localInfo);
        },
        // 初始化VueX、本地的缓存信息,这里主要是国际化配置
        initLocale() {
          this.setLocaleInfo({
            ...localeSetting,
            ...this.localInfo,
          });
        },
    }
})

export const localeSetting = {
  showPicker: true,
  // 地点
  locale: LOCALE.ZH_CN,
  // 默认语言
  fallback: LOCALE.ZH_CN,
  // 可用地区
  availableLocales: [LOCALE.ZH_CN, LOCALE.EN_US],
};
export const LOCALE = {
  ZH_CN: 'zh_CN',
  EN_US: 'en',
};
const createOptions = (storage: Storage, options: Options = {}): Options => {
  return {
    // 开发模式不加密
    hasEncrypt: enableStorageEncryption,
    storage,
    // 根据版本生成缓存键
    prefixKey: getStorageShortName(),
    ...options,
  };
};

// 根据当前开发所处的环境判断是否使用aes加密系统缓存
export const enableStorageEncryption = !isDevMode();
// 判断是否处于开发环境
export function isDevMode(): boolean {
  return import.meta.env.DEV;
}

// 根据版本生成缓存键,格式为:项目名__所处环境__版本号__
export function getStorageShortName() {
  return `${getCommonStoragePrefix()}${`__${pkg.version}`}__`.toUpperCase();
}

export function getCommonStoragePrefix() {
  // 从环境中获取项目名
  const { VITE_GLOB_APP_SHORT_NAME } = import.meta.env;
  // 获取当前环境是开发还是生产并记录
  return `${VITE_GLOB_APP_SHORT_NAME}__${import.meta.env.MODE}`.toUpperCase();
}


// key和iv是Aes加密所需的自定义密钥
export const createStorage({
  storage = sessionStorage,
  key = cacheCipher.key,
  iv = cacheCipher.iv,
  timeout = null,
  hasEncrypt = true,
  prefixKey = ''
}: Partial<CreateStorageParams> = {}) => {
  // 判断密钥格式是否正确
  if (hasEncrypt && [key.length, iv.length].some((item) => item !== 16)) {
    throw new Error('When hasEncrypt is true, the key or iv must be 16 bits!');
  }
  // 创建Aes加密工具
  const encryption = new AesEncryption({ key, iv });

  // 构造本地缓存实体类
  const WebStorage = class WebStorage {
    private storage: Storage;
    private prefixKey?: string;
    private encryption: AesEncryption;
    private hasEncrypt: boolean;
    

    constructor() {
      this.storage = storage;
      this.prefixKey = prefixKey;
      this.encryption = encryption;
      this.hasEncrypt = hasEncrypt;
    }
    
    //prefixKey格式为:项目名__所处环境__版本号__
    private getKey(key: string) {
      return `${this.prefixKey}${key}`.toUpperCase();
    }

    // key是缓存键,value是值,expire是过期时间(秒)
    set(key: string, value: any, expire: number | null = timeout) {
      const stringData = JSON.stringify({
        value,
        time: Date.now(),
        expire: !expire ? new Date().getTime() + expire * 1000 : null,
      });
      // 是否加密value
      const stringifyValue = this.hasEncrypt
        ? this.encryption.encryptByAES(stringData)
        : stringData;
      // 设置缓存
      this.storage.setItem(this.getKey(key), stringifyValue);
    }

    
    get(key: string, def: any = null): any {
      const val = this.storage.getItem(this.getKey(key));
      if (!val) return def;

      try {
        // 是否需要解密
        const decVal = this.hasEncrypt ? this.encryption.decryptByAES(val) : val;
        const data = JSON.parse(decVal);
        const { value, expire } = data;
        // 判断是否过期
        if (isNullOrUnDef(expire) || expire >= new Date().getTime()) {
          return value;
        }
        // 过期则移除
        this.remove(key);
      } catch (e) {
        return def;
      }
    }

    
    remove(key: string) {
      this.storage.removeItem(this.getKey(key));
    }

   
    clear(): void {
      this.storage.clear();
    }
  };
  return new WebStorage();
};

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Web端网站本地缓存测试是指测试一个网站在浏览器本地缓存中的功能是否正常。在现代的Web应用中,为了提高网站的性能和用户体验,常常会使用本地缓存来减少网络请求,加快页面加载速度。 进行Web端网站本地缓存测试时,首先可以通过清除浏览器缓存来模拟用户首次访问网站的情况。然后,访问网站的各个页面,并在浏览器的开发者工具中的Network面板中观察请求的情况。正常情况下,在首次访问后,一些常用的资源如样式表、脚本文件和图片等应该被缓存在本地,下次访问同一个页面时能够直接从缓存加载,而不需要再次向服务器发送请求。通过观察请求的状态码和响应时间等信息,可以确定缓存是否生效。 另外,还可以测试网站在缓存策略上的正确性。比如,设置不同的缓存过期时间和Etag头,然后测试不同时间点再次访问同一个页面时缓存的更新情况。在开发者工具的Network面板中,可以观察到资源的状态是从服务器下载还是从缓存加载,以及缓存是否按照预期的更新。 在测试过程中,还需要注意一些常见的问题。比如,某些浏览器可能会有自己的缓存机制,可能会对某些资源进行额外的缓存处理,需要确认这些情况是否符合设计要求。另外,由于浏览器缓存是根据URL进行存储的,所以如果网站使用了动态URL参数等,需要确保缓存策略不会因为URL的不同而失效。 通过以上的测试,可以确定网站的本地缓存功能是否正常,并且根据测试结果进行优化和调整,以提高网站的性能和用户体验。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值