温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

springboot配置多数据源的实例(MongoDB主从)

发布时间:2020-09-21 22:47:36 来源:脚本之家 阅读:303 作者:小_白狼 栏目:编程语言

相信看过上一篇文章的小伙伴已经知道了, 这章要讲的就是MongoDB主从配置。

在这边文章中,你将要学到的是在项目中配置主从数据库,并且兼容其他数据库哟。。这些都是博主项目中需要并且比较重要的知识哦~

好了,废话不多说,直接进主题。

1.pom依赖

<span >		</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 >重点哦</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的小伙伴可以留言我哟。。

以上这篇springboot配置多数据源的实例(MongoDB主从)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI