一、添加依赖
导入mongodb连接驱动包
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.6.3</version>
</dependency>
二、代码实现
import com.mongodb.*;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
public class mongoDB {
public static void main(String[] args) {
ServerAddress serverAddress = new ServerAddress("192.168.215.84",27017);
// List<ServerAddress> addrs = new ArrayList<ServerAddress>();
// addrs.add(serverAddress);
//
// credentials存储登录数据库管理,用户名root,authDB: admin,密码password
// MongoCredential credential = MongoCredential.createScramSha1Credential("admin","admin","password".toCharArray());
// List<MongoCredential> credentials = new ArrayList<MongoCredential>();
// credentials.add(credential);
//登录MongoDB服务器
MongoClient mongoClient = new MongoClient(serverAddress,getConfOptions());
MongoDatabase haoZShop = mongoClient.getDatabase("order");
System.out.println(haoZShop.getName());
MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
System.out.println(mongoDatabase.getName());
//创建表(集合)
// mongoDatabase.createCollection("haozhuoShop");
// System.out.println("集合创建成功");
MongoCollection<Document> collection = mongoDatabase.getCollection("list");
System.out.println("集合list选择成功");
insertMongDB(collection);
threadInsert(collection);
}
private static MongoClientOptions getConfOptions() {
return new MongoClientOptions.Builder().socketKeepAlive(true) // 是否保持长链接
.connectTimeout(5000) // 链接超时时间
.socketTimeout(5000) // read数据超时时间
.readPreference(ReadPreference.primary()) // 最近优先策略
.connectionsPerHost(30) // 每个地址最大请求数
.maxWaitTime(1000 * 60 * 2) // 长链接的最大等待时间
.threadsAllowedToBlockForConnectionMultiplier(50) // 一个socket最大的等待请求数
.writeConcern(WriteConcern.NORMAL).build();
}
public static void insertMongDB(MongoCollection<Document> collection) {
for (int i = 0; i < 2000000000; i++) {
Document document = new Document();
document.put("ID", "xxxxxxxxx");
document.put("PHONE", "abc");
document.put("MSG", "男");
document.put("CHKTIME", "2019-12-2");
collection.insertOne(document);
System.out.println("插入完成" + i);
}
}
public static void threadInsert(MongoCollection<Document> collection) {
// 匿名内部类对象实现
new Thread(
new Runnable() {
@Override
public void run() {
for (int i = 0; i < 2000000000; i++) {
Document document = new Document();
document.put("ID", "xxxxxxxxx");
document.put("PHONE", "abc");
document.put("MSG", "男");
document.put("CHKTIME", "2023-1-2");
collection.insertOne(document);
System.out.println("线程" + Thread.currentThread().getName() + "插入成功");
}
}
}
).start();
}
}
三、Linux性能检测工具
安装命令
yum install iotop -y
使用方法
iotop -o
以上记录Java向Mongodb数据库添加多条数据,如需在源库中直接添加多条的朋友可以去研究下js脚本去实现。