@zenweb/cache
TypeScript icon, indicating that this package has built-in type declarations

4.3.1 • Public • Published

ZenWeb Cache Module

基于 Redis 的对象缓存工具

功能如下:

  • 对象缓存
  • 大对象自动压缩
  • JSON 序列直接输出
  • 防止缓存击穿
  • 单例执行

安装

yarn add @zenweb/cache
import { create } from 'zenweb';
import modCache from '@zenweb/cache';

const app = create();

app.setup(modCache());

app.start();

使用

import { Context, mapping } from "zenweb";
import { $cache, cached } from "@zenweb/cache";

export class CacheController {
  /**
   * 一般使用
   */
  @mapping()
  async index() {
    const result = await $cache.lockGet('TEST', function() {
      return {
        cacheAt: new Date(),
      };
    });
    return result;
  }

  /**
   * 大对象压缩存储
   */
  @mapping()
  async big() {
    const result = await $cache.lockGet('TEST-GZ', function() {
      return longData;
    });
    return result;
  }

  /**
   * 大对象直接输出 - 1
   */
  @mapping()
  async big_direct_out(ctx: Context) {
    const result = await $cache.lockGet('TEST-GZ', function() {
      return longData;
    }, { parse: false, decompress: false });
    if (result.compressed) {
      ctx.set('Content-Encoding', 'gzip');
    }
    ctx.type = 'json';
    ctx.body = result.data;
  }

  /**
   * 使用缓存中间件
   * - 自动处理是否需要解压缩对象
   */
  @mapping({
    middleware: cached('TEST-middleware'),
  })
  async cached_middleware() {
    return longData;
  }
}

Package Sidebar

Install

npm i @zenweb/cache

Weekly Downloads

34

Version

4.3.1

License

MIT

Unpacked Size

26.7 kB

Total Files

16

Last publish

Collaborators

  • yefei777