如何确保 spring 引导中方法执行的原子性?
How to ensure atomicity of a method execution in spring boot?
我有一个方法也调用了一些其他方法。这些操作与数据库没有任何关系。我只是在执行一些逻辑,很少 API 调用其他一些外部服务等等。如果在任何操作中发生任何异常,我希望所有操作都必须回滚。我怎样才能做到这一点?
这听起来像是一个无辜的问题,但实际上非常棘手。您要求的是 API 调用之间的分布式事务。为此,API 同行需要支持 "two-phased commit" 之类的东西。底线是:如果您的 API 提供商不支持分布式事务,您将不得不自己构建一些东西。 (Post一些代码,把方法描述的更详细一些,我们会帮忙的)
参见示例。更多详情:https://developers.redhat.com/blog/2018/10/01/patterns-for-distributed-transactions-within-a-microservices-architecture/,或 Google "distributed transaction service calls"
很抱歉,您必须手动处理。例如,如果发生异常,手动应用一个补偿动作来撤销。
一种叫做saga模式的模式就是为了解决这样的问题,我引用this的基本思想如下:
The Saga pattern describes how to solve distributed (business)
transactions without two-phase-commit as this does not scale in
distributed systems. The basic idea is to break the overall
transaction into multiple steps or activities. Only the steps
internally can be performed in atomic transactions but the overall
consistency is taken care of by the Saga. The Saga has the
responsibility to either get the overall business transaction
completed or to leave the system in a known termination state. So in
case of errors a business rollback procedure is applied which occurs
by calling compensation steps or activities in reverse order.
我有一个方法也调用了一些其他方法。这些操作与数据库没有任何关系。我只是在执行一些逻辑,很少 API 调用其他一些外部服务等等。如果在任何操作中发生任何异常,我希望所有操作都必须回滚。我怎样才能做到这一点?
这听起来像是一个无辜的问题,但实际上非常棘手。您要求的是 API 调用之间的分布式事务。为此,API 同行需要支持 "two-phased commit" 之类的东西。底线是:如果您的 API 提供商不支持分布式事务,您将不得不自己构建一些东西。 (Post一些代码,把方法描述的更详细一些,我们会帮忙的)
参见示例。更多详情:https://developers.redhat.com/blog/2018/10/01/patterns-for-distributed-transactions-within-a-microservices-architecture/,或 Google "distributed transaction service calls"
很抱歉,您必须手动处理。例如,如果发生异常,手动应用一个补偿动作来撤销。
一种叫做saga模式的模式就是为了解决这样的问题,我引用this的基本思想如下:
The Saga pattern describes how to solve distributed (business) transactions without two-phase-commit as this does not scale in distributed systems. The basic idea is to break the overall transaction into multiple steps or activities. Only the steps internally can be performed in atomic transactions but the overall consistency is taken care of by the Saga. The Saga has the responsibility to either get the overall business transaction completed or to leave the system in a known termination state. So in case of errors a business rollback procedure is applied which occurs by calling compensation steps or activities in reverse order.