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;
@RunWith(SpringRunner.class)
@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)); }
} }
|