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(); }