【问题标题】:Does MikroORM require a RequestContext when used with background workers like BullMQ?与 BullMQ 等后台工作人员一起使用时,MikroORM 是否需要 RequestContext?
【发布时间】:2024-04-26 09:50:01
【问题描述】:

我正在将 MikroORM 与 BullMQ 工人一起使用。当 MikroORM 与 Express 应用程序一起使用时,它需要 RequestContext 以维护每个请求的唯一身份映射。我怀疑在使用同一个 BullMQ 工作人员处理多个作业时也需要这样做。

有没有其他人成功地结合了这两个库?是否可以在工作人员开始新工作时自动分叉实体管理器?

【问题讨论】:

    标签: mikro-orm bullmq


    【解决方案1】:

    对于这种情况,您可以使用 @UseRequestContext() 装饰器。它基本上就像在添加上下文的中间件之后执行该方法一样。请注意,要使用它,this.orm 需要是 MikroORM 实例。

    @Injectable()
    export class MyService {
    
      constructor(private readonly orm: MikroORM) { }
    
      @UseRequestContext()
      async doSomething() {
        // this will be executed in a separate context
      }
    
    }
    

    https://mikro-orm.io/docs/usage-with-nestjs/#request-scoped-handlers-in-queues

    (这部分文档是关于nestjs的,但同样的问题,同样的解决方案)

    您也可以明确使用RequestContext.createAsync()

    await RequestContext.createAsync(orm.em, async () => {
      // orm.em here will use the contextual fork created just for this handler
    });
    

    【讨论】: