gpt4 book ai didi

c# - ServiceBus 是否尊重事务范围?

转载 作者:行者123 更新时间:2023-12-03 06:52:45 25 4
gpt4 key购买 nike

在代码中我需要原子地:

//write to a database table
//publish EventA to service bus
//write to another database table
//publish EventB to service bus

如果任一数据库写入失败,我可以轻松地在事务范围内回滚所有内容。但是,如果发生这种情况,则事件永远不会发布到服务总线,这一点很重要。

理想情况下,我需要服务总线库“等到事务范围成功完成”,然后再将消息发布到总线上。

我正在使用遗留的.net框架代码 - 我可以轻松地编写一些东西来保存要在内存中引发的事件,并且只有在范围完成后才引发这些事件。即使如此,问题是如果 EventB 发布失败,EventA 已经发布了。

将服务总线事件包含在事务范围内的最简单方法是什么?

最佳答案

我认为没有简单的方法可以解决这个问题。 Azure 服务总线不会与任何其他服务共享事务。正如数据库事务不能包含 Web 服务调用一样。与本地(在一定程度上)可能的简单 DTC 事务相比,实现这一点的方法总是需要一些额外的复杂性。

但是这是可以做到的。 this 中很好地描述了发件箱(工作单元)和收件箱(幂等性)等模式。发布

Outbox Pattern - This pattern ensures that a message was sent (e.g. to a queue) successfully at least once. With this pattern, instead of directly publishing a message to the queue, we store it in the temporary storage (e.g. database table). We’re wrapping the entity save and message storing with the Unit of Work (transaction). By that, we’re making sure that if the application data was stored, the message wouldn’t be lost. It will be published later by a background process. This process will check if there are any not sent events in the table. When the worker finds such messages, it tries to send them. After it gets confirmation of publishing (e.g. ACK from the queue) it marks the event as sent.

Inbox Pattern - This is a pattern similar to Outbox Pattern. It’s used to handle incoming messages (e.g. from a queue). Accordingly, we have a table in which we’re storing incoming events. Contrary to outbox pattern, we first save the event in the database, then we’re returning ACK to queue. If save succeeded, but we didn’t return ACK to queue, then delivery will be retried. That’s why we have at-least-once delivery again. After that, an outbox-like process runs. It calls message handlers that perform business logic.

回答您的具体问题。

What's the easiest way to include service bus events within a transaction scope?

最简单的方法是使用一个已经执行此操作、经过彻底测试并且可以集成到您的系统中的库。 MassTransit , NServiceBus , Jasper等等。或者,构建您自己的。我不建议,除非它是一个宠物项目或您系统的核心。

关于c# - ServiceBus 是否尊重事务范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73406399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com