mongdb工具类
package e16wifi.statistic.com.mongodb;

import java.util.ArrayList;
import java.util.List; import org.bson.Document; import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase; import e16wifi.statistic.com.utils.DESUtil;
import e16wifi.statistic.com.utils.MongoDBProperty;
import e16wifi.statistic.com.utils.SysPropertyJdbc; public class MongoDBDao {
//数据库
private MongoDatabase database = null;
private DB get_db_credit = null;
private MongoCollection<Document> collection = null;
private DBCollection dbcollection = null;
private DBCursor dbCursor = null;
private MongoCursor<Document> cursor = null;
private FindIterable<Document> findIterable = null;
//客户端实例
private MongoClient mongoClient = null; /**
* 构造函数
* @throws Exception
*/
public MongoDBDao() throws Exception{
this.mongoClient =getMongoClient();
} public void getMongoDatabase(String dataBsae) throws Exception{
database = this.mongoClient.getDatabase(dataBsae);
} public void getDB(String dataBsae){
get_db_credit = this.mongoClient.getDB(dataBsae);
} public DBCollection getDBCollection(String dataBsae,String tableName){
getDB(dataBsae);
this.dbcollection = get_db_credit.getCollection(tableName);
return this.dbcollection ;
} public MongoCollection getMongoCollection(String dataBsae,String tableName) throws Exception{
getMongoDatabase(dataBsae);
this.collection = database.getCollection(tableName);
return this.collection;
} public MongoCursor<Document> getMongoCursor(String dataBsae,String tableName,BasicDBObject searchQueryCity,BasicDBObject sort) throws Exception{
getMongoCollection(dataBsae, tableName);
if(sort !=null){
this.cursor = this.collection.find(searchQueryCity).sort(sort).iterator();
}else{
this.cursor = this.collection.find(searchQueryCity).iterator();
} return cursor;
} public DBCursor getDBCursor(String dataBsae,String tableName,BasicDBObject searchQueryCity){
getDBCollection(dataBsae,tableName);
dbCursor = this.dbcollection.find(searchQueryCity);
return dbCursor;
} public FindIterable<Document> getFindIterable(String dataBsae,String tableName,BasicDBObject searchQueryCity,int page,int size, BasicDBObject sort) throws Exception{
getMongoCollection(dataBsae, tableName);
return findIterable = collection.find(searchQueryCity).skip(page).sort(sort)
.limit(size);
} public void closeDBCursor(){
dbCursor.close();
mongoClient.close();
} public void closeMongoCursor(){
cursor.close();
mongoClient.close();
} public void closeMongoClient(){
mongoClient.close();
}
/**
* 获取MONGODB客户端实例
*
* @return
* @throws Exception
*/
private MongoClient getMongoClient() throws Exception {
try {
// 解密用密钥
String sKey = SysPropertyJdbc.getProperty("jdbc.deskey")
.substring(4, 28); String sIp = DESUtil.decryptMode(sKey,
MongoDBProperty.getProperty("mip"));
int iPort = Integer.valueOf(DESUtil.decryptMode(sKey,
MongoDBProperty.getProperty("mport")));
String sUser = DESUtil.decryptMode(sKey,
MongoDBProperty.getProperty("muser"));
String sPasword = DESUtil.decryptMode(sKey,
MongoDBProperty.getProperty("mpassword"));
String sDbNm = DESUtil.decryptMode(sKey,
MongoDBProperty.getProperty("mdb")); // ===================================================//
List<ServerAddress> serverList = new ArrayList<ServerAddress>();
serverList.add(new ServerAddress(sIp, iPort));
// ===================================================//
List<MongoCredential> mcList = new ArrayList<MongoCredential>();
mcList.add(MongoCredential.createCredential(sUser, sDbNm,
sPasword.toCharArray()));
// ===================================================//
MongoClientOptions.Builder builder = MongoClientOptions.builder();
// 与目标数据库能够建立的最大connection数量为50
builder.connectionsPerHost(50);
// 如果当前所有的connection都在使用中,则每个connection上可以有50个线程排队等待
builder.threadsAllowedToBlockForConnectionMultiplier(50);
// 一个线程访问数据库的时候,在成功获取到一个可用数据库连接之前的最长等待时间为2分钟
// 这里比较危险,如果超过maxWaitTime都没有获取到这个连接的话,该线程就会抛出Exception
// 故这里设置的maxWaitTime应该足够大,以免由于排队线程过多造成的数据库访问失败
builder.maxWaitTime(1000 * 60 * 2);
// 与数据库建立连接的timeout设置为1分钟
builder.connectTimeout(1000 * 60 * 1);
// ===================================================//
MongoClientOptions mco = builder.build();
return new MongoClient(serverList, mcList, mco);
} catch (Exception e) {
throw e;
}
} }

