[英]Java Spring: Compatibility for both transactional and non-transactional versions of mongodb
I'm using Spring Boot 2.1.2 release (mongodb-driver v 3.8.2) and developing web application that operates with mongodb. 我正在使用Spring Boot 2.1.2版本(mongodb-driver v 3.8.2),并开发可与mongodb一起运行的Web应用程序。 My application is compatible with mongodb 3.4 version (This version doesn't support transactions) and now I'm introducing transactional mechanism.
我的应用程序与mongodb 3.4版本兼容(此版本不支持事务),现在我要介绍事务机制。 I annotate my service method with transactional annotation
我用事务注释来注释我的服务方法
@Transactional
public void process(Object argument) {
...
...
...
}
and it works fine for mongodb v 4, everything works just excpected - failed transactions are rolledback. 并且在mongodb v 4上运行良好,一切都在预期之中-失败的事务将回滚。
But when I start my app with mongodb v 3.4 my app crashes with 但是,当我使用mongodb v 3.4启动我的应用程序时,我的应用程序崩溃了
Sessions are not supported by the MongoDB cluster to which this client is connected
exception. 例外。
The problem is that I want my app to support both cases: transactional and non-transactional with the same code (for both mongodb versions). 问题是我希望我的应用程序支持两种情况:具有相同代码的事务性和非事务性(对于两个mongodb版本)。 So I wonder how can I do it?
所以我想知道我该怎么做? It seems like my application should create session only for specific version of mongo, ie this annotation should be processed only for this case.
似乎我的应用程序应仅针对特定版本的mongo创建会话,即,仅应在这种情况下处理此批注。
How can I do it? 我该怎么做?
I have found a solution. 我找到了解决方案。 Spring checks for existence of
PlatformTransactionManager
in current context before creating a transaction. Spring在创建事务之前检查当前上下文中是否存在
PlatformTransactionManager
。 So if this bean is not defined, then session wouldn't be opened for transaction. 因此,如果未定义此bean,则不会打开会话进行事务处理。 Thus I had used on condition bean for this purpose in my configuration class:
因此,我在配置类中为此使用了条件豆:
@Bean
@Autowired
@ConditionalOnExpression("'${mongo.transactions}'=='enabled'")
MongoTransactionManager mongoTransactionManager(MongoDbFactory dbFactory) {
return new MongoTransactionManager(dbFactory);
}
So MongoTransactionManager
bean will be created only if mongo.transactions parameter is set to enabled. 因此,仅当mongo.transactions参数设置为enabled时,才会创建
MongoTransactionManager
bean。
不确定它是否有效,但是您可以尝试将@EnableTransactionManagement
批注移动到新的配置类,将批注@Configuration
和@Profile("enableTransactions")
到配置类,并在给定配置文件时运行应用程序需要自动配置事务管理,例如使用:
mvn spring-boot:run -Dspring-boot.run.profiles=enableTransactions
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.