当前位置: 首页 > article >正文

springboot配置两个MongoDB

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

添加依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

配置application.yml或application.properties

spring:  
  data:  
    mongodb:  
      primary:  
        uri: mongodb://user:password@localhost:27017/primarydb  
      secondary:  
        uri: mongodb://user:password@localhost:27018/secondarydb

java配置

启动类排除MongoDB自动配置

@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
public class Application {

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

}

primary配置类

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配置类
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

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

  

}
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);

  

}

测试类

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


http://www.kler.cn/a/286824.html

相关文章:

  • ceph基本概念,架构,部署(一)
  • 学到一些小知识关于Maven 与 logback 与 jpa 日志
  • SQLLOADER小实验
  • 澎峰科技计算软件栈与沐曦GPU完成适配和互认证
  • 代码随想录day1
  • 【2024年华为OD机试】(C/D卷,200分)- 5G网络建设 (JavaScriptJava PythonC/C++)
  • 手搓 Java hashmap
  • vscode解决运行程序无法从控制台输入问题
  • Unity(2022.3.41LTS) - 视频
  • 深度解读并发安全集合的原理及源码
  • net_device数据结构简单总结
  • Day 1 : 数据结构
  • nginx配置ssl证书
  • JSON处理库 -- Fastjson
  • 堆《数据结构》
  • 【Unity小工具】Image组件宽度、高度自适应
  • 【大数据算法】时间亚线性算法之:串相等判定算法。
  • Python 全栈系列266 Kafka服务的Docker搭建
  • ctfshow之web58~web71
  • Android --- transaction.commitAllowingStateLoss();和transcation.commit 有什么区别
  • J.U.C Review - volatile / synchronized / 锁 深入剖析
  • Java网络编程概述
  • 【maven】阿里云和apache仓库配置
  • Java 流过滤器是否足够智能,可以忽略有序流中不必要的项目吗?
  • 云计算实训40——部署project_exam_system项目及容器的编排
  • c++ 原型模式