springboot配置多数据源的实例(MongoDB主从)
时间:2020-10-15 23:16:00|栏目:JAVA代码|点击: 次
相信看过上一篇文章的小伙伴已经知道了, 这章要讲的就是MongoDB主从配置。
在这边文章中,你将要学到的是在项目中配置主从数据库,并且兼容其他数据库哟。。这些都是博主项目中需要并且比较重要的知识哦~
好了,废话不多说,直接进主题。
1.pom依赖
<span style="white-space:pre"> </span><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
2.配置文件的编写
## master mongo master: mongodb: host: localhost port: 27017 database: db_ops ## slave1 mongo slave1: mongodb: host: localhost port: 27017 database: db_note ## zookeeper注册中心
3.配置文件的编写
在mongodb主从配置中,配置有所不同
1.配置父类AbstractMongoConfigure
public abstract class AbstractMongoConfigure {
private String host, database;
private int port;
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;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getDatabase() {
return database;
}
public void setDatabase(String database) {
this.database = database;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
2.主数据库配置
@Configuration
@EnableAutoConfiguration(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
@EnableMongoRepositories(basePackages = {"com.jx.ops.mapper.mongodb.ops"},mongoTemplateRef = "opsMongoTemplate")
@ComponentScan
@ConfigurationProperties(prefix = "ops.mongodb")
public class MongoMasterConfig extends AbstractMongoConfigure {
@Override
@Bean(name = "opsMongoTemplate")
@Primary //<span style="color:#ff0000;">重点哦</span>
public MongoTemplate getMongoTemplate() throws Exception {
return new MongoTemplate(mongoDbFactory());
}
}
3.从数据库配置
@Configuration
@EnableAutoConfiguration(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
@EnableMongoRepositories(basePackages = {"com.jx.ops.mapper.mongodb.post"},mongoTemplateRef = "postMongoTemplate")
@ComponentScan
@ConfigurationProperties(prefix = "post.mongodb")
public class MongoPostConfig extends AbstractMongoConfigure {
@Override
@Bean(name = "postMongoTemplate")
public MongoTemplate getMongoTemplate() throws Exception {
return new MongoTemplate(mongoDbFactory());
}
}
到此,主从数据库也讲解完毕,如果有不懂或出bug的小伙伴可以留言我哟。。
上一篇:spring-cloud入门之eureka-client(服务注册)
栏 目:JAVA代码
下一篇:浅谈maven单元测试设置代理
本文标题:springboot配置多数据源的实例(MongoDB主从)
本文地址:http://www.codeinn.net/misctech/11678.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




