12.SpringDataMongoDB 连接副本集

 

SpringDataMongoDB 连接副本集

连接副本集 url 语法:

1
mongodb://host1,host2,host3/articledb?connect=replicaSet&slaveOk=true&replicaSet=[replication_name]
  • slaveOk=true:开启副本节点读的功能,可实现读写分离。
  • connect=replicaSet:自动到副本集中选择读写的主机。如果slaveOK是打开的,则实现了读写分离

主机必须是副本集中所有的主机,包括主节点、副本节点、仲裁节点

SpringDataMongoDB自动实现了读写分离

写操作时,只打开主节点连接

读操作是,同时打开主节点和从节点连接,但使用从节点获取数据

(1) 修改 application.yml

使用 uri 的方式连接

1
2
3
4
spring:
data:
mongodb:
uri: mongodb://192.168.76.128:27017,192.168.76.128:27018,192.168.76.132:27019/articledb?connect=replicaSet&slaveOk=true&replicaSet=myrs

(2) 运行测试类

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
30
31
32
33
34
35
36
37
38
39
package com.learn.article.service;

import com.learn.article.ArticleApplication;
import com.learn.article.po.Comment;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.test.context.junit4.SpringRunner;

import java.time.LocalDateTime;
import java.util.List;

// SpringBoot的Junit集成测试
@RunWith(SpringRunner.class)
// SpringBoot的测试环境初始化,参数:启动类
@SpringBootTest(classes = ArticleApplication.class)
public class CommentServiceTest {

@Autowired
private CommentService commentService;

@Test
public void testFindCommentList() {
List<Comment> commentList = commentService.findCommentList();
for (int i = 0; i < commentList.size(); i++) {
System.out.println(commentList.get(i));
}
// 从 SECONDARY 节点读取数据
// 2023-03-24 16:51:43.881 INFO 10280 --- [ main] org.mongodb.driver.connection : Opened connection [connectionId{localValue:5, serverValue:57}] to 192.168.76.128:27017


// Comment{id='641cc67ab8fd97e6b05dd3bd', content='今天天气真好,阳光明媚', publishtime=null, userid='1001', nickname='Rose', createdatetime=2023-03-24T05:36:58.736, likenum=null, replynum=null, state='null', parentid='null', articleid='100000'}
// Comment{id='1', content='morning', publishtime=null, userid='1002', nickname='lake', createdatetime=2019-08-06T06:08:15.522, likenum=1000, replynum=null, state='1', parentid='null', articleid='100001'}
// Comment{id='641d5cc9546c2d2c0c5361b5', content='afternoon', publishtime=null, userid='null', nickname='null', createdatetime=null, likenum=null, replynum=null, state='null', parentid='null', articleid='100002'}
// Comment{id='641d60da546c2d2c0c5361b7', content='evening', publishtime=null, userid='null', nickname='null', createdatetime=null, likenum=null, replynum=null, state='null', parentid='null', articleid='100003'}
}
}