MongoDb在多数据源下的事务
2021/8/6 2:07:36
本文主要是介绍MongoDb在多数据源下的事务,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
MongoDb在多数据源下的事务
创建并注入mongoDatabaseFactory,mongoTemplate,mongoTransactionManager
import com.mongodb.ConnectionString; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.MongoDatabaseFactory; import org.springframework.data.mongodb.MongoTransactionManager; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory; /* * mongodb配置 * */ @Configuration public class SecondDataSourceConfig { @Value("${mongodb.secondary.url}") private String url; @Value("${mongodb.secondary.database}") private String database; @Bean MongoDatabaseFactory mongoDatabaseFactory() { ConnectionString connectionString = new ConnectionString(url); return new SimpleMongoClientDatabaseFactory(connectionString); } @Bean public MongoTemplate mongoTemplate(MongoDatabaseFactory factory) { // ConnectionString connectionString = new ConnectionString(url); // MongoClientSettings setting = MongoClientSettings.builder() // .applyConnectionString(connectionString) // .build(); // MongoClient mongo = MongoClients.create(setting); return new MongoTemplate(factory); } @Bean("MONGO_TRANSACTION_MANAGER") MongoTransactionManager mongoTransactionManager(MongoDatabaseFactory factory) { return new MongoTransactionManager(factory); } }
在用到的地方添加注解 @Transactional(rollbackFor = Exception.class,transactionManager = “MONGO_TRANSACTION_MANAGER”)
@Transactional(rollbackFor = Exception.class,transactionManager = "MONGO_TRANSACTION_MANAGER") public void syncByUserId(String userId) throws AppException { a.insert(); b.insert(); }
这篇关于MongoDb在多数据源下的事务的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-12Cargo deny安装指路
- 2024-11-02MongoDB项目实战:从入门到初级应用
- 2024-11-01随时随地一键转录,Google Cloud 新模型 Chirp 2 让语音识别更上一层楼
- 2024-10-25Google Cloud动手实验详解:如何在Cloud Run上开发无服务器应用
- 2024-10-24AI ?先驱齐聚 BAAI 2024,发布大规模语言、多模态、具身、生物计算以及 FlagOpen 2.0 等 AI 模型创新成果。
- 2024-10-20goland工具下,如修改一个项目的标准库SDK的版本-icode9专业技术文章分享
- 2024-10-17Go学习:初学者的简单教程
- 2024-10-17Go学习:新手入门完全指南
- 2024-10-17Golang学习:初学者入门教程
- 2024-10-17Golang学习:新手入门教程