wangzhibo
6 天以前 3f249e399659dcd09d3fe58071b146e50e45c17f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
---
description: 缓存(Cache)
globs: 
---
# 缓存
 
为了方便开发者进行缓存操作的组件,它有利于改善项目的性能。它为我们提供了一个数据中心以便进行高效的数据访问。
 
:::
 
## 使用
 
```ts
import { InjectClient, Provide } from '@midwayjs/core';
import { CachingFactory, MidwayCache } from '@midwayjs/cache-manager';
 
@Provide()
export class UserService {
 
  @InjectClient(CachingFactory, 'default')
  cache: MidwayCache;
 
  async invoke(name: string, value: string) {
    // 设置缓存
    await this.cache.set(name, value);
    // 获取缓存
    const data = await this.cache.get(name);
    // ...
  }
}
```
 
## 换成 Redis (v7.1 版本)
 
安装依赖,具体可以查看@midwayjs cache
 
```bash
pnpm i cache-manager-ioredis-yet --save
```
 
`src/config/config.default.ts`
 
```ts
import { CoolFileConfig, MODETYPE } from "@cool-midway/file";
import { MidwayConfig } from "@midwayjs/core";
// redis缓存
import { redisStore } from "cache-manager-ioredis-yet";
 
export default {
  // Redis缓存
  cacheManager: {
    clients: {
      default: {
        store: redisStore,
        options: {
          port: 6379,
          host: "127.0.0.1",
          password: "",
          ttl: 0,
          db: 0,
        },
      },
    },
  },
} as unknown as MidwayConfig;
```
 
## 换成 Redis (以往版本)
 
```bash
pnpm i cache-manager-ioredis --save
```
 
`src/config/config.default.ts`
 
```ts
import { CoolFileConfig, MODETYPE } from "@cool-midway/file";
import { MidwayConfig } from "@midwayjs/core";
// redis缓存
import * as redisStore from "cache-manager-ioredis";
 
export default {
  // Redis缓存
  cache: {
    store: redisStore,
    options: {
      port: 6379,
      host: "127.0.0.1",
      password: "",
      db: 0,
      keyPrefix: "cool:",
      ttl: null,
    },
  },
} as unknown as MidwayConfig;
```
 
## 使用
 
`src/modules/demo/controller/open/cache.ts`
 
```ts
import { DemoCacheService } from "../../service/cache";
import { Inject, Post, Provide, Get, InjectClient } from "@midwayjs/core";
import { CoolController, BaseController } from "@cool-midway/core";
import { CachingFactory, MidwayCache } from "@midwayjs/cache-manager";
 
/**
 * 缓存
 */
@Provide()
@CoolController()
export class AppDemoCacheController extends BaseController {
  @InjectClient(CachingFactory, "default")
  midwayCache: MidwayCache;
 
  @Inject()
  demoCacheService: DemoCacheService;
 
  /**
   * 设置缓存
   * @returns
   */
  @Post("/set")
  async set() {
    await this.midwayCache.set("a", 1);
    // 缓存10秒
    await this.midwayCache.set("a", 1, 10 * 1000);
    return this.ok(await this.midwayCache.get("a"));
  }
 
  /**
   * 获得缓存
   * @returns
   */
  @Get("/get")
  async get() {
    return this.ok(await this.demoCacheService.get());
  }
}
```
 
## 方法缓存
 
有些业务场景,我们并不希望每次请求接口都需要操作数据库,如:今日推荐、上个月排行榜等,数据存储在 redis
 
框架提供了 `@CoolCache` 方法装饰器,方法设置缓存,让代码更优雅
 
`src/modules/demo/service/cache.ts`
 
```ts
import { Provide } from "@midwayjs/core";
import { CoolCache } from "@cool-midway/core";
 
/**
 * 缓存
 */
@Provide()
export class DemoCacheService {
  // 数据缓存5秒
  @CoolCache(5000)
  async get() {
    console.log("执行方法");
    return {
      a: 1,
      b: 2,
    };
  }
}
```
 
::: warning
service 主要是处理业务逻辑,`@CoolCache`应该要在 service 中使用,不要在 controller 等其他位置使用
:::