前言:
Spring Boot支持应用程序中创建多个Mongo模板连接到两个不同的mongo服务器。
创建多个Mongo连接
application.properties/yml
properties:
primary.mongodb.host=<primary_mongodb_host>
primary.mongodb.port=<primary_mongodb_port>
primary.mongodb.database=<primary_mongodb_database>
secondary.mongodb.host=<secondary_mongodb_host>
secondary.mongodb.port=<secondary_mongodb_port>
secondary.mongodb.database=<secondary_mongodb_database>
yml:
primary:
mongodb:
host:<primary_mongodb_host>
port:<primary_mongodb_port>
database:<primary_mongodb_database>
secondary:
mongodb:
host:<secondary_mongodb_host>
port:<primary_mongodb_port>
database:<secondary_mongodb_database>
复制代码
创建配置类:
public abstract class AbstractMongoConfig {
//mongodb配置属性
private String host, database;
private int port;
//Setter methods go here..
/*
* 创建MongoDBFactory的方法
* 两个MongoDB连接共用
*/
public MongoDbFactory mongoDbFactory() throws Exception {
return new SimpleMongoDbFactory(new MongoClient(host, port), database);
}
/*
* Factory method to create the MongoTemplate
*/
abstract public MongoTemplate getMongoTemplate() throws Exception;
}复制代码
连接配置:
//Master-MongoTemplate
@Configuration
@ConfigurationProperties(prefix = "primary.mongodb") //前缀指向
public class CommonMongoConfig extends AbstractMongoConfig {
/**
* MongoTemplate实现
* @Bean为创建的mongotemplate实例提供一个名称(primarymongotemplate)
* @Primary 设为默认
*/
@Primary
@Override
public @Bean(name = "primaryMongoTemplate") MongoTemplate getMongoTemplate() throws Exception {
return new MongoTemplate(mongoDbFactory());
}
}复制代码
// Slave-mongoTempalte
@Configuration
class @ConfigurationProperties(prefix = "secondary.mongodb") //前缀映射
public class SecondaryMongoConfig extends AbstractMongoConfig {
@Override public @Bean(name = "secondaryMongoTemplate")
MongoTemplate getMongoTemplate() throws Exception {
return new MongoTemplate(mongoDbFactory());
}
}复制代码
使用
//Using MongoTemplate for primary database
@Autowired
@Qualifier(value = "primaryMongoTemplate") //primarymongotemplate为默认的mongotemplate
protected MongoTemplate mongoTemplate;
//Using mongoTemplate for secondary database
@Autowired
@Qualifier(value = "secondaryMongoTemplate")
protected MongoTemplate mongoTemplate;复制代码