Nestjs Redis 是一个基于 Redis 的模块,可以让你在 Nest.js 应用程序中轻松地使用 Redis。它提供了丰富的功能,包括连接池、发布/订阅、管道、事务、Lua 脚本等。
下面是 Nestjs Redis 的完整用法:
- 安装依赖
npm install --save @nestjs-modules/redis redis
- 引入模块
在你的应用程序模块中引入 Redis 模块:
import { Module } from '@nestjs/common';
import { RedisModule } from '@nestjs-modules/redis';
@Module({
imports: [
RedisModule.forRoot({
// Redis 配置参数
config: {
host: 'localhost',
port: 6379,
},
}),
],
})
export class AppModule {}
- 注入客户端
在你的服务中注入 Redis 客户端:
import { Injectable } from '@nestjs/common';
import { RedisService } from '@nestjs-modules/redis';
@Injectable()
export class MyService {
constructor(private readonly redisService: RedisService) {}
async setValue(key: string, value: string) {
const client = this.redisService.getClient();
await client.set(key, value);
}
async getValue(key: string): Promise<string> {
const client = this.redisService.getClient();
return client.get(key);
}
}
- 使用其他 Redis 功能
除了基本的 GET 和 SET 命令之外,Nestjs Redis 还支持 Redis 的其他功能。例如,您可以使用管道和 Lua 脚本来执行复杂的 Redis 命令:
import { Injectable } from '@nestjs/common';
import { RedisService } from '@nestjs-modules/redis';
@Injectable()
export class MyService {
constructor(private readonly redisService: RedisService) {}
async usePipeline() {
const client = this.redisService.getClient();
const pipeline = client.pipeline();
pipeline.set('key1', 'value1');
pipeline.set('key2', 'value2');
return pipeline.exec();
}
async useLuaScript() {
const client = this.redisService.getClient();
const script = `
local value = redis.call('GET', KEYS[1])
if (not value) then
redis.call('SET', KEYS[1], ARGV[1])
return ARGV[1]
else
return value
end
`;
const result = await client.eval(script, 1, 'key', 'newValue');
console.log(result); // "newValue"
}
}
- 发布/订阅
您还可以使用 Nestjs Redis 来实现发布/订阅模式。首先,将 Redis 模块导入到应用程序模块中,并创建一个频道:
import { Module } from '@nestjs/common';
import { RedisModule } from '@nestjs-modules/redis';
@Module({
imports: [
RedisModule.forRoot({
// Redis 配置参数
config: {
host: 'localhost',
port: 6379,
},
}),
],
})
export class AppModule {}
然后,在您的服务中实现发布和订阅:
import { Injectable } from '@nestjs/common';
import { RedisService } from '@nestjs-modules/redis';
@Injectable()
export class MyService {
constructor(private readonly redisService: RedisService) {}
async publishMessage(channel: string, message: string) {
const client = this.redisService.getClient();
return client.publish(channel, message);
}
async subscribeToChannel(channel: string) {
const client = this.redisService.getClient();
return new Promise<string>((resolve, reject) => {
client.subscribe(channel, (err, count) => {
if (err) {
reject(err);
}
});
client.on('message', (ch, message) => {
resolve(message);
});
});
}
}
最后,您可以在 Nestjs 控制器中使用这些服务:
import { Controller, Get } from '@nestjs/common';
import { MyService } from './my.service';
@Controller()
export class MyController {
constructor(private readonly myService: MyService) {}
@Get('/publish')
async publishMessage(): Promise<string> {
await this.myService.publishMessage('my-channel', 'Hello, world!');
return 'Message published!';
}
@Get('/subscribe')
async subscribeToChannel(): Promise<string> {
const message = await this.myService.subscribeToChannel('my-channel');
return `Received message: ${message}`;
}
}
这就是 Nestjs Redis 的完整用法。使用 Nestjs Redis,您可以轻松地将 Redis 集成到 Nest.js 应用程序中,并利用其强大的功能来实现复杂的应用程序逻辑。