本次测试是通过java代码直接连接Mongodb集群,执行增删改查操作来完成对集群的测试。
jar准备
由于mongodb复制集的版本为3.4.3,需要我们到mongodb官网去下载对应的java驱动包mongo-java-driver-3.2.1.jar。
集群连接
package com.mongo.demo;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientOptions.Builder;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
public class MongoDao {
private static MongoClient client;
// 数据库
private static DB db;
// 相当于mysql数据库的表
private static DBCollection collection;
static {
// 1.构建mongo 复制集客户端
List<ServerAddress> list = new ArrayList<>();
list.add(new ServerAddress("localhost", 28010));
list.add(new ServerAddress("localhost", 28011));
list.add(new ServerAddress("localhost", 28012));
// 2.用来做认证的
List<MongoCredential> credentials = new ArrayList<>();
// 3.0 以下版本 createMongoCRCredential 3.0 以上 createCredential()
credentials.add(MongoCredential.createCredential("root", "admin", "sports".toCharArray()));
credentials.add(MongoCredential.createCredential("cyb", "User", "cyb".toCharArray()));
// 3.用来做mongo复制集的基本配置
Builder builder = new Builder();
// 4.自动重连
// builder.autoConnectRetry(true);
// 5.每个mongodb服务器的连接数
builder.connectionsPerHost(1000);
// 6.连接超时
builder.maxWaitTime(100000);
// 7.每个连接上的线程数
builder.threadsAllowedToBlockForConnectionMultiplier(50);
MongoClientOptions options = builder.build();
// 8.参数一: 复制集地址 参数二:用来做认证的 参数三: mongo复制集的基本参数设置
client = new MongoClient(list, credentials, options);
}
// 测试
public static void main(String[] args) {
db = client.getDB("User");
// 9.创建表
collection = db.createCollection("user", null);
DBObject data = new BasicDBObject();
data.put("user", "cqh");
data.put("pwd", "cqh");
// 10.根据表插入数据
collection.insert(data);
}
}