java如何连接mongoDB
解决方法:
下面代码init()初始化MongoClient,getDb()获取数据库,insertOne插入方法,main方法是测试的
public class MongoDbConfig {
private static Logger log = Logger.getLogger(MongoDbConfig .class);
public static MongoClient mongoClient;
public static void init(){
//MongoClient类是线程安全和线程共享的。通常在应用程序中对指定的数据库集群只创建一个MongoClient实例
if(mongoClient==null){
MongoClientOptions.Builder builder = MongoClientOptions.builder();
//最大连接数
builder.connectionsPerHost(20);
//最小连接数
builder.minConnectionsPerHost(5);
//超时时间
builder.connectTimeout(8000);
// 一个线程成功获取到一个可用数据库之前的最大等待时间
builder.maxWaitTime(5000);
//此参数跟connectionsPerHost的乘机为一个线程变为可用的最大阻塞数,超过此乘机数之后的所有线程将及时获取一个异常.eg.connectionsPerHost=10 and threadsAllowedToBlockForConnectionMultiplier=5,最多50个线程等级一个链接,推荐配置为5
builder.threadsAllowedToBlockForConnectionMultiplier(5);
//最大空闲时间
builder.maxConnectionIdleTime(1000*10);
//连接超时时间
builder.socketTimeout(1000*30);
MongoClientOptions myOptions = builder.build();
//通过身份认证获取MongoDB连接
if(MongoConfig.AUTH==0){
ServerAddress serverAddress = new ServerAddress(MongoConfig.IP,MongoConfig.PORT); MongoCredential credential = MongoCredential.createCredential(MongoConfig.USERNAME, MongoConfig.DBNAME, MongoConfig.PASSWORD.toCharArray());
mongoClient = new MongoClient(serverAddress, credential, myOptions);
//免密连接
}else if(MongoConfig.AUTH==1){
mongoClient = new MongoClient(MongoConfig.IP,MongoConfig.PORT);
}
}
}
public static MongoDatabase getDb() {
MongoDatabase database =null;
if(mongoClient==null){
init();
}
try {
database = mongoClient.getDatabase("数据库名db0");
} catch (Exception e) {
log.error(e.getMessage());
}
return database;
}
public void insertOne(Document document,String collectionName){
MongoCollection<Document> collection = getDb().getCollection(collectionName);
try {
collection.insertOne(document);
} catch (Exception e) {
log.error(e.getMessage());
}
}
//测试,插入数据
public static void main(String[] args) {
MongoDb mongo = new MongoDb();
String sms="{'a':'2'}";
Document document = Document.parse(sms);
String collectionName = "数据库表名";
mongo.insertOne(document,collectionName);
}
}
本文链接:http://www.yayihouse.com/yayishuwu/chapter/1420