nest-modules / ioredis

:see_no_evil: :hear_no_evil: :speak_no_evil: A ioredis module for Nest framework (node.js)
MIT License
144 stars 30 forks source link

在nestjs项目中使用该组件时被阻塞 #291

Open wenjian337 opened 1 day ago

wenjian337 commented 1 day ago

I found that I cannot add elements to a list using lpush when using this component in the Nestjs project. 我在nestjs项目中使用该组件时发现无法使用 lpush向列表中添加元素。 I implemented a message queue using a list in Nestjs 我在nestjs中使用list实现了一个消息队列

import { RedisModule } from '@nestjs-modules/ioredis';
//Redis,用于消息队列
    RedisModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        type: 'single',
        // url: 'redis://' + configService.get('REDIS_HOST', 'localhost') + ':' + configService.get('REDIS_PORT', 6379),
        // options: { password: configService.get('REDIS_PWD', ''), db: configService.get('REDIS_DB', 0) }
        url: 'redis://localhost:6379',
        options: { password: "", db: 14 }
      }),
    }),

项目启动时:

async onApplicationBootstrap() {
    this.logger.log("应用生命周期钩子 onApplicationBootstrap");
    this.cacheRefreshHandler();
}

async cacheRefreshHandler() {
    while (true) {
        let res = null
        try {
            res = await this.redis.brpop('bff_msg_queue', 0)
            this.logger.log('>>>>>>>>收到消息:', JSON.stringify(res))
            //消息处理任务
            if (res !== null && res[1]) {
               //.code
            }
        } catch (err) {
            console.log('brpop 出错,重新brpop', err)
            continue
        }
    }
}

Finally used in the project's service 最后在项目的service中使用

import Redis from 'ioredis';
import { InjectRedis } from '@nestjs-modules/ioredis';

@Resolver('Article')
export class ArticleResolver {
  private logger = new Logger(ArticleResolver.name);
  constructor(
    @InjectRedis() private readonly redis: Redis,
  ) { }

async method(tid){
// The execution of the following line of code is blocked and cannot return
await this.redis.lpush("bff_msg_queue", JSON.stringify({ "event": "update_article_info", "tid": tid }));
}
}

When I call the method() method, the execution keeps waiting for lpush to complete, and the program does not continue to execute. 当我调用 method() 方法的时候,执行一直在等待lpush执行完成,程序不在往下执行。

jleverenz commented 1 day ago

Just a quick hunch, but could it be because brpop is blocking, and then the same client cannot do the lpush? Also, cacheRefreshHandler (and the blocking) is not awaited in onApplicationBootstrap.