【问题标题】:Java Spring: Compatibility for both transactional and non-transactional versions of mongodbJava Spring:mongodb 的事务和非事务版本的兼容性
【发布时间】:2019-09-11 19:40:52
【问题描述】:

我正在使用 Spring Boot 2.1.2 版本(mongodb-driver v 3.8.2)并开发与 mongodb 一起运行的 Web 应用程序。我的应用程序兼容 mongodb 3.4 版本(此版本不支持事务),现在我正在引入事务机制。我用事务注释来注释我的服务方法

@Transactional
    public void process(Object argument) {
        ...
        ...
        ...
    }

它适用于 mongodb v 4,一切正常 - 失败的事务被回滚。

但是当我使用 mongodb v 3.4 启动我的应用程序时,我的应用程序崩溃了

Sessions are not supported by the MongoDB cluster to which this client is connected

异常。

问题是我希望我的应用程序支持两种情况:使用相同代码的事务性和非事务性(对于两个 mongodb 版本)。所以我想知道我该怎么做?似乎我的应用程序应该只为特定版本的 mongo 创建会话,即这个注释应该只针对这种情况进行处理。

我该怎么做?

【问题讨论】:

    标签: java spring mongodb transactions spring-data


    【解决方案1】:

    不确定它是否有效,但您可以尝试将 @EnableTransactionManagement 注释移动到新的配置类,将注释 @Configuration@Profile("enableTransactions") 添加到配置类,然后使用给定的配置文件运行应用程序您需要自动配置事务管理,例如使用:

    mvn spring-boot:run -Dspring-boot.run.profiles=enableTransactions

    【讨论】:

    • 我找到了一个类似于profile的解决方案,把它写成了我的答案
    【解决方案2】:

    我找到了解决办法。 Spring 在创建事务之前检查当前上下文中是否存在PlatformTransactionManager。因此,如果未定义此 bean,则不会为事务打开会话。因此,我在配置类中为此目的使用了条件 bean:

        @Bean
        @Autowired
        @ConditionalOnExpression("'${mongo.transactions}'=='enabled'")
        MongoTransactionManager mongoTransactionManager(MongoDbFactory dbFactory) {
            return new MongoTransactionManager(dbFactory);
        }
    

    所以MongoTransactionManager bean 只有在 mongo.transactions 参数设置为启用时才会被创建。

    【讨论】:

      猜你喜欢
      • 2010-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多