# 前言
Redis 是一个开源的内存存储的数据结构服务器,可用作数据库,高速缓存和消息队列代理。
因为是内存数据库,所以大多数情况把它用来做数据缓存服务,得益于它的高性能,目前 Web 应用中普遍都会使用 Redis.
今天就拿之前的 Nest9.0 框架集成一个 Redis 服务,由于 nest 官方没有 Redis 模块,我们只能采用第三方的模块了
一些第三方 Redis 模块都只适配 Nest8 版本,针对 Nest9 版本的目前找到一个比较好的 nestjs-redis-plus
接下来就把它集成到 Nest 框架中吧
# 安装必要的模块
| $ npm install -S nestjs-redis-plus ioredis | 
# 集成 Redis 配置
就像之前集成 Typeorm 一样,需要把 Redis 的配置单独做个 env 配置,用来区分各个环境
在 config 下新建 redis.ts 文件
| //redis.ts | |
| export default { | |
| host: process.env.REDIS_HOST, | |
| password: process.env.REDIS_PASSWORD?process.env.REDIS_PASSWORD:null, | |
| port: process.env.REDIS_PORT?parseInt(process.env.REDIS_PORT):6379, | |
| db: process.env.REDIS_DB?parseInt(process.env.REDIS_DB):0, | |
| }; | 
在 .env 和 .env.local 文件中分别加入 Redis 配置项
| #Redis配置 | |
| REDIS_HOST=127.0.0.1 | |
| REDIS_PASSWORD= | |
| REDIS_PORT=6379 | |
| REDIS_DB=0 | 
# 集成与测试 nestjs-redis-plus 模块
接下来集成 nestjs-redis-plus 模块,在 app.modeule.ts 中引入该模块,这里采用异步的模式
| //app.module.ts | |
| //imports | |
| RedisModule.forRootAsync({ | |
| useFactory: async (config: ConfigService) => config.get('redis'), | |
| inject: [ConfigService] | |
| }), | 
如果我们需要在 service 中使用的话,需要在 service 导入 ioredis , 并使用 @InjectRedisClient 装饰器
| //app.service.ts | |
| import {Injectable} from '@nestjs/common'; | |
| import {InjectRedisClient} from "nestjs-redis-plus"; | |
| import Ioredis from "ioredis" | |
| @Injectable() | |
| export class AppService { | |
| constructor( | |
| @InjectRedisClient() private readonly redisService: Ioredis | |
| ) {} | |
| async setRedisString(key:string,value:string,expire:number|null = null){ | |
| if(expire !== null){ | |
| return await this.redisService.setex(key,expire,value); | |
| }else{ | |
| return await this.redisService.set(key, value); | |
|         } | |
|     } | |
| async getRedisString(key:string){ | |
| return await this.redisService.get(key); | |
|     } | |
| } | 
在 app.controller.ts 中建立 2 个简单的接口来测试一下操作 Redis
| @Get('set_key/:key') | |
| async setString(@Param("key") key:string,@Query("v") value:string){ | |
| return await this.appService.setRedisString(key,value); | |
| } | |
| @Get('get_key/:key') | |
| async getString(@Param('key') key:string):Promise<string>{ | |
| let item = await this.appService.getRedisString(key); | |
| return item?item:`Not found`; | |
| } | 
使用浏览器测试一下,成功!
下一篇文章介绍如何将 Redis 和 socket.io 结合起来以实现多实例共享连接。
