【问题标题】:Spring transaction with restful application带有宁静应用程序的 Spring 事务
【发布时间】:2016-06-01 04:05:57
【问题描述】:

我正在开发 Spring Boot,我需要澄清有关 transaction 管理的一些事情。

例如,我确实有 2 个类运行两个单独的作业(第一个作业是在数据库上创建配置文件,第二个作业是调用 restful 应用程序也创建配置文件,但在不同的系统上)。

这 2 个工作必须是事务性的。两者都需要成功。如果其中一项作业失败,则不应在任何数据存储上创建任何配置文件)

因为我是这个春天的新手。我希望得到建议,并且需要知道这种情况下的最佳做法是什么。

【问题讨论】:

    标签: java spring spring-mvc spring-boot spring-data


    【解决方案1】:

    有一个facade pattern。我建议做一个facade service 来加入两个服务的逻辑。服务必须是独立的,因为使用配置文件和与其他系统通信是业务逻辑的不同部分。

    例如,有ProfileServiceOuterService 用于处理配置文件和进行外部通信。您可以写SomeFacadeService 来加入两个方法并将其包装在一个事务中。 @Transactional 的默认传播是 REQUIRED。因此事务将在方法SomeFacadeService.doComplexJob 上创建,方法profileService.createProfileouterService.doOuterJob 将加入当前事务。如果其中一个发生异常,整个SomeFacadeService.doComplexJob 将被回滚。

    @Controller
    public class SomeController {
    @Autowired
                SomeFacadeService someFacadeService ;
    
        @RequestMapping("/someMapping")
        public void doSomeJob() {
            someFacadeService.doComplexJob();
        }
    }
    
    @Service
            public class SomeFacadeService {
                @Autowired
                ProfileService profileService;
                @Autowired
                OuterService outerService;
    
                @Transactional
                public void doComplexJob() {
                    profileService.createProfile();
                    outerService.doOuterJob();
                }
            }
    
            @Service 
            public class ProfileService {
                @Transactional
                public void createProfile() {
                    // create profile logic
                }
            }
    

    【讨论】:

    • 感谢@doge,现在测试这种方法并将分享更新!
    • 对不起@doge,我需要快速澄清一下。在outerService.doOuterJob()上,是否应该返回Boolean来表示处理的结果?
    • 不,如果您因为其他原因不需要结果。只要抛出一个异常就足够了。
    猜你喜欢
    • 2015-07-19
    • 2016-12-17
    • 2018-12-30
    • 2011-12-10
    • 1970-01-01
    • 2019-03-17
    • 2018-04-21
    • 2010-12-26
    • 1970-01-01
    相关资源
    最近更新 更多