首页 > 解决方案 > 使用rabbitmq队列处理微服务之间的实时数据同步

问题描述

我们已经将我们的微服务设置为使用rabbitmq队列来处理任何即将到来的数据。

所以,我们有service Aservice B和。service Cservice D

当请求创建一个用户时service A,它会创建一个用户并将一个事件推送到newUserIsCreated队列中。

现在,service B需要service C为新添加的用户更新他们的数据库。


问题

如果用户创建在任何service Band中失败怎么办service C

可能的失败情况可能是验证失败,或者service B关闭service C

如果service D尝试访问同一用户,也会出现问题。

service B会有什么service C反应?因为到那时他们将没有新创建的用户。


总结一下,

如何处理这些服务之间的验证失败或任何类型的失败?

如果需要实时同步怎么办?(队列可能需要一些时间来处理)

标签: architecturerabbitmqmicroservicesdevopseventual-consistency

解决方案


您可以拥有B并且C(以及任何其他需要确认用户已创建的服务)向 RabbitMQ 发布确认消息以供A; A然后在收到确认之前不确认用户已创建。这不是万无一失的:它很有可能在所有地方都取得了成功,但A没有及时得到确认。对于那种(理想情况下很少见)的情况,您可以有一个清理过程。

It's worth noticing though, that this sort of synchronous relation is basically reimplementing request/response via a message queue, so if going down this path, why not just do direct request/response (e.g. HTTP or gRPC)?

If you have an operation which needs to affect multiple services, it's often useful to model it as a saga, which will make requests to the various services and handle failures (and potentially give up if there have been too many failures, rolling back the changes it's made). By persisting the state of the saga (e.g. updated B, but C has not yet acknowledged the update), it can be queried.

如果您发现大多数操作B都是 sagas touch 的一部分A,那么可能值得考虑是否B并且A应该是相同的服务,这将提供更强的一致性保证并可能简化事情。


推荐阅读