mongodb java 单例_Java单例MongoDB工具类

我经常对MongoDB进行一些基础操作,将这些常用操作合并到一个工具类中,方便自己开发使用。

没用Spring Data、Morphia等框架是为了减少学习、维护成本,另外自己直接JDBC方式的话可以更灵活,为自己以后的积累留一个脚印。

Java驱动版本:

org.mongodb

mongo-java-driver

3.0.2

工具类代码如下:

package utils;

import java.util.ArrayList;

import java.util.List;

import org.apache.commons.configuration.CompositeConfiguration;

import org.apache.commons.configuration.ConfigurationException;

import org.apache.commons.configuration.PropertiesConfiguration;

import org.bson.Document;

import org.bson.conversions.Bson;

import org.bson.types.ObjectId;

import com.mongodb.BasicDBObject;

import com.mongodb.MongoClient;

import com.mongodb.MongoClientOptions;

import com.mongodb.MongoClientOptions.Builder;

import com.mongodb.WriteConcern;

import com.mongodb.client.MongoCollection;

import com.mongodb.client.MongoCursor;

import com.mongodb.client.MongoDatabase;

import com.mongodb.client.MongoIterable;

import com.mongodb.client.model.Filters;

import com.mongodb.client.result.DeleteResult;

/**

* MongoDB工具类 Mongo实例代表了一个数据库连接池,即使在多线程的环境中,一个Mongo实例对我们来说已经足够了

* 注意Mongo已经实现了连接池,并且是线程安全的。

* 设计为单例模式, 因 MongoDB的Java驱动是线程安全的,对于一般的应用,只要一个Mongo实例即可,

* Mongo有个内置的连接池(默认为10个) 对于有大量写和读的环境中,为了确保在一个Session中使用同一个DB时,

* DB和DBCollection是绝对线程安全的

*

* @author zhoulingfei

* @date 2015-5-29 上午11:49:49

* @version 0.0.0

* @Copyright (c)1997-2015 NavInfo Co.Ltd. All Rights Reserved.

*/

public enum MongoDBUtil {

/**

* 定义一个枚举的元素,它代表此类的一个实例

*/

instance;

private MongoClient mongoClient;

static {

System.out.println("===============MongoDBUtil初始化========================");

CompositeConfiguration config = new CompositeConfiguration();

try {

config.addConfiguration(new PropertiesConfiguration("mongodb.properties"));

} catch (ConfigurationException e) {

e.printStackTrace();

}

// 从配置文件中获取属性值

String ip = config.getString("host");

int port = config.getInt("port");

instance.mongoClient = new MongoClient(ip, port);

// or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members

// List listHost = Arrays.asList(new ServerAddress("localhost", 27017),new ServerAddress("localhost", 27018));

// instance.mongoClient = new MongoClient(listHost);

// 大部分用户使用mongodb都在安全内网下,但如果将mongodb设为安全验证模式,就需要在客户端提供用户名和密码:

// boolean auth = db.authenticate(myUserName, myPassword);

Builder options = new MongoClientOptions.Builder();

// options.autoConnectRetry(true);// 自动重连true

// options.maxAutoConnectRetryTime(10); // the maximum auto connect retry time

options.connectionsPerHost(300);// 连接池设置为300个连接,默认为100

options.connectTimeout(15000);// 连接超时,推荐>3000毫秒

options.maxWaitTime(5000); //

options.socketTimeout(0);// 套接字超时时间,0无限制

options.threadsAllowedToBlockForConnectionMultiplier(5000);// 线程队列数,如果连接线程排满了队列就会抛出“Out of semaphores to get db”错误。

options.writeConcern(WriteConcern.SAFE);//

options.build();

}

// ------------------------------------共用方法---------------------------------------------------

/**

* 获取DB实例 - 指定DB

*

* @param dbName

* @return

*/

public MongoDatabase getDB(String dbName) {

if (dbName != null && !"".equals(dbName)) {

MongoDatabase database = mongoClient.getDatabase(dbName);

return database;

}

return null;

}

/**

* 获取collection对象 - 指定Collection

*

* @param collName

* @return

*/

public MongoCollection getCollection(String dbName, String collName) {

if (null == collName || "".equals(collName)) {

return null;

}

if (null == dbName || "".equals(dbName)) {

return null;

}

MongoCollection collection = mongoClient.getDatabase(dbName).getCollection(collName);

return collection;

}

/**

* 查询DB下的所有表名

*/

public List getAllCollections(String dbName) {

MongoIterable colls = getDB(dbName).listCollectionNames();

List _list = new ArrayList();

for (String s : colls) {

_list.add(s);

}

return _list;

}

/**

* 获取所有数据库名称列表

*

* @return

*/

public MongoIterable getAllDBNames() {

MongoIterable s = mongoClient.listDatabaseNames();

return s;

}

/**

* 删除一个数据库

*/

public void dropDB(String dbName) {

getDB(dbName).drop();

}

/**

* 查找对象 - 根据主键_id

*

* @param collection

* @param id

* @return

*/

public Document findById(MongoCollection coll, String id) {

ObjectId _idobj = null;

try {

_idobj = new ObjectId(id);

} catch (Exception e) {

return null;

}

Document myDoc = coll.find(Filters.eq("_id", _idobj)).first();

return myDoc;

}

/** 统计数 */

public int getCount(MongoCollection coll) {

int count = (int) coll.count();

return count;

}

/** 条件查询 */

public MongoCursor find(MongoCollection coll, Bson filter) {

return coll.find(filter).iterator();

}

/** 分页查询 */

public MongoCursor findByPage(MongoCollection coll, Bson filter, int pageNo, int pageSize) {

Bson orderBy = new BasicDBObject("_id", 1);

return coll.find(filter).sort(orderBy).skip((pageNo - 1) * pageSize).limit(pageSize).iterator();

}

/**

* 通过ID删除

*

* @param coll

* @param id

* @return

*/

public int deleteById(MongoCollection coll, String id) {

int count = 0;

ObjectId _id = null;

try {

_id = new ObjectId(id);

} catch (Exception e) {

return 0;

}

Bson filter = Filters.eq("_id", _id);

DeleteResult deleteResult = coll.deleteOne(filter);

count = (int) deleteResult.getDeletedCount();

return count;

}

/**

* FIXME

*

* @param coll

* @param id

* @param newdoc

* @return

*/

public Document updateById(MongoCollection coll, String id, Document newdoc) {

ObjectId _idobj = null;

try {

_idobj = new ObjectId(id);

} catch (Exception e) {

return null;

}

Bson filter = Filters.eq("_id", _idobj);

// coll.replaceOne(filter, newdoc); // 完全替代

coll.updateOne(filter, new Document("$set", newdoc));

return newdoc;

}

public void dropCollection(String dbName, String collName) {

getDB(dbName).getCollection(collName).drop();

}

/**

* 关闭Mongodb

*/

public void close() {

if (mongoClient != null) {

mongoClient.close();

mongoClient = null;

}

}

/**

* 测试入口

*

* @param args

*/

public static void main(String[] args) {

String dbName = "GC_MAP_DISPLAY_DB";

String collName = "COMMUNITY_BJ";

MongoCollection coll = MongoDBUtil.instance.getCollection(dbName, collName);

// 插入多条

// for (int i = 1; i <= 4; i++) {

// Document doc = new Document();

// doc.put("name", "zhoulf");

// doc.put("school", "NEFU" + i);

// Document interests = new Document();

// interests.put("game", "game" + i);

// interests.put("ball", "ball" + i);

// doc.put("interests", interests);

// coll.insertOne(doc);

// }

// // 根据ID查询

// String id = "556925f34711371df0ddfd4b";

// Document doc = MongoDBUtil2.instance.findById(coll, id);

// System.out.println(doc);

// 查询多个

// MongoCursor cursor1 = coll.find(Filters.eq("name", "zhoulf")).iterator();

// while (cursor1.hasNext()) {

// org.bson.Document _doc = (Document) cursor1.next();

// System.out.println(_doc.toString());

// }

// cursor1.close();

// 查询多个

// MongoCursor cursor2 = coll.find(Person.class).iterator();

// 删除数据库

// MongoDBUtil2.instance.dropDB("testdb");

// 删除表

// MongoDBUtil2.instance.dropCollection(dbName, collName);

// 修改数据

// String id = "556949504711371c60601b5a";

// Document newdoc = new Document();

// newdoc.put("name", "时候");

// MongoDBUtil.instance.updateById(coll, id, newdoc);

// 统计表

// System.out.println(MongoDBUtil.instance.getCount(coll));

// 查询所有

Bson filter = Filters.eq("count", 0);

MongoDBUtil.instance.find(coll, filter);

}

}

也请多提宝贵意见和建议。0b1331709591d260c1c78e86d0c51c18.png

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/539572.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Spring IOC容器-注解的方式

注解方式可以简化spring的IOC容器的配置&#xff0c;但不利于后期维护&#xff0c;对象之间的依赖关系不能像xml文件一样方便查阅&#xff0c;一目了然。 注解可以和XML配置一起使用。 使用注解步骤&#xff1a; 1&#xff09;先引入context名称空间 xmlns:context"htt…

前端请求进化之路--从form表单到JSONP

简单梳理前端请求的变迁史&#xff0c;着重对JSONP进行整理 请求演变 使用form表单提交请求&#xff0c;缺点是每次提交必定会刷新页面在1基础之上使用iframe进行局部刷新&#xff0c;用户体验得到一定优化动态创建图片提交请求 注意请求与返回内容类型须一致每次必须返回图片较…

Spring IOC容器-注解的方式【更简化】

----更加简化的版本 UserAction.java import javax.annotation.Resource;import org.springframework.stereotype.Component; import org.springframework.stereotype.Controller;//Component("userAction") // 加入IOC容器//ComponentController // 控制层的组件…

hive安装mysql驱动_Hadoop-2.6.0为基础的Hive安装

Hive安装软件需求与环境说明假设已经搭建好 Hadoop-2.6.0 环境&#xff0c;并能正常运行mysql 安装软件服务端&#xff1a;MySQL-server-5.5.16-1.rhel5.x86_64.rpm客户端&#xff1a;MySQL-client-5.5.16-1.rhel5.x86_64.rpmhive安装软件&#xff1a;apache-hive-1.2.1-bin.ta…

视频通信原理——NAT介绍

一&#xff1a;为什么需要NAT由于IP地址随着互联网的发展而逐渐稀缺&#xff0c;难以使得每台主机都拥有一个公网上的IP地址&#xff0c;且并不是所有主机都需要一个公网上的地址&#xff0c;于是就有了NAT技术。NAT&#xff08;The IP Network Address Translator&#xff09;…

Oracle中执行存储过程call和exec区别

在sqlplus中这两种方法都可以使用&#xff1a; exec pro_name(参数1..); call pro_name(参数1..); 区别&#xff1a; 1. 但是exec是sqlplus命令&#xff0c;只能在sqlplus中使用&#xff1b;call为SQL命令&#xff0c;没有限制. 2. 存储过程没有参数时,exec可以直接跟过…

java和cnc_Java程序员的目标,你都达到了多少条?

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼7.你需要学习Servlets&#xff0c;JSP&#xff0c;以及JSTL(StandardTagLibraries)和可以选择的第三方TagLibraries。8.你需要熟悉主流的网页框架&#xff0c;例如JSF&#xff0c;Struts&#xff0c;Tapestry&#xff0c;Cocoon&am…

每秒处理10万订单乐视集团支付架构

原文&#xff1a;http://www.iteye.com/news/31550 ----------- 随着乐视硬件抢购的不断升级&#xff0c;乐视集团支付面临的请求压力百倍乃至千倍的暴增。作为商品购买的最后一环&#xff0c;保证用户快速稳定的完成支付尤为重要。所以在15年11月&#xff0c;我们对整个支付…

X--名称空间详解

转自:http://blog.csdn.net/lisenyang/article/details/18312039 X名称空间里面的成员(如X:Name,X:Class)都是写给XAML编译器看的、用来引导XAML代码将XAML代码编译为CLR代码。 4.1X名称空间里面到底都有些什么&#xff1f; x名称空间映射的是:http://schemas.microsoft.com/wi…

事物 php,什么是php事务

事务&#xff1a;用于保证数据的一致性&#xff0c;他由一组相关的dml语句组成&#xff0c;改组的dml语句要么全部成功&#xff0c;要么全部失败。当前版本的插件并不是事务安全的&#xff0c;因为他并没有识别全部的事务操作。SQL 事务单元是在单一服务器中运行的。插件并不能…

那些年,在nodejs上踩过的坑

原文&#xff1a;http://cnodejs.org/topic/4fc7789a8be5d070121141cd ----------------------------------------------------------- 自己写nodejs也有一段时间&#xff0c;踩过很多坑&#xff08;而且大部分是自己给自己埋&#xff09;&#xff0c;也见过很多别人踩过的坑&…

Flask form(登录,注册)

用户登录 from flask import Flask, render_template, request, redirect from wtforms import Form from wtforms.fields import core from wtforms.fields import html5 from wtforms.fields import simple from wtforms import validators from wtforms import widgetsapp …

substr php,PHP substr() 函数

更多实例例子 1使用带有不同正负数的 start 参数&#xff1a;<?phpecho substr("Hello world",10)."";echo substr("Hello world",1)."";echo substr("Hello world",3)."";echo substr("Hello world&quo…

怎么看so文件是哪个aar引进来的_手机爱奇艺下载视频存在哪个文件夹

我们很多朋友喜欢看视频使用爱奇艺观看&#xff0c;并且喜欢直接把视频缓冲到手机里&#xff0c;或是直接下载视频文件&#xff0c;但是经常不知道手机爱奇艺下载视频存在哪个文件夹&#xff0c;不知道怎么分享给好友或是传到电脑上&#xff0c;下面就来简单介绍一下。手机爱奇…

Node.js 异步编程之 Callback介绍

原文&#xff1a;http://www.jb51.net/article/63070.htm ------------------------------------- Node.js 基于 JavaScript 引擎 v8&#xff0c;是单线程的。Node.js 采用了与通常 Web 上的 JavaScript 异步编程的方式来处理会造成阻塞的I/O操作。在 Node.js 中读取文件、访问…

php双向链表+性能,PHP双向链表定义与用法示例

本文实例讲述了PHP双向链表定义与用法。分享给大家供大家参考&#xff0c;具体如下&#xff1a;由于需要对一组数据多次进行移动操作&#xff0c;所以写个双向链表。但对php实在不熟悉&#xff0c;虽然测试各个方法没啥问题&#xff0c;就是不知道php语言深层的这些指针和unset…

反击爬虫,前端工程师的脑洞可以有多大?

对于一张网页&#xff0c;我们往往希望它是结构良好&#xff0c;内容清晰的&#xff0c;这样搜索引擎才能准确地认知它。 而反过来&#xff0c;又有一些情景&#xff0c;我们不希望内容能被轻易获取&#xff0c; 前言 比方说电商网站的交易额&#xff0c;教育网站的题目等。因为…

Spring与Struts框架整合

Spring&#xff0c;负责对象对象创建 Struts&#xff0c;用Action处理请求 Spring与Struts框架整合&#xff0c;关键点&#xff1a;让struts框架action对象的创建&#xff0c;交给spring完成&#xff01; 1.步骤&#xff1a; 引入jar文件 1&#xff09;引入struts .jar相关文件…

esxi能直通的显卡型号_显卡刷bios教程

一般来说显卡默认的出厂bios就已经很稳定&#xff0c;如果没有特殊情况下建议不要刷显卡bios。一般而言部分网友刷显卡BIOS目的是开核或超频&#xff0c;那么对于一个不会刷显卡bios的网友来说肯定会问显卡怎么刷bios类似的问题&#xff0c;那么本文这里就说一下有关显卡怎么刷…

关于Linux网卡调优之:RPS (Receive Packet Steering)

昨天在查LVS调度均衡性问题时&#xff0c;最终确定是 persistence_timeout 参数会使用IP哈希。目的是为了保证长连接&#xff0c;即一定时间内访问到的是同一台机器。而我们内部系统&#xff0c;由于出口IP相对单一&#xff0c;所以总会被哈希到相同的RealServer。 过去使用LVS…