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在多数据源下的事务的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程