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")

相关推荐
向前看-2 小时前
验证码机制
前端·后端
你的微笑,乱了夏天3 小时前
linux centos 7 安装 mongodb7
数据库·mongodb
黄油饼卷咖喱鸡就味增汤拌孜然羊肉炒饭3 小时前
SpringBoot如何实现缓存预热?
java·spring boot·spring·缓存·程序员
超爱吃士力架4 小时前
邀请逻辑
java·linux·后端
AskHarries5 小时前
Spring Cloud OpenFeign快速入门demo
spring boot·后端
isolusion6 小时前
Springboot的创建方式
java·spring boot·后端
Yvemil77 小时前
《开启微服务之旅:Spring Boot Web开发举例》(一)
前端·spring boot·微服务
zjw_rp7 小时前
Spring-AOP
java·后端·spring·spring-aop
TodoCoder7 小时前
【编程思想】CopyOnWrite是如何解决高并发场景中的读写瓶颈?
java·后端·面试
凌虚8 小时前
Kubernetes APF(API 优先级和公平调度)简介
后端·程序员·kubernetes