缓存

为了方便开发者进行缓存操作的组件,它有利于改善项目的性能。它为我们提供了一个数据中心以便进行高效的数据访问。

鉴于缓存的重要性,得益于midwayjs cacheopen in new window,cool-admin内置了两种缓存

提示

使用两种缓存,主要是为了项目不要过多依赖,开发者运行项目无需过多配置,但是开发者需要根据自己的需求选择对应的缓存

配置

src/config/config.default.ts

import { CoolFileConfig, MODETYPE } from '@cool-midway/file';
import { MidwayConfig } from '@midwayjs/core';
import * as fsStore from 'cache-manager-fs-hash';

// import * as redisStore from 'cache-manager-ioredis';

export default {
  // 修改成你自己独有的key
  keys: 'cool-admin for node',
  koa: {
    port: 8001,
  },
  // 缓存 可切换成其他缓存如:redis http://midwayjs.org/docs/extensions/cache
  cache: {
    store: fsStore,
    options: {
      path: 'cache',
      ttl: -1,
    },
  },
// redis
//   cache: {
//     store: redisStore,
//     options: {
//       host: '127.0.0.1', 
//       port: 6379, 
//       password: '',
//       db: 0,
//       keyPrefix: 'cache:',
//       ttl: 100
//     },
//   }
} as unknown as MidwayConfig;

使用

src/modules/demo/controller/app/cache.ts

import { DemoCacheService } from './../../service/cache';
import { Inject, Post, Provide, Get } from '@midwayjs/decorator';
import { CoolController, BaseController } from '@cool-midway/core';
import { CacheManager } from '@midwayjs/cache';

/**
 * 缓存
 */
@Provide()
@CoolController()
export class AppDemoCacheController extends BaseController {
  @Inject()
  cacheManager: CacheManager;

  @Inject()
  demoCacheService: DemoCacheService;

  /**
   * 设置缓存
   * @returns
   */
  @Post('/set')
  async set() {
    await this.cacheManager.set('a', 1);
    // 缓存10秒
    await this.cacheManager.set('a', 1, {
      ttl: 10,
    });
    return this.ok(await this.cacheManager.get('a'));
  }

  /**
   * 获得缓存
   * @returns
   */
  @Get('/get')
  async get() {
    return this.ok(await this.demoCacheService.get());
  }
}

方法缓存

有些业务场景,我们并不希望每次请求接口都需要操作数据库,如:今日推荐、上个月排行榜等,数据存储在redis

框架提供了 @CoolCache 方法装饰器,方法设置缓存,让代码更优雅

src/modules/demo/service/cache.ts

import { Provide } from '@midwayjs/decorator';
import { CoolCache } from '@cool-midway/core';

/**
 * 缓存
 */
@Provide()
export class DemoCacheService {
  // 数据缓存5秒
  @CoolCache(5)
  async get() {
    console.log('执行方法');
    return {
      a: 1,
      b: 2,
    };
  }
}

WARNING

service主要是处理业务逻辑,@CoolCache应该要在service中使用,不要在controller等其他位置使用

Last Updated: