MongoDB和Web应用程序
當今時代是數據大規模增長的時代。 數據存儲不是問題,是的,但是結構化和存儲的方式可能會增加或減少所需數據塊的查找時間。
不斷增長的非結構化數據的用例
- 臉書:
- 7.5億用戶處于活躍狀態,三分之一的互聯網用戶擁有Facebook帳戶
- 每月共享的內容超過300億條(Web鏈接,新聞報道,博客文章,便箋,相冊等)。
- 容納30PB數據進行分析,每天增加12 TB壓縮數據
- 推特
- 2億用戶,每日2億條推文
- 每天有16億個搜索查詢
- 每天生成7 TB數據用于分析
在這樣的規模下,傳統的數據存儲,技術和分析工具不起作用!
當前方案要求需要NoSQL數據庫(例如Apache Cassandra,Mongo DB)來處理不斷增長的非結構化數據。 NoSQL數據庫提供比傳統RDBMS寬松的一致性模型,用于存儲和檢索數據。 NoSQL數據庫將數據存儲為高度優化的鍵值對,這導致簡單的檢索和附加操作,從而在低延遲和高吞吐量方面提高了性能。
在開發和維護大數據和實時Web應用程序的行業中,NoSQL數據庫發揮著重要作用。
Mongo數據庫和Web應用程序的用例
讓我們想象一下,我們想在后端使用JSF2.0和Mongo DB創建一個汽車注冊門戶。 將有兩個功能
- 汽車登記
- 查看已注冊汽車的報告
圖1描繪了要進行的項目的流程。
假設:
- Mongo DB已安裝并作為服務運行
- Eclipse靛藍或更高版本
- Tomcat 7.0或更高版本
- 存在必需的jar文件(JSF2.0 jars jsf-api.jar,jsf-impl),mongo-java-driver-2.10.1.jar或任何合適的版本
應用程序具有三個頁面,即Home.xhtml,AddCar.xhtml,Report.xhtml。
Home.xhtml的實現如下:
Home.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"xmlns:f="http://java.sun.com/jsf/core"xmlns:h="http://java.sun.com/jsf/html"xmlns:j="http://java.sun.com/jsp/jstl/core"> <h:head><meta http-equiv="content-type" content="text/html; charset=utf-8" /></h:head><h:body><f:view> <h:form><center> <h2> MSD Car Portal</h2><h4><h:outputLink value="AddCar.xhtml">Add Car</h:outputLink><br/><br/> <h:commandLink action="#{carBean.getCarDetails}" >See Registered Cars</h:commandLink></h4></center></h:form> </f:view></h:body> </html>單擊“ 添加汽車”鏈接后 ,將加載AddCar.xhtml并執行以下代碼行。
AddCar.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"xmlns:f="http://java.sun.com/jsf/core"xmlns:h="http://java.sun.com/jsf/html"xmlns:j="http://java.sun.com/jsp/jstl/core"> <h:head><meta http-equiv="content-type" content="text/html; charset=utf-8" /></h:head><h:body><f:view> <h:form><center><h2>MSD Car Portal</h2> <h3>Add a Car</h3><h:panelGrid border="2" columns="2"><h:outputText value="CarName"></h:outputText> <h:inputText value="#{carBean.carTO.carName}"></h:inputText><h:outputText value="Company"></h:outputText> <h:inputText value="#{carBean.carTO.company}"></h:inputText><h:outputText value="Model"></h:outputText> <h:inputText value="#{carBean.carTO.model}"> <f:convertDateTime pattern="dd-MMM-yyyy"></f:convertDateTime> </h:inputText><h:outputText value="CC"></h:outputText> <h:inputText value="#{carBean.carTO.cc}"></h:inputText><h:outputText value="Price"></h:outputText> <h:inputText value="#{carBean.carTO.price}"></h:inputText></h:panelGrid><h:commandButton action="#{carBean.addCar}" value="Add Car"></h:commandButton><br/><h:outputText value="#{carBean.message}"></h:outputText><br/><h:outputLink value="Home.xhtml">Home</h:outputLink></center></h:form> </f:view></h:body> </html>點擊“ 添加汽車”按鈕后,將調用CarBean (后備bean)的動作處理程序,并在后備Bean 中將CarTO (Car Transfer Object)發送到CarService的insertData函數,此處將CarTO值的值插入文檔中并將文檔添加到集合中。 然后單擊“ 主頁 Home.xhtml”。 以下清單顯示了CarBean的代碼。
CarBean.java
package mongo.db.bean; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import javax.faces.bean.ManagedBean; import mongo.db.service.CarService; import mongo.db.to.CarTO; @ManagedBean public class CarBean {private List<CarTO> list = new ArrayList<CarTO>();private String message;private CarTO carTO= new CarTO();/**Action handler to save the data in the collection*/public String addCar(){try {/**Inserting the data to the Service class to insert it intoMongo DB*/message= new CarService().insertData("testdb","MyNewJAVATableCollection3",carTO);/**Message property is shown on the Page to show successmessage on the page*/} catch (UnknownHostException e) {message= e.getMessage();}return "samePage";}/**Action handler to get the data from the collection*/public String getCarDetails(){try {/**Reading the data From the Service class which further readthe data from the Mongo DB */list = new CarService().findData("testdb","MyNewJAVATableCollection3");if(list.size()==0){message="No records Exist";}} catch (UnknownHostException e) {message= e.getMessage();}return "success";} /*Getters and setters to be coded*/ }服務類的代碼如下:
CarService.java
package mongo.db.service; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Calendar; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import mongo.db.to.CarTO; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MongoClient;public class CarService {/**Utility to Get the Connection from the database*/ public static DBCollection getConnection(String dbName, String collectionName)throws UnknownHostException {/** Connecting to MongoDB */MongoClient mongo = new MongoClient("localhost", 27017);/**Gets database, incase if the database is not existingMongoDB Creates it for you*/DB db = mongo.getDB(dbName);/**Gets collection / table from database specified ifcollection doesn't exists, MongoDB will create it foryou*/DBCollection table = db.getCollection(collectionName);return table;}/**function to insert the data to the database */ public String insertData(String dbName, String collectionName, CarTO carTO) throws UnknownHostException {/**Connecting to MongoDB*/ DBCollection table =CarService.getConnection(dbName, collectionName);/**creating a document to store as key and value*/BasicDBObject document = new BasicDBObject();document.put("carName", carTO.getCarName());document.put("company", carTO.getCompany());document.put("model", carTO.getModel());document.put("cc", carTO.getCc());document.put("Price", carTO.getPrice());/** inserting to the document to collection or table*/table.insert(document);return "Car added successfully with the record number :"+table.count(); }/**function to get Details from the database*/ public List<CarTO> findData(String dbName, String collectionName) throws UnknownHostException {/**Connecting to database*/ DBCollection table= CarService.getConnection(dbName, collectionName);/**getting results from the database*/ DBCursor cursor = table.find(); List<CarTO>list= new ArrayList<CarTO>();/**iterating over the documents got from the database*/ while (cursor.hasNext()) {DBObject obj= cursor.next();/**documentToMapUtility is coded to convert the document received from database to key value pairs and put it inside a map*/ Map map=CarService.documentToMapUtility(obj.toString());/**Map having values is iterated using entry set and CarTO is populated and CarTO is added in the List<CarTO> and this list returned*//**Getting the Entery Set from the map */ Set<Entry<String,String>> set= map.entrySet();/**Getting the Iterator to iterate the entry Set*/ Iterator<Entry<String,String>> itr= set.iterator();CarTO carTO = new CarTO();/**loop to put ever Key value pair to CarTO object*/ while(itr.hasNext()){Entry<String, String> entry = itr.next();String key=entry.getKey();/**Removing the unwanted from the keys*/key = CarService.subStringUtility(key);String value=entry.getValue();if(key.equalsIgnoreCase("carName")){carTO.setCarName(value.substring(2,value.length()-2));}else if(key.equalsIgnoreCase("company")){carTO.setCompany(value.substring(2,value.length()-2));}else if(key.equalsIgnoreCase("model")){String date[]=value.split("-");int year=Integer.parseInt(date[0].substring(2));int month=Integer.parseInt(date[1]);int datemon=Integer.parseInt(date[2].substring(0, date.length-1));Calendar c= Calendar.getInstance();c.set(Calendar.YEAR, year);c.set(Calendar.MONTH, month);c.set(Calendar.DATE, datemon);carTO.setModel(c.getTime());}else if(key.equalsIgnoreCase("cc")){carTO.setCc(Integer.parseInt(value.trim()));}else if(key.equalsIgnoreCase("Price")){carTO.setPrice(Double.parseDouble(value.trim()));}} /**inner While closed*/list.add(carTO); } /**while iterating over the cursor records closed here*/return list; }/**Utility to remove un wanted contents*/public static String subStringUtility (String s){return s.substring(2,s.length()-2);}/**Utility to convert the document to map*/public static Map<String,String> documentToMapUtility (String s){s= s.substring(1,s.length()-1);String sArr[]= s.split(",");Map<String,String> map = new LinkedHashMap<String,String>();for(int i=1;i<sArr.length;i++){if(!sArr[i].contains("$date")){String keyValue[]= sArr[i].split(":");map.put(keyValue[0],keyValue[1]);System.out.println(keyValue[0]+","+keyValue[1]);}else{String keyValue[]= sArr[i].split(":");map.put(keyValue[0],keyValue[2]);}}return map;}}以下清單顯示了傳輸對象類CarTO的內容
CarTO.java
package mongo.db.to; import java.util.Date; public class CarTO {private String carName;private String company;private Integer cc;private Double price;private Date model;/*Getters and Setters to be coded*/ }單擊主頁上的“查看注冊的汽車”鏈接時,因為它是命令鏈接,所以將執行CarBean的動作處理程序getCarDetails并在方法findData的幫助下從CarService類獲取詳細信息,請參閱動作處理程序getCarDetails的CarBean代碼。 下面的清單表示Report.xhtml的代碼。
Report.xhtml.java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"xmlns:f="http://java.sun.com/jsf/core"xmlns:h="http://java.sun.com/jsf/html"xmlns:j="http://java.sun.com/jsp/jstl/core"> <h:head><meta http-equiv="content-type" content="text/html; charset=utf-8" /></h:head><h:body><f:view> <h:form><center> <h2>MSD Car Portal</h2> <h3>Car Details</h3><h:dataTable value="#{carBean.list}" var="item" border="2" rendered="#{not empty carBean.list}"><h:column> <f:facet name="header"> <h:outputText value="CarName"></h:outputText> </f:facet> <h:outputText value="#{item.carName}"></h:outputText> </h:column><h:column> <f:facet name="header"> <h:outputText value="Company"></h:outputText> </f:facet> <h:outputText value="#{item.company}"></h:outputText> </h:column><h:column> <f:facet name="header"> <h:outputText value="Model"></h:outputText> </f:facet> <h:outputText value="#{item.model.time}"> <f:convertDateTime pattern="dd-MMM-yyyy"></f:convertDateTime> </h:outputText> </h:column><h:column> <f:facet name="header"> <h:outputText value="CC"></h:outputText> </f:facet> <h:outputText value="#{item.cc}"></h:outputText> </h:column><h:column> <f:facet name="header"> <h:outputText value="Price"></h:outputText> </f:facet> <h:outputText value="#{item.price}"></h:outputText> </h:column></h:dataTable><br/><h:outputText value="#{carBean.message}"></h:outputText><br/><h:outputLink value="Home.xhtml">Home</h:outputLink> </center></h:form> </f:view></h:body> </html>結論
從給定的示例中可以很明顯地看出,MongoDb可以與現有的Web框架集成,并且可以用于制作可以輕松處理大數據問題的Web應用程序。
參考:
- http://www.rabidgremlin.com/data20/
- http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/
- http://docs.oracle.com/javaee/6/tutorial/doc/bnaph.html
翻譯自: https://www.javacodegeeks.com/2013/09/mongodb-and-web-applications.html
總結
以上是生活随笔為你收集整理的MongoDB和Web应用程序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 受JAAS保护的JAX-RS端点
- 下一篇: 使用Couchbase分页