MikroORM 与 BullMQ 等后台工作者一起使用时是否需要 RequestContext?

Does MikroORM require a RequestContext when used with background workers like BullMQ?

我将 MikroORM 与 BullMQ workers. When MikroORM is used with Express apps, it requires a RequestContext 结合使用,以便为每个请求维护唯一的身份映射。我怀疑在使用同一个 BullMQ worker 处理多个作业时需要同样的东西。

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

对于这种情况,您可以使用 @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
});