如何優(yōu)雅的進(jìn)行Spring整合MongoDB詳解
前言
本文重點(diǎn)是要將mongodb與spring整合到項(xiàng)目中去,在實(shí)踐中發(fā)現(xiàn)問題,追蹤問題,然后解決問題。下面話不多說了,來一起看看詳細(xì)的介紹吧。
一、準(zhǔn)備
- Maven、Spring(spring-data-mongodb)
- spring Data for MongoDB是Spring Data的一個子模塊。 目標(biāo)是為mongodb提供一個相近的一致的基于Spring的編程模型。
- Spring Data for MongoDB核心功能是映射POJO到Mongo的DBCollection中的文檔,并且提供Repository 風(fēng)格數(shù)據(jù)訪問層。
二、特性
- MongoDB的提供了一個面向文檔存儲,操作起來比較簡單和容易。
- 你可以在MongoDB記錄中設(shè)置任何屬性的索引 (如:FirstName="Ning",Address="Beijing")來實(shí)現(xiàn)更快的排序。
- 你可以通過本地或者網(wǎng)絡(luò)創(chuàng)建數(shù)據(jù)鏡像,這使得MongoDB有更強(qiáng)的擴(kuò)展性。
- 如果負(fù)載的增加(需要更多的存儲空間和更強(qiáng)的處理能力) ,它可以分布在計(jì)算機(jī)網(wǎng)絡(luò)中的其他節(jié)點(diǎn)上這就是所謂的分片。
- Mongo支持豐富的查詢表達(dá)式。查詢指令使用JSON形式的標(biāo)記,可輕易查詢文檔中內(nèi)嵌的對象及數(shù)組。
- MongoDb 使用update()命令可以實(shí)現(xiàn)替換完成的文檔(數(shù)據(jù))或者一些指定的數(shù)據(jù)字段 。
- Mongodb中的Map/reduce主要是用來對數(shù)據(jù)進(jìn)行批量處理和聚合操作。
- Map和Reduce。Map函數(shù)調(diào)用emit(key,value)遍歷集合中所有的記錄,將key與value傳給Reduce函數(shù)進(jìn)行處理。
- Map函數(shù)和Reduce函數(shù)是使用Javascript編寫的,并可以通過db.runCommand或mapreduce命令來執(zhí)行MapReduce操作。
- GridFS是MongoDB中的一個內(nèi)置功能,可以用于存放大量小文件。
- MongoDB允許在服務(wù)端執(zhí)行腳本,可以用Javascript編寫某個函數(shù),直接在服務(wù)端執(zhí)行,也可以把函數(shù)的定義存儲在服務(wù)端,下次直接調(diào)用即可。
- MongoDB支持各種編程語言:RUBY,PYTHON,JAVA,C++,PHP,C#等多種語言。
三、依賴包
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>1.5.0.RELEASE</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.5.10</version> </dependency>
spring 相關(guān)依賴
<!-- spring web相關(guān)依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.1.2.RELEASE</version> </dependency> <!-- spring test依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.1.RELEASE</version> </dependency>
四、集成MongoDB
【注:MongoDB添加權(quán)限管理請參見我的這篇文章:MongDB開啟權(quán)限認(rèn)證】
mongodb.properties
mongo.hostport=172.16.4.166:27017 mongo.dbname=ad_api_count mongo.username=hehaitao mongo.password=hehaitao mongo.connectionsPerHost=8 mongo.threadsAllowedToBlockForConnectionMultiplier=4 #\u8FDE\u63A5\u8D85\u65F6\u65F6\u95F4 mongo.connectTimeout=1000 #\u7B49\u5F85\u65F6\u95F4 mongo.maxWaitTime=1500 mongo.autoConnectRetry=true mongo.socketKeepAlive=true #Socket\u8D85\u65F6\u65F6\u95F4 mongo.socketTimeout=1500 mongo.slaveOk=true
mongoDB.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <!-- 加載mongodb的屬性配置文件 --> <context:property-placeholder location="classpath:mongodb.properties" ignore-unresolvable="true"/> <!-- 定義mongo對象,對應(yīng)的是mongodb官方j(luò)ar包中的Mongo,replica-set設(shè)置集群副本的ip地址和端口 --> <mongo:mongo id="mongo" replica-set="${mongo.hostport}"> <mongo:options connections-per-host="${mongo.connectionsPerHost}" threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}" connect-timeout="${mongo.connectTimeout}" max-wait-time="${mongo.maxWaitTime}" auto-connect-retry="${mongo.autoConnectRetry}" socket-keep-alive="${mongo.socketKeepAlive}" socket-timeout="${mongo.socketTimeout}" slave-ok="${mongo.slaveOk}" write-number="1" write-timeout="0" write-fsync="true"/> </mongo:mongo> <mongo:db-factory id="mgFactory" dbname="${mongo.dbname}" username="${mongo.username}" password="${mongo.password}" mongo-ref="mongo" /> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg name="mongoDbFactory" ref="mgFactory"/> </bean> </beans>
spring-contex.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd"> <aop:aspectj-autoproxy proxy-target-class="true"/> <!--使用注解管理bean --> <context:annotation-config/> <!-- 掃描com.lutongnet下的所有類 --> <context:component-scan base-package="com.lutong.cps"> <context:exclude-filter type = "annotation" expression = "org.springframework.stereotype.Controller"/> </context:component-scan> <import resource="mongoDB.xml"/> </beans>
五、代碼實(shí)現(xiàn)
基礎(chǔ)實(shí)現(xiàn)MongoDBService
/** * File Name : MongoDBService.java * Package : com.lutongnet.ad.service * Description : TODO * Author : zhangfj * Date : 2012-11-29 * Version : V1.0 */ package com.lutong.cps.schedule.service.fj; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Service; /** * @author zhangfj * */ @Service("mongoDBService") public class MongoDBService { /*@Resource(name = "mongoTemplate") protected MongoTemplate mongoTemplate;*/ /** * * @param query * @param entityClass * @return T */ public <T> T findOne(Query query, Class<T> entityClass) { ApplicationContext context=new ClassPathXmlApplicationContext("mongoDB.xml"); MongoTemplate mongoTemplate= (MongoTemplate) context.getBean("mongoTemplate"); // 可以直接調(diào)用 return mongoTemplate.findOne(query, entityClass); } }
繼承類UserAdCountService
/** * File Name : UserAdCountService.java * Package : com.lutongnet.ad.service * Description : TODO * Author : zhangfj * Date : 2012-11-29 * Version : V1.0 */ package com.lutong.cps.schedule.service.fj; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Service; import com.lutong.cps.schedule.entity.UserAdCount; /** * @author zhangfj * */ @Service("userAdCountService") public class UserAdCountService extends MongoDBService { /** * 獲取單個廣告的觀看次數(shù),查詢不到則返回0 * * @param adCode * @return int */ public int getUserAdCount(UserAdCount adCode) { Criteria criteria = new Criteria(); criteria.andOperator(Criteria.where("userAd").is(adCode.getUserAd()), Criteria.where("adCode").is(adCode.getAdCode()), Criteria.where("countDate").is(adCode.getCountDate())); Query query = new Query(criteria); UserAdCount result = findOne(query, UserAdCount.class); if (null != result) { return result.getTimesCount(); } return 0; } }
實(shí)體類UserAdCount
package com.lutong.cps.schedule.entity; import java.util.Date; import org.springframework.data.annotation.PersistenceConstructor; import org.springframework.data.mongodb.core.mapping.Document; /** * mongo專用統(tǒng)計(jì)單個用戶的單個廣告觀看次數(shù) * @author cancer * */ @Document(collection="userAdCount") public class UserAdCount { private int timesCount; /** * 用戶賬號 */ private String userAd; private String adCode; private String countDate; private Date expireAt; @PersistenceConstructor public UserAdCount(int timesCount, String userAd,String adCode,String countDate,Date expireAt) { this.timesCount = timesCount; this.userAd = userAd; this.adCode = adCode; this.countDate = countDate; this.expireAt = expireAt; } public UserAdCount(String userAd,String adCode,String countDate) { this.userAd = userAd; this.adCode = adCode; this.countDate = countDate; } public UserAdCount(String userAd,String adCode,String countDate,Date expireAt) { this.userAd = userAd; this.adCode = adCode; this.countDate = countDate; this.expireAt = expireAt; } public UserAdCount(String countDate) { this.countDate = countDate; } public int getTimesCount() { return timesCount; } public void setTimesCount(int timesCount) { this.timesCount = timesCount; } public String getUserAd() { return userAd; } public void setUserAd(String userAd) { this.userAd = userAd; } public String getAdCode() { return adCode; } public void setAdCode(String adCode) { this.adCode = adCode; } public String getCountDate() { return countDate; } public void setCountDate(String countDate) { this.countDate = countDate; } public Date getExpireAt() { return expireAt; } public void setExpireAt(Date expireAt) { this.expireAt = expireAt; } }
最后寫一個測試類來測試下
import java.util.List; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.acts.web.modules.mark.model.Users; import com.lutong.cps.schedule.service.fj.UserAdCountService; @ContextConfiguration({ "classpath:spring-context.xml", "classpath:mongoDB.xml"}) @RunWith(SpringJUnit4ClassRunner.class) public class UserTest { @Resource(name = "userAdCountService") private UserAdCountService userAdCountService; @Test public void testDao() { try { UserAdCount userAdCount = new UserAdCount("hehaitao", "pos001", DateTime.now().toString("yyyy-MM-dd")); int count = userAdCountService .getUserAdCount(userAdCount); System.out.println(count); } catch (Exception e) { e.printStackTrace(); } } }
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
Mybatis-Plus3.2.0 MetaObjectHandler 無法進(jìn)行公共字段全局填充
這篇文章主要介紹了Mybatis-Plus3.2.0 MetaObjectHandler 無法進(jìn)行公共字段全局填充,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11java后臺實(shí)現(xiàn)js關(guān)閉本頁面,父頁面指定跳轉(zhuǎn)或刷新操作
這篇文章主要介紹了java后臺實(shí)現(xiàn)js關(guān)閉本頁面,父頁面指定跳轉(zhuǎn)或刷新操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11TraceIdPatternLogbackLayout日志攔截源碼解析
這篇文章主要為大家介紹了TraceIdPatternLogbackLayout日志攔截源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11java swing實(shí)現(xiàn)的掃雷游戲及改進(jìn)版完整示例
這篇文章主要介紹了java swing實(shí)現(xiàn)的掃雷游戲及改進(jìn)版,結(jié)合完整實(shí)例形式對比分析了java使用swing框架實(shí)現(xiàn)掃雷游戲功能與相關(guān)操作技巧,需要的朋友可以參考下2017-12-12SpringCloud 服務(wù)網(wǎng)關(guān)路由規(guī)則的坑及解決
這篇文章主要介紹了SpringCloud 服務(wù)網(wǎng)關(guān)路由規(guī)則的坑及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07使用Springboot自定義注解,支持SPEL表達(dá)式
這篇文章主要介紹了使用Springboot自定義注解,支持SPEL表達(dá)式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02Java中的getClass()以及getName()方法使用
這篇文章主要介紹了Java中的getClass()以及getName()方法使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12java實(shí)現(xiàn)連接mysql數(shù)據(jù)庫單元測試查詢數(shù)據(jù)的實(shí)例代碼
下面小編就為大家?guī)硪黄猨ava實(shí)現(xiàn)連接mysql數(shù)據(jù)庫單元測試查詢數(shù)據(jù)的實(shí)例代碼。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-10-10