java连接mongoDB的高可用性实现

mongodb高可用集群示意图如下:
在这里插入图片描述

在这里插入图片描述

副本集中的副本节点在主节点挂掉后通过心跳机制检测到后,就会在集群内发起主节点的选举机制,自动选举一位新的主服务器。
三个节点有一个节点挂掉也不会影响应用程序客户端对整个副本集的读写!


使用mongoDB集群实现高可用性HA,如果其中一台机器宕机,mongodb集群的连接主机自动会切换到其他主机,java实现代码如下:

package cetc.anji.judgeSpeed.topology;

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

/** 
* 描述:
* @author: fangchangtan
* @version 创建时间:2018年11月26日 下午7:45:29 
*/
public class TestMongoDBReplSet {

	public static void main(String[] args) {
		ArrayList<ServerAddress> arrayList = new ArrayList<>();
        try {
              List<ServerAddress> addresses = new ArrayList<ServerAddress>();
              ServerAddress address1 = new ServerAddress("192.168.xx.2" , 27017);
              ServerAddress address2 = new ServerAddress("192.168.xx.5" , 27017);
              ServerAddress address3 = new ServerAddress("192.168.xx.7" , 27017);
              addresses.add(address1);
              addresses.add(address2);
              addresses.add(address3);

              MongoClient mongoClient = new MongoClient(addresses);
              MongoDatabase database = mongoClient.getDatabase("LastDataNew");
              MongoCollection<Document> collection = database.getCollection("Last_AssetEvent_FXD");

               // 插入
              FindIterable<Document> find = collection.find();
              for(Document doc : find){
            	  System.out.println(doc);
              }

       } catch (Exception e) {
              e.printStackTrace();
       }

}

}

猜你喜欢

转载自blog.csdn.net/fct2001140269/article/details/84555407