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中的两种方式