相信看過上一篇文章的小伙伴已經(jīng)知道了, 這章要講的就是MongoDB主從配置。
在這邊文章中,你將要學(xué)到的是在項(xiàng)目中配置主從數(shù)據(jù)庫,并且兼容其他數(shù)據(jù)庫喲。。這些都是博主項(xiàng)目中需要并且比較重要的知識哦~
好了,廢話不多說,直接進(jìn)主題。
1.pom依賴
1
2
3
4
|
< span style = "white-space:pre" > </ span >< dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-data-mongodb</ artifactId > </ dependency > |
2.配置文件的編寫
1
2
3
4
5
6
7
8
9
10
11
12
13
|
## 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
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.主數(shù)據(jù)庫配置
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@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;" >重點(diǎn)哦</ span > public MongoTemplate getMongoTemplate() throws Exception { return new MongoTemplate(mongoDbFactory()); } } |
3.從數(shù)據(jù)庫配置
1
2
3
4
5
6
7
8
9
10
11
12
|
@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()); } } |
到此,主從數(shù)據(jù)庫也講解完畢,如果有不懂或出bug的小伙伴可以留言我喲。。
以上這篇springboot配置多數(shù)據(jù)源的實(shí)例(MongoDB主從)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://blog.csdn.net/m0_37625860/article/details/78913057