springboot-mongodb 多数据源

本文介绍如何在Spring Boot项目中配置并使用两个MongoDB数据源,包括配置类的编写、控制器中注入不同MongoDB实例的方法及配置文件示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. AbstractMongoConfig.java 

public abstract class AbstractMongoConfig {
	// Mongo DB Properties
	private String host, database, username, password;
	private int port;
	// Setter methods go here.
;

/*
	 * Method that creates MongoDbFactory Common to both of the MongoDb
	 * connections
	 */
	public MongoDbFactory mongoDbFactory() throws Exception {
		ServerAddress serverAddress = new ServerAddress(host, port);
		List<MongoCredential> mongoCredentialList = new ArrayList<>();
		mongoCredentialList.add(MongoCredential.createCredential(username, database, password.toCharArray()));
		return new SimpleMongoDbFactory(new MongoClient(serverAddress, mongoCredentialList), database);
	}

	/*
	 * Factory method to create the MongoTemplate
	 */
	abstract public MongoTemplate getMongoTemplate() throws Exception;
}

或者

public abstract class AbstractMongoConfig {
	
private String url;
/*
	 * Method that creates MongoDbFactory Common to both of the MongoDb
	 * connections
	 */
	public MongoDbFactory mongoDbFactory() throws Exception {
		
		return new SimpleMongoDbFactory(new MongoClientURI(url);
	}

	/*
	 * Factory method to create the MongoTemplate
	 */
	abstract public MongoTemplate getMongoTemplate() throws Exception;
}

2. first mongodb 配置

@Configuration  //Configuration class
@ConfigurationProperties(prefix = "spring.data.mongodb.primary") //Defines my custom prefix and points to the primary db properties
public class PrimaryMongoConfig extends AbstractMongoConfig {     
   
     @Primary    
     @Override    
     @Bean(name = "primaryMongoTemplate")
     public  MongoTemplate getMongoTemplate() throws Exception {        
         return new MongoTemplate(mongoDbFactory());    
     }
}

second mongo配置

@Configuration  //Configuration 
@ConfigurationProperties(prefix = "spring.data.mongodb.secondary")  //Defines my custom prefix and points to the secondary db properties
public class SecondaryMongoConfig extends  AbstractMongoConfig{     
   
    @Override public @Bean(name = "secondaryMongoTemplate") 
    MongoTemplate getMongoTemplate() throws Exception {        
        return new MongoTemplate(mongoDbFactory());    
    }
}

3. Controller 中使用

@Autowired
	@Qualifier(value = "primaryMongoTemplate")
	protected MongoTemplate primaryMongoTemplate;

	// Using mongoTemplate for secondary database
	@Autowired
	@Qualifier(value = "secondaryMongoTemplate")
	protected MongoTemplate secondaryMongoTemplate;

4. Application 中注意

@SpringBootApplication(exclude = MongoAutoConfiguration.class,MongoDataAutoConfiguration.class)

如果不添加,就会报错:

com.mongodb.MongoSocketOpenException: Exception opening socket

 

5. 配置文件:

 

spring.data.mongodb.secondary.url=标准的写法就可以

或者

spring.data.mongodb.secondary.username=  

分开写,匹配步骤1中的两种方式

 

springboot的mongodb的连接池:

Spring Boot中通过依赖spring-boot-starter-data-mongodb,来实现spring-data-mongodb的自动配置。 
但是默认情况下,Spring Boot 中,并没有像使用MySQL或者Redis一样,提供了连接池配置的功能。因此,我们需要自行重写 MongoDbFactory,实现MongoDB客户端连接的参数配置扩展。

需要说明的是,MongoDB的客户端本身就是一个连接池,因此,我们只需要配置客户端即可。

为了统一Spring Boot的配置,我们要将重写的配置也配置到 application.yml中,前缀为spring.data.mongodb.custom下(前缀可自己随意配置):

spring:
    data:
       mongodb:
              xxx1:
                  uri: mongodb://ip:port,ip:port/database1
              xxx2:
                  uri: mongodb://ip:port,ip:port/database2
       minConnectionsPerHost: 20
       connectionsPerHost: 20

connections-per-host为客户端的连接数,in-connections-per-host为客户端最小连接数。
 

MongoClientOptions.Builder builder = new MongoClientOptions.Builder(); 

builder.connectionsPerHost(ConnectionsPerHost); 

builder.minConnectionsPerHost(MinConnectionsPerHost);

new SimpleMongoDbFactory(new MongoClientURI(DB_DAAS_URI,builder));

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值