LOOK:SpringBoot 配置 MongoDB 多数据源

public MongoDbFactory mongoDbFactory() throws Exception {

/*// 无认证的初始化方法

return new SimpleMongoDbFactory(new MongoClient(host, port), database);*/

//有认证的初始化方法

ServerAddress serverAddress = new ServerAddress(host, port);

List mongoCredentialList = new ArrayList<>();

MongoCredential mongoCredential = MongoCredential.createCredential(username, database, password.toCharArray());

mongoCredentialList.add(mongoCredential);

return new SimpleMongoDbFactory(new MongoClient(serverAddress, mongoCredentialList), database);

}

abstract public MongoTemplate getMongoTemplate() throws Exception;

}

数据源加载需要继承 AbstractMongoConfigure 抽象类,有多少个数据源就需要新建多少个数据源加载类

3.1、第一个数据源

import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.Primary;

import org.springframework.data.mongodb.core.MongoTemplate;

import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@Configuration

@EnableMongoRepositories(basePackages = {“com.tcl.dc.autodata.dao.base”}, mongoTemplateRef = “mongoTemplate”)

@ConfigurationProperties(prefix = “basic.spring.data.mongodb”)

public class BasicMongoConfig extends AbstractMongoConfigure {

@Primary

@Bean(name = “mongoTemplate”)

@Override

public MongoTemplate getMongoTemplate() throws Exception {

return new MongoTemplate(mongoDbFactory());

}

}

其中 basePackages 的值用于相应的基础包,prefix 为 application.properties 中的配置值

3.2、第二个数据源

import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.data.mongodb.core.MongoTemplate;

import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@Configuration

@EnableMongoRepositories(basePackages = {“com.tcl.dc.autodata.dao.auth”}, mongoTemplateRef = “authMongoTemplate”)

@ConfigurationProperties(prefix = “auth.spring.data.mongodb”)

public class BasicMongoConfig extends AbstractMongoConfigure {

@Bean(name = “authMongoTemplate”)

@Override

public MongoTemplate getMongoTemplate() throws Exception {

return new MongoTemplate(mongoDbFactory());

}

}

4、注意

1、多个数据源中有一个 bean 需要设置为 mongoTemplate ,且必须添加 @Primary 注解,否则 WebMvcConfigurationSupport.class 等会报错找不到 mongoTemplate

2、Spring Boot 会自动注入 mongoTemplate ,与我们配置的多个数据源有冲突。为了防止默认注入,需要排除自动注入的类。在 Spring Boot 的启动类 Applocation.java 添加排除类注解

@SpringBootApplication(exclude = {

MongoAutoConfiguration.class,

MongoDataAutoConfiguration.class})

5、使用多个数据源

使用时,直接对应注入即可

@Autowired

@Qualifier(value = “mongoTemplate”)

MongoTemplate mongoTemplate;

@Autowired

@Qualifier(value = “authMongoTemplate”)

MongoTemplate authMongoTemplate;

6、可能遇到的问题

1、‘com.mongodb.MongoClient’ that could not be found

详细报错如下:


APPLICATION FAILED TO START


Description:

Parameter 0 of method mongoDbFactory in org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration required a bean of type ‘com.mongodb.MongoClient’ that could not be found.

  • Bean method ‘mongo’ not loaded because auto-configuration ‘MongoAutoConfiguration’ was excluded

Action:

Consider revisiting the conditions above or defining a bean of type ‘com.mongodb.MongoClient’ in your configuration.

原因:重写了 MongoClient 等之后导致原来的自动注入缺少 bean

解决方式:主要是看哪个自动注入的类在引用默认的 MongoClient ,把它排除出去即可,例如:

@SpringBootApplication(exclude = {

MongoAutoConfiguration.class,

MongoDataAutoConfiguration.class})

2、more than one ‘primary’ bean found among candidates

详细报错如下:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘sampleController’: Unsatisfied dependency expressed through field ‘mongoTemplate’; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type ‘org.springframework.data.mongodb.core.MongoTemplate’ available: more than one ‘primary’ bean found among candidates: [logMongoTemplate, userMongoTemplate, mongoTemplate]

at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]

at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]

at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]

at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]

at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]

at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]

at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]

at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]

at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]

at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]

at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]

at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]

at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]

at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]

at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]

at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]

at com.biologic.Applocation.main(Applocation.java:18) [classes/:na]

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type ‘org.springframework.data.mongodb.core.MongoTemplate’ available: more than one ‘primary’ bean found among candidates: [logMongoTemplate, userMongoTemplate, mongoTemplate]

at org.springframework.beans.factory.support.DefaultListableBeanFactory.determinePrimaryCandidate(DefaultListableBeanFactory.java:1365) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]

at org.springframework.beans.factory.support.DefaultListableBeanFactory.determineAutowireCandidate(DefaultListableBeanFactory.java:1326) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]

at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1113) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]

Spring Boot配置MongoDB动态数据源可以使用Spring Data MongoDBSpring Boot多数据源功能。下面是一个基本的示例: 首先,确保在pom.xml文件中添加以下依赖: ```xml <!-- Spring Data MongoDB --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <!-- Spring Boot JDBC --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> ``` 接下来,创建一个MongoDB配置类,例如`MongoDBConfig`: ```java @Configuration public class MongoDBConfig { @Bean @ConfigurationProperties("spring.data.mongodb.primary") public MongoProperties primaryMongoProperties() { return new MongoProperties(); } @Bean @Primary public MongoClient primaryMongoClient() { MongoProperties mongoProperties = primaryMongoProperties(); return MongoClients.create(mongoProperties.getUri()); } @Bean @ConfigurationProperties("spring.data.mongodb.secondary") public MongoProperties secondaryMongoProperties() { return new MongoProperties(); } @Bean public MongoClient secondaryMongoClient() { MongoProperties mongoProperties = secondaryMongoProperties(); return MongoClients.create(mongoProperties.getUri()); } @Primary @Bean(name = "primaryMongoTemplate") public MongoTemplate primaryMongoTemplate() { return new MongoTemplate(primaryMongoClient(), primaryMongoProperties().getDatabase()); } @Bean(name = "secondaryMongoTemplate") public MongoTemplate secondaryMongoTemplate() { return new MongoTemplate(secondaryMongoClient(), secondaryMongoProperties().getDatabase()); } } ``` 在上述配置类中,我们使用`@ConfigurationProperties`来读取配置文件中的MongoDB连接属性。其中`spring.data.mongodb.primary`和`spring.data.mongodb.secondary`分别是主数据源和次数据源的配置属性。 接下来,在application.properties或application.yml文件中配置MongoDB连接属性: ```properties # Primary MongoDB spring.data.mongodb.primary.uri=mongodb://localhost:27017/primary_db spring.data.mongodb.primary.database=primary_db # Secondary MongoDB spring.data.mongodb.secondary.uri=mongodb://localhost:27017/secondary_db spring.data.mongodb.secondary.database=secondary_db ``` 最后,在需要使用数据源的地方,使用`@Qualifier`注解指定要使用的数据源: ```java @Service public class MyService { @Autowired @Qualifier("primaryMongoTemplate") private MongoTemplate primaryMongoTemplate; @Autowired @Qualifier("secondaryMongoTemplate") private MongoTemplate secondaryMongoTemplate; // 使用primaryMongoTemplate或secondaryMongoTemplate进行操作 } ``` 这样,就可以根据需要在不同的地方使用不同的MongoDB数据源了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值