mongdb取数据,(包含分页)


 PageView pageView = new PageView();
CommonUtil commonUtil = new CommonUtil();
String cityCode = this.getPara("selCity");// 当前城市
if (StringUtils.isNullOrEmpty(cityCode)) {
cityCode = iSelCity + "";
}
// 分页信息开始
String page = StringUtils.isNullOrEmpty(this.getPara("sPage"))
? "1"
: this.getPara("sPage");
Integer curPage = Integer.parseInt(page);
pageView.setCurrentPage(curPage);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
logger.debug("START...");
Date date = new Date();// 取时间
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.add(calendar.DATE, -1);// 把日期往后增加一天.整数往后推,负数往前移动
date = calendar.getTime();
// App用户基本信息
// mongoDB获取连接
MongoDBDao mongoClient = new MongoDBDao();
// 获取数据库
String mdb = DESUtil.decryptMode(
SysPropertyJdbc.getProperty("jdbc.deskey").substring(4, 28),
MongoDBProperty.getProperty("mdb")); BasicDBObject condition = new BasicDBObject();
condition.put("statDate", new BasicDBObject("$gte",matter2.parse(datestart)).append("$lte", matter2.parse(dateend))); //日期查询条件 查询时间范围 gt大于, lt小于 gte、ge大于等于   lte、le 小于等于
if (!"999".equals(cityCode)) {
condition.put("cityCode", cityCode);
}
BasicDBObject sort = new BasicDBObject();
// 1,表示正序; -1,表示倒序
sort.put("cityCode", 1);// 按照活跃度排名
MongoCursor<Document> cursor1 = mongoClient.getMongoCursor(mdb, "app_user_stat", condition,sort);
Integer i = 0;
try{
while (cursor1.hasNext()) {
cursor1.next();
i++;
}
} finally {
cursor1.close();
}
pageView.setTotal(i);
MongoCursor<Document> cursor = mongoClient.getFindIterable(mdb, "app_user_stat", condition, (curPage - 1) * pageView.getPageSize(), pageView.getPageSize(), sort).iterator();
List<Record> appDetail = new ArrayList<Record>();
try{
while (cursor.hasNext()) {
Iterator<Entry<String, Object>> iter = cursor.next().entrySet()
.iterator();
Record record = new Record();
while (iter.hasNext()) {
Entry eTmp = (Entry) iter.next();
Map colums = record.getColumns();
String sKeyTmp = eTmp.getKey().toString();
String sKeyValue = "";
if (eTmp.getValue() == null) {
sKeyValue = "0";
} else {
sKeyValue = eTmp.getValue().toString();
}
switch (sKeyTmp) {
case "statDate" :
if ("0".equals(sKeyValue)) {
colums.put("DATE", dateFormat.format(new Date()));
} else {
System.out.println("test" + sKeyValue);
colums.put("DATE",
dateFormat.format(eTmp.getValue()));
}
break;
case "cityName" :
// String cityName = TCity.dao
// .getCityInfoByCityCd(sKeyValue).get(0)
// .getStr("city_name");
colums.put("CITY", sKeyValue);
break;
case "userSum" :
colums.put("TOTALUSER", sKeyValue);
break;
case "newUserSum" :
colums.put("NEWADD", sKeyValue);
break;
case "activeUserDay" :
colums.put("ACTIVEDAY", sKeyValue);
break;
case "activeUserWeek" :
colums.put("ACTIVEWEEK", sKeyValue);
break;
case "activeUserMonth" :
colums.put("ACTIVEMONTH", sKeyValue);
break;
case "openTimes" :
colums.put("APPOPEN", sKeyValue);
break;
case "avgTimeDay" :
colums.put("AVGDAY", sKeyValue);
break;
case "avgTimeWeek" :
colums.put("AVGWEEK", sKeyValue);
break;
}
}
appDetail.add(record);
}
} finally {
cursor.close();
mongoClient.closeMongoClient();
}

 

MongoDBDao 工具类(包含分页取数据)的更多相关文章

  1. 借助Spring工具类如何实现支持数据嵌套的赋值操作

    假设有两个Bean A和B,想将B中的属性赋值到A实体中,可以使用get set来实现,当属性过多时,就会显得很冗余,可以使用spring提供的BeanUtils.copyProperties()来实 ...

  2. Java并发工具类之线程间数据交换工具Exchanger

    Exchanger是一个用于线程间协做的工具类,主要用于线程间的数据交换.它提供了一个同步点,在这个同步点,两个线程可以彼此交换数据.两个线程通过exchange方法交换数据,如果一个线程执行exch ...

  3. 利用BeanUtils工具类封装表单数据

    一.BeanUtils工具类的使用 1.首先导入BeanUtils工具类的jar包 commons-beanutils-1.8.0.jar commons-logging-1.1.1.jar 2.se ...

  4. 使用POI导出EXCEL工具类并解决导出数据量大的问题

    POI导出工具类 工作中常常会遇到一些图表需要导出的功能,在这里自己写了一个工具类方便以后使用(使用POI实现). 项目依赖 <dependency> <groupId>org ...

  5. 利用JDBC工具类添加和查询数据-Java(新手)

    JDBC工具类: 1 package cn.lxr.jdbclx; 2 3 import java.sql.*; 4 5 public class JDBCUtils { 6 private stat ...

  6. Javascript加载talbe(包含分页、数据下载功能)

    效果图如下: 首先简单说明一下,后面会给所涉及到的代码都贴上来的. 1.excel图标是一个用户控件,用来触发下载 2.首页.上页......每页多少条,这一块是一个整体,你可以选择放置在表格下面,或 ...

  7. SQL 2012 分页取数据

    ,), data int ) select * from t1 row rows only create clustered index t1c on t1(id) declare @i int ) ...

  8. php 循环从数据库分页取数据批量修改数据

    //批量修改email重复 public function getEmail() { $this->model = app::get('shop')->model('manage'); / ...

  9. c#中@标志的作用 C#通过序列化实现深表复制 细说并发编程-TPL 大数据量下DataTable To List效率对比 【转载】C#工具类:实现文件操作File的工具类 异步多线程 Async .net 多线程 Thread ThreadPool Task .Net 反射学习

    c#中@标志的作用   参考微软官方文档-特殊字符@,地址 https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/toke ...

随机推荐

  1. 【转】async & await 的前世今生

    async 和 await 出现在C# 5.0之后,给并行编程带来了不少的方便,特别是当在MVC中的Action也变成async之后,有点开始什么都是async的味道了.但是这也给我们编程埋下了一些隐 ...

  2. 第一篇 Entity Framework Plus 之 Audit

    一般系统会有登陆日志,操作日志,异常日志,已经满足大部分的需求了.但是有时候,还是需要Audit 审计日志,审计日志,主要针对数据增,改,删操作数据变化的记录,主要是对数据变化的一个追踪过程.其中主要 ...

  3. Java接口响应超时监控

    为什么要监控 服务化接口是提供服务的,接口正确性.稳定性是最最重要的,在保证正确的同时需要尽量提高接口响应时间. 有的团队会有专门的工具来对系统响应时间.吞吐量做监控,但如果团队没有这种"待 ...

  4. PHP学习笔记:输入一句话,实现单词倒序输出

    约定:句子以空格为词语分割符号,以句号为结束符号. 实现思路: 用函数explode(separator,string,limit)对字符串进行分割,再对得到的数据最后一个成员分割切掉符号.用一个新的 ...

  5. 在xcode中用 swift 进行网络服务请求

    xcode集成开发环境是运行于Mac苹果电脑上用于开发swift应用程序的工具,利用xcode可以很方便.直观的开发OS X和iOS系统所支持的应用程序. 1 开发环境: Mac OS 10.11 X ...

  6. jQuery+css3侧边栏导航菜单

    效果体验:http://hovertree.com/texiao/jquery/37/ 代码如下: <!doctype html> <html lang="zh" ...

  7. 自助式BI为何能取代传统BI,逐渐占据商业智能市场?

    前言:未来的时代将由数据勾画,未来的BI将是自助BI的时代 随着数据爆发式增长,像ERP.OA.CRM等系统在企业运用的越来越多.这些系统的使用必然会产生很多的数据,比如在产品加工设计测试维护过程中产 ...

  8. CentOS7系统安装及初始化

    1.运行VirtualBox5. 2.安装CentOS7系统. 注意:选择Basic Server类型 安装过程略. 3.修改计算机IP和计算机名. 1)nmtui 1.修改主机名: nmcli ge ...

  9. 学习笔记 MSSQL显错手工注入

    和朋友一起学习,速度就是快.感谢珍惜少年时. 网上很多都在长篇大论MSSQL显错手工注入,其实原理只有一小段.如下: ' and (查询一段内容)=1 and 'C'='Cnvarchar类型(查询一 ...

  10. When it comes to intrusion analysis and forensics

    以下内容的出现可以追溯到一个发生在互联网的安全事件: Z公司遭受某种攻击,服务器上被植入了Linux DDOS木马,部分系统命令入ls遭替换,攻击者已经获得该服务器root权限: 影响更恶劣的是,连接 ...