本文将介绍如何在 Nest 框架中集成和使用 Redis。Redis 是一个高性能的键值数据库,广泛用于缓存、会话存储等场景。我们将通过具体的操作步骤、命令示例和注意事项,帮助您快速上手。
在开始之前,请确保您已经安装了以下软件:
首先,您需要创建一个新的 NestJS 项目。如果您还没有安装 NestJS CLI,请先通过以下命令安装:
npm install -g @nestjs/cli
然后,使用 NestJS CLI 创建新项目:
nest new my-redis-app
进入项目目录:
cd my-redis-app
为了让 Nest 能够与 Redis 交互,我们需要安装一个 Redis 客户端库,推荐使用 ioredis,因为它支持 Promise 和多种 Redis 特性。
npm install ioredis
接下来,我们可以使用 @nestjs/redis 模块来简化 Redis 的集成:
npm install @nestjs/redis
在项目的 app.module.ts 中添加 Redis 模块的配置:
import { Module } from '@nestjs/common';
import { RedisModule } from '@nestjs/redis';
@Module({
imports: [
RedisModule.forRoot({
host: 'localhost',
port: 6379,
}),
],
})
export class AppModule {}
在上面的代码中,我们使用 RedisModule.forRoot() 方法配置 Redis 连接。请根据您的 Redis 服务器地址和端口进行调整。
为了更好地管理 Redis 操作,建议创建一个服务来封装 Redis 的操作。
import { Injectable } from '@nestjs/common';
import { InjectRedis, Redis } from '@nestjs/redis';
@Injectable()
export class RedisService {
constructor(@InjectRedis() private readonly redis: Redis) {}
async set(key: string, value: string) {
await this.redis.set(key, value);
}
async get(key: string) {
return await this.redis.get(key);
}
async del(key: string) {
await this.redis.del(key);
}
async exists(key: string) {
return await this.redis.exists(key);
}
}
在这个服务中,我们封装了常用的 set、get、del 和 exists 函数。
接下来,我们可以在任意模块中使用这个 Redis 服务。以 app.controller.ts 为例:
import { Controller, Get, Param, Post, Body } from '@nestjs/common';
import { RedisService } from './redis.service';
@Controller('redis')
export class AppController {
constructor(private readonly redisService: RedisService) {}
@Post('set')
async setKey(@Body() body: { key: string; value: string }) {
await this.redisService.set(body.key, body.value);
return { status: 'success' };
}
@Get('get/:key')
async getKey(@Param('key') key: string) {
const value = await this.redisService.get(key);
return { key, value };
}
@Post('delete')
async deleteKey(@Body() body: { key: string }) {
await this.redisService.del(body.key);
return { status: 'deleted' };
}
}
在这个控制器中,我们定义了三个路由:
启动您的 Nest.js 应用:
npm run start
您可以使用 Postman 或 CURL 测试 API 接口:
curl -X POST http://localhost:3000/redis/set -H "Content-Type: application/json" -d "{\"key\": \"testKey\", \"value\": \"testValue\"}"
curl http://localhost:3000/redis/get/testKey
curl -X POST http://localhost:3000/redis/delete -H "Content-Type: application/json" -d "{\"key\": \"testKey\"}"
docker run --name some-redis -d redis
const pipeline = this.redis.pipeline();
pipeline.set(key1, value1);
pipeline.set(key2, value2);
await pipeline.exec();
await this.redis.set(key, value, 'EX', 60); // 60秒后过期
this.redis.publish('channel', JSON.stringify(data));
通过以上步骤,我们成功在 Nest 环境中集成并使用了 Redis。您可以根据实际需求扩展 Redis 服务,提高应用性能。