Nest 使用 redis
创建项目:
bash1nest new redis-next-test -p pnpm
安装 redis 包
bash1pnpm install redis
appModule 中使用 useFactory 动态注入 redis Provider。
typescript1@Module({ 2 imports: [], 3 controllers: [AppController], 4 providers: [ 5 AppService, 6 { 7 provide: 'REDIS_Client', 8 useFactory: async () => { 9 const client = createClient({ 10 socket: { 11 host: 'localhost', 12 port: 6379, 13 }, 14 }); 15 await client.connect(); 16 return client; 17 }, 18 }, 19 ], 20})
注入到 service 并获取所有的 keys
typescript1import { Inject, Injectable } from '@nestjs/common' 2import { RedisClientType } from 'redis' 3 4@Injectable() 5export class AppService { 6 constructor(@Inject('REDIS_Client') private readonly redisClient: RedisClientType) {} 7 async getHello(): Promise<string> { 8 const allKeys = await this.redisClient.keys('*') 9 console.log('——————🚀🚀🚀🚀🚀 —— allKeys:', allKeys) 10 return 'Hello World!' 11 } 12}
