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,org,ConnectionString,factory,springframework,数据源,import,MongoDb 来源: https://blog.csdn.net/growing1224/article/details/119425690