UNPKG

@zenweb/cache

Version:
86 lines (72 loc) 1.49 kB
# ZenWeb Cache Module 基于 Redis 的对象缓存工具 功能如下: - 对象缓存 - 大对象自动压缩 - JSON 序列直接输出 - 防止缓存击穿 - 单例执行 ## 安装 ```bash yarn add @zenweb/cache ``` ```ts title="src/index.ts" import { create } from 'zenweb'; import modCache from '@zenweb/cache'; const app = create(); app.setup(modCache()); app.start(); ``` ## 使用 ```ts 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; } } ```