Mongoose事务和事务后操作。

huangapple go评论66阅读模式
英文:

Mongoose Transactions and Post Transactional Operations

问题

我正在使用 mongoosesessions 在我们的 nodejs + express 后端执行 ACID 事务。

最近,我需要向我们的一个由 RabbitMQ 支持的工作程序发送消息,以执行事务后的操作。我不能在提交后直接发送消息给我们的工作程序,因为背后有一个复杂的工作流程,并且完成事务并不总是意味着必须调用代码。

我相信我需要使用事件发射器来注册 .once('onCommit', ...) 事件,并在事务完成时调用 emit('onCommit')。但这是手动的方法。

我想知道是否有 mongoose 提供的内置支持,以使用 mongoose.ClientSession 进行事务后操作。我看到 mongoose 会话本身是事件监听器,但我找不到相关的文档。我猜会话事件是供内部使用的。

有人可以给我一些启发吗?

谢谢。

英文:

I am using mongoose together with sessions to perform ACID transactions in our nodejs + express backend.

lately, I have a necessity to send a message to one of our workers (backed by RabbitMQ) to make post transactional operation. I cannot directly send the message to our worker after the commit because there is a complex workflow behind it and completing the transaction does not always mean that the code must be called.

I believe that I need to use event emitters to register .once('onCommit', ...) event, and call emit('onCommit') when the transaction is done. But this is manual approach.

I would like to know if there is out of the box support in mongoose to make post transactional operations using mongoose.ClientSession. I am seeing that mongoose sessions are by itself Event Listeners but I couldn't find any related docuementation. I guess session events are for internal use.

can anyone enlighten me?

thank you

答案1

得分: 1

你应该能够使用ended事件。所以下面的代码应该能够正常工作,如果你使用session.endSession();来完成事务操作:

session.on('ended', () => '事务操作完成');

此外,如果你需要获取关于事务提交或中止的信息,你可以获取会话后的数据并像下面这样检查事务状态:

session.on('ended', (postSession) => {
    const state = postSession.transaction.state;

    if (state === 'TRANSACTION_COMMITTED') {
        '成功的事务操作';
    }

    if (state === 'TRANSACTION_ABORTED') {
        '中止的事务操作';
    }
});
英文:

You should be able to use ended event. So below code should work if you finalize the transaction operation with session.endSession();

session.on('ended', () => 'post transaction operation');

Additionally if you need an information about transaction committed or aborted. You can get the post session data and check transaction state like below:

session.on('ended', (postSession) => {
    const state = postSession.transaction.state;

    if (state === 'TRANSACTION_COMMITTED') {
      'successful transaction operation';
    }

    if (state === 'TRANSACTION_ABORTED') {
      'aborted transaction operation';
    }
 });

huangapple
  • 本文由 发表于 2023年1月6日 18:38:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75029843.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定