1、pom文件中增加依赖
<!--mongodb-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2、配置两个数据源
<!-- mongodb -->
<ecej.admin.mongodb.servers>mongodb://db.stmongo.ecej.com:27017/ecejaoss</ecej.admin.mongodb.servers>
<ecej.emp.mongodb.servers>mongodb://db.simongo.ecej.com:27017/employee_location_st</ecej.emp.mongodb.servers>
3、application.properties中增加数据源引入
spring.data.mongodb.uri=@ecej.admin.mongodb.servers@
spring.data.mongodb.emp.uri=@ecej.emp.mongodb.servers@
4、分别新建两个数据源加载类
@Configuration
@EnableMongoRepositories(mongoTemplateRef = "mongoTemplate")//指定注入名称
public class MongodbConfig{
//从配置文件注入地址
@Value("${spring.data.mongodb.uri}")
private String uri;
·//用mongo工厂创建mongoTemplate 、并指定bean的名称
@Primary
@Bean(name = "mongoTemplate")
public MongoTemplate statisMongoTemplate() throws Exception {
//删除mongo由类创建集合时默认生成的类字段
MappingMongoConverter c =
new MappingMongoConverter(statisFactory(), new MongoMappingContext());
c.setTypeMapper(new DefaultMongoTypeMapper(null));
return new MongoTemplate(statisFactory(), c);
}
//创建mongo实例工厂
@Bean
@Primary
public MongoDbFactory statisFactory() throws Exception {
//指定最大链接时间和超时时间
return new SimpleMongoDbFactory(new MongoClient(new MongoClientURI(uri, MongoClientOptions.builder().maxConnectionIdleTime(30000).connectTimeout(5000))), "ecejaoss");
}
}
@Configuration
@EnableMongoRepositories(mongoTemplateRef = "empMongoTemplate")
public class EmpMongoConfig {
@Value("${spring.data.mongodb.emp.uri}")
private String uri;
@Bean(name = "empMongoTemplate")
public MongoTemplate listTemplate() throws Exception {
//remove _class
MappingMongoConverter c =
new MappingMongoConverter(empMongoFactory(), new MongoMappingContext());
c.setTypeMapper(new DefaultMongoTypeMapper(null));
return new MongoTemplate(empMongoFactory(), c);
}
@Bean
public MongoDbFactory empMongoFactory() throws Exception {
String sourceName = "employee_location_dev";
if(StringUtils.isNotBlank(uri)){
String copUri = uri;
int idx = copUri.lastIndexOf("/");
if (idx == -1) {
throw new IllegalArgumentException("mongodb_uri配置错误");
} else {
sourceName = copUri.substring(idx+1);
}
}
return new SimpleMongoDbFactory(new MongoClient(new MongoClientURI(uri, MongoClientOptions.builder().maxConnectionIdleTime(30000).connectTimeout(5000))), sourceName);
}
}
5、应用实例
@Autowired
@Qualifier("empMongoTemplate")
private MongoTemplate empMongoTemplate;
@Autowired
@Qualifier("mongoTemplate ")
private MongoTemplate mongoTemplate ;
6、若出现链接超时问题、则需排除自动注入
在spingboot启动类中加入
@SpringBootApplication(exclude = {MongoAutoConfiguration.class,MongoDataAutoConfiguration.class})
网友评论