Node、Nest 中使用 Redis

各种官方客户端包

node 中推荐 <font style="color:rgb(37, 41, 51);">redis</font> <font style="color:rgb(37, 41, 51);">ioredis</font>

redis

npm install redis

tips: Node.js 中,要想顶级 await(top-level await)在 JS 文件中正常工作,有两个重要的前提:你的代码必须运行在模块环境中,也就是说,你需要将你的文件标记为 ES 模块。这可以通过在package.json 中添加”type”: “module”,或者使用.mjs 文件扩展名来实现。node 版本必须为 14.8.0 以及更高.

(函数中还是需要 async 哦)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { createClient } from "redis";

const client = createClient({
socket: {
host: "localhost",
port: 6379,
},
});

client.on("error", (err) => console.log("[redis client error]===>", err));

await client.connect();

const value = await client.keys("*");

await client.hSet("xiaobazi", "name", "heihei");
await client.hSet("xiaobazi", "age", 12);

await client.disconnect();

ioredis

npm install ioredis

1
2
3
4
5
6
7
8
9
10
import Redis from "ioredis";

// ioredis会默认 host: 'localhost', port: 6379
const redis = new Redis();

const res = await redis.keys("*");

console.log(res);

redis.disconnect();

Nest 中使用

如果在 nest 里,可以直接通过 <font style="color:rgb(37, 41, 51);">useFactory</font> 动态创建一个 provider,在里面使用 redis 的 npm 包创建连接。或是官方的 caching 方案。

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
// AppModule.ts
import { Module } from "@nestjs/common";
import { AppController } from "./app.controller";
import { AppService } from "./app.service";
import { createClient } from "redis";

@Module({
imports: [],
controllers: [AppController],
providers: [
AppService,
{
provide: "REDIS_CLIENT",
useFactory: async () => {
const client = createClient({
socket: {
host: "localhost",
port: 6379,
},
});
await client.connect();
return client;
},
},
],
})
export class AppModule {}

// AppService.ts
import { Inject, Injectable } from "@nestjs/common";
import { RedisClientType } from "redis";

@Injectable()
export class AppService {
@Inject("REDIS_CLIENT")
private redisClient: RedisClientType;

async getHello() {
const value = await this.redisClient.keys("*");
console.log(value);
return "Hello World!";
}
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!