UNPKG

@zenweb/cache

Version:
129 lines (109 loc) 2.53 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; } } ``` ## 进阶优化 使用 msgpackr 序列化 + snappy 压缩 ```ts import { create } from 'zenweb'; import modCache from '@zenweb/cache'; import { Packr } from 'msgpackr'; import * as snappy from 'snappy'; const SNAPPY_MAGIC_HEADER = Buffer.from('SNAPPY'); const packer = new Packr(); const app = create(); app.setup(cache({ serializer: { deserialize(data) { return packer.unpack(data) }, serialize(data) { return packer.pack(data) }, }, compressor: { isCompressed(data) { return SNAPPY_MAGIC_HEADER.equals(data.subarray(0, SNAPPY_MAGIC_HEADER.length)); }, async compress(data) { const compressed = await snappy.compress(data); return Buffer.concat([SNAPPY_MAGIC_HEADER, compressed]); }, async decompress(data) { const result = await snappy.uncompress(data.subarray(SNAPPY_MAGIC_HEADER.length)); return typeof result === 'string' ? Buffer.from(result) : result; }, }, })); app.start(); ```