springboot配置两个MongoDB

由于项目需要访问不通的数据,需要配置两个MongoDB(也可以是多个)

添加依赖

XML 复制代码
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

配置application.yml或application.properties

XML 复制代码
spring:  
  data:  
    mongodb:  
      primary:  
        uri: mongodb://user:password@localhost:27017/primarydb  
      secondary:  
        uri: mongodb://user:password@localhost:27018/secondarydb

java配置

启动类排除MongoDB自动配置

java 复制代码
@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

primary配置类

java 复制代码
package XXX;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.mongo.MongoClientFactory;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

//此处建议用package。之前用class,会绑定错误的MongoTemplate
@Configuration
@EnableMongoRepositories(basePackages = "com.xxx.dao.primary", mongoTemplateRef = "primaryMongoTemplate")
public class PrimaryMongodbConfig {

    @Autowired
    private ObjectProvider<MongoClientOptions> options;
    @Autowired
    private Environment environment;

    @Bean(name = "primaryPropertiess")
    @ConfigurationProperties(prefix = "spring.data.mongodb.primary")
    @Primary
    public MongoProperties primaryPropertiess() {
        return new MongoProperties();
    }

    @Bean(name = "primaryMongoClient")
    public MongoClient mongoClient(@Qualifier("primaryPropertiess") MongoProperties mongoProperties) {
        MongoClientFactory factory = new MongoClientFactory(mongoProperties, environment);
        return factory.createMongoClient(options.getIfAvailable());
    }

    @Bean(name = "primaryMongoDBFactory")
    public SimpleMongoDbFactory mongoDbFactory(
            @Qualifier("primaryMongoClient") MongoClient mongoClient,
            @Qualifier("primaryPropertiess") MongoProperties mongoProperties) {
        String database = mongoProperties.getMongoClientDatabase();
        return new SimpleMongoDbFactory(mongoClient, database);
    }

    @Bean(name = "primaryMongoTemplate")
    public MongoTemplate mongoTemplate(@Qualifier("primaryMongoDBFactory") SimpleMongoDbFactory mongoDatabaseFactory) {
        return new MongoTemplate(mongoDatabaseFactory);
    }
}
复制代码
secondary配置类
java 复制代码
package com.xxx.mongo;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.mongo.MongoClientFactory;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;


@Configuration
@EnableMongoRepositories(basePackages = "com.xxx.dao.secondary", mongoTemplateRef = "secondaryMongoTemplate")
public class SecondMongodbConfig {

    @Autowired
    private ObjectProvider<MongoClientOptions> options;
    @Autowired
    private Environment environment;

    @Bean(name = "secondaryProperties")
    @ConfigurationProperties(prefix = "spring.data.mongodb.secondary")
    public MongoProperties secondaryProperties() {
        return new MongoProperties();
    }

    @Bean(name = "secondaryMongoClient")
    public MongoClient mongoClient(@Qualifier("secondaryProperties") MongoProperties mongoProperties) {
        MongoClientFactory factory = new MongoClientFactory(mongoProperties, environment);
        return factory.createMongoClient(options.getIfAvailable());
    }

    @Bean(name = "secondaryMongoDBFactory")
    public SimpleMongoDbFactory mongoDbFactory(
            @Qualifier("secondaryMongoClient") MongoClient mongoClient,
            @Qualifier("secondaryProperties") MongoProperties mongoProperties) {
        String database = mongoProperties.getMongoClientDatabase();
        return new SimpleMongoDbFactory(mongoClient, database);
    }

    @Bean(name = "secondaryMongoTemplate")
    public MongoTemplate mongoTemplate(@Qualifier("secondaryMongoDBFactory") SimpleMongoDbFactory mongoDatabaseFactory) {
        return new MongoTemplate(mongoDatabaseFactory);
    }
}

OrderInfoPrimaryDao

java 复制代码
package com.xxx.dao.primary;

import com.xxx.mongo.OrderInfoBase;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface OrderInfoPrimaryDao extends MongoRepository<OrderInfoPrimary, Long> {

    /**
     *
     * @param orderId
     * @return
     */
    List<OrderInfoPrimary> findByOrderId(Long orderId);

  

}
java 复制代码
package com.xxx.dao.secondary;

import com.xxx.mongo.OrderInfoBase;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface OrderInfoSecondaryDao extends MongoRepository<OrderInfoSecondary, Long> {

    /**
     *
     * @param orderId
     * @return
     */
    List<OrderInfoSecondary> findByOrderId(Long orderId);

  

}

测试类

java 复制代码
    @Autowired
    OrderInfoPrimaryDao orderInfoPrimaryDao;

    @Autowired
    OrderInfoSecondaryDao orderInfoSecondaryDao;

public BaseResponse test() {
       

            List<OrderInfoPrimary> byOrderId1 = orderInfoPrimaryDao.findByOrderId(7407731806818009176L);
            List<OrderInfoSecondary> byOrderId2 = orderInfoSecondaryDao.findByOrderId(7407731806818009176L);
    }

总结

本来是按basePackageClasses的方式实现的,结果两个MongoDB只有一个生效,怀疑是dao在一个包里面的原因,改成放在不同的包里面就正常了。

复制代码
错误代码:@EnableMongoRepositories(basePackageClasses = orderInfoPrimaryDao.class, mongoTemplateRef = "primaryMongoTemplate")

有效代码:@EnableMongoRepositories(basePackages = "com.xxx.dao.secondary", mongoTemplateRef = "secondaryMongoTemplate")

相关推荐
Asthenia04127 小时前
Spring AOP 和 Aware:在Bean实例化后-调用BeanPostProcessor开始工作!在初始化方法执行之前!
后端
Asthenia04128 小时前
什么是消除直接左递归 - 编译原理解析
后端
Asthenia04128 小时前
什么是自上而下分析 - 编译原理剖析
后端
Asthenia04129 小时前
什么是语法分析 - 编译原理基础
后端
Asthenia04129 小时前
理解词法分析与LEX:编译器的守门人
后端
uhakadotcom9 小时前
视频直播与视频点播:基础知识与应用场景
后端·面试·架构
Asthenia041210 小时前
Spring扩展点与工具类获取容器Bean-基于ApplicationContextAware实现非IOC容器中调用IOC的Bean
后端
bobz96510 小时前
ovs patch port 对比 veth pair
后端
Asthenia041210 小时前
Java受检异常与非受检异常分析
后端