Java连接MongoDB集群的几种方式,阿里技术官整合的四大主流中间件笔记【附源码】_程序员小虎

 MongoClient mongoClient = new MongoClient( "host1" , 27017 );? 

2.

 MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://host1:27017")); 

MongoDB将自动发现主要和副本。连接到副本集

You can specify the members using the?[MongoClientURI](

)?connection string:

指定两个副本集:

MongoClient mongoClient =?new?MongoClient(?new?MongoClientURI(?"mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myReplicaSet"));

至少有一个副本集和副本集选项的成员:

MongoClient mongoClient =?new?MongoClient(?new?MongoClientURI(?"mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myReplicaSet"));

你可以使用ServerAddress指定副本集中的所有成员.?

 MongoClient mongoClient = new MongoClient(  Arrays.asList(new ServerAddress("host1", 27017),                new ServerAddress("host2", 27017),                new ServerAddress("host3", 27017))); 

连接到分片集群

要连接到分片群集,请将mongos实例或多个实例指定给MongoClient构造函数。

连接到一个mongos实例:

MongoClient mongoClient =?new?MongoClient(?"localhost"?,?27017?);

连接多个?mongos?实例:

MongoClient mongoClient =?new?MongoClient(?new?MongoClientURI("mongodb://host1:27017,host2:27017"));

 MongoClient mongoClient = new MongoClient(     Arrays.asList(new ServerAddress("host1", 27017),                   new ServerAddress("host2", 27017))); 

连接选项

您可以使用MongoClientURIMongoClientOptions或两者来指定连接设置。

例如,您可以在MongoClientURI连接字符串中指定?TLS/SSL和身份验证设置:

 MongoClientURI uri = new MongoClientURI("mongodb://user1:pwd1@host1/?authSource=db1&ssl=true");  MongoClient mongoClient = new MongoClient(uri); 

您还可以使用MongoClientOptions来指定?TLS/SSL?和MongoCredential的认证信息:

  String user; // the user name   String database; // the name of the database in which the user is defined   char[] password; // the password as a character array   // ...   MongoCredential credential = MongoCredential.createCredential(user, database, password);  # 知其然不知其所以然,大厂常问面试技术如何复习?  **1、热门面试题及答案大全**  面试前做足功夫,让你面试成功率提升一截,这里一份热门350道一线互联网常问面试题及答案助你拿offer  > **[CodeChina开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频】](https://ali1024.coding.net/public/P7/Java/git)**  ![](https://s2.51cto.com/images/20210920/1632121497325351.jpg)  **2、多线程、高并发、缓存入门到实战项目pdf书籍**  ![](https://s2.51cto.com/images/20210920/1632121498588571.jpg)  ![](https://s2.51cto.com/images/20210920/1632121498985900.jpg)  ![](https://s2.51cto.com/images/20210920/1632121499214307.jpg)  **3、文中提到面试题答案整理**  ![](https://s2.51cto.com/images/20210920/1632121499371228.jpg)  **4、Java核心知识面试宝典**  覆盖了**JVM 、JAVA集合、JAVA多线程并发、JAVA基础、Spring原理、微服务、Netty与RPC、网络、日志、Zookeeper、Kafka、RabbitMQ、Hbase、MongoDB 、Cassandra、设计模式、负载均衡、数据库、一致性算法 、JAVA算法、数据结构、算法、分布式缓存、Hadoop、Spark、Storm的大量技术点且讲解的非常深入**  ![](https://s2.51cto.com/images/20210920/1632121499959876.jpg)  ![](https://s2.51cto.com/images/20210920/1632121500344529.jpg)  ![](https://s2.51cto.com/images/20210920/1632121500948251.jpg)

本站由小牛团队全力维护,小牛十年了,大家已经步入中年 。本站源码全部经过团队成员测试并调试,价格可能比其它网站略贵几元钱,不解释!
小牛资源 » Java连接MongoDB集群的几种方式,阿里技术官整合的四大主流中间件笔记【附源码】_程序员小虎

发表评论

全站资源亲测可用,价格略高几元,不解释

立即查看 了解详情