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

相关推荐
Ciderw1 分钟前
MySQL为什么使用B+树?B+树和B树的区别
c++·后端·b树·mysql·面试·golang·b+树
计算机-秋大田4 分钟前
基于微信小程序的汽车保养系统设计与实现(LW+源码+讲解)
spring boot·后端·微信小程序·小程序·课程设计
齐雅彤8 分钟前
Bash语言的并发编程
开发语言·后端·golang
峰子201223 分钟前
B站评论系统的多级存储架构
开发语言·数据库·分布式·后端·golang·tidb
秋淮安1 小时前
后端开发Web
后端·web
milk_yan2 小时前
MinIO的安装与使用
linux·数据仓库·spring boot
浏览器爱好者2 小时前
如何使用MongoDB进行数据存储?
数据库·mongodb
yuanpan2 小时前
MongoDB中的横向扩容数据分片
数据库·mongodb
草明2 小时前
Mongodb 慢查询日志分析 - 1
数据库·python·mongodb
yuanpan2 小时前
MongoDB的事务机制
数据库·mongodb