Skip to content

Cell - 缓存组件 ​

Cell 后端的命名缓存管理器,基于 cache-manager 5。

bash
npm install @celljs/cache
ts
import { Autowired, Component, Named } from '@celljs/core';
import { CacheManager } from '@celljs/cache';

@Component()
export class UserService {
    @Autowired(CacheManager)                 // 名为 "default" 的缓存
    protected readonly cache: CacheManager;

    @Autowired(CacheManager) @Named('sessions')
    protected readonly sessions: CacheManager;

    getUser(id: string) {
        return this.cache.wrap(`user:${id}`, () => this.load(id), 60_000);   // 计算一次,保留 60 毫秒
    }
}

CacheManager 有 get、set(key, value, ttl?)、del、reset 和 wrap(key, fn, ttl?) 方法。首次注入时创建一个管理器。

配置(cache.config) ​

为每个缓存名称设置一个条目:

yaml
cache:
  config:
    default:
      store: memory
      max: 100            # 条目数
      ttl: 3600000        # 毫秒
    sessions:
      store: redis-yet    # 需要 cache-manager-redis-yet 包
      url: "${env.REDIS_URL}"
      ttl: 86400000
  • ttl 以毫秒为单位,与 cache-manager 5 一致。默认缓存保留条目 3600 毫秒。
  • store 是 memory 或你安装的 store 包名:redis(cache-manager-redis)、redis-store、redis-yet、ioredis、ioredis-yet、mongodb、mongoose、fs-binary、fs-hash、hazelcast、memcached-store、memory-store(各有 cache-manager-<name> 包)。其他键是该 store 的选项。
  • 条目列表组成多级缓存(multiCaching):读操作依次尝试每个 store。
  • 注入未配置的名称会抛出 Not found cache options.

绑定自己的 CacheStoreFactory(rebind: true)以另外的方式创建 store。