yaml配置文件:
spring:
data:
mongodb:
uri: mongodb://admin:密码@ip:27017/paasoo?authSource=admin
other:
uri: mongodb://admin:密码@ip:27017/conversation?authSource=admin
java config文件:
package com.paasoo.quartz.config.mongo;
import org.springframework.beans.factory.annotation.Value;
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.core.SimpleMongoClientDatabaseFactory;
/**
* @Author: bin.liu
* @Date: 2023/7/5 14:11
* @Description:
*/
@Configuration
public class MultipleMongoConfig {
@Value("${spring.data.mongodb.uri}")
private String primaryUri;
@Value("${spring.data.mongodb.other.uri}")
private String otherUri;
@Primary
@Bean(name = "mongoTemplate")
public MongoTemplate primaryMongoTemplate() {
SimpleMongoClientDatabaseFactory simpleMongoClientDbFactory = new SimpleMongoClientDatabaseFactory(primaryUri);
return new MongoTemplate(simpleMongoClientDbFactory);
}
@Bean(name = "conversationMongoTemplate")
public MongoTemplate conversationMongoTemplate() {
SimpleMongoClientDatabaseFactory simpleMongoClientDbFactory = new SimpleMongoClientDatabaseFactory(otherUri);
return new MongoTemplate(simpleMongoClientDbFactory);
}
}
实际调用:
因为一开始是一个 mongo库, 已经有很多代码用了mongoTemplate,所以尽量不用动以前的代码,实现两个都可以用: