1. 程式人生 > >springmvc + mongodb 整合

springmvc + mongodb 整合

前幾天準備做一個專案,由於資料橫向可拓展性,最終選擇了用mongodb 資料庫  

本來以為應該是很好配的,結果弄了好幾天才將將弄好,

現在把自己的配置貼出來做個記錄

由於一開始 想的是 springmvc + mybatis + mongodb  然後 死活 整合不了 dao層 ,然後就迷茫了  

然後想著用 MySQL + mongodb 的方式,後來研究後 發現了 兩個東西  

hibernate orm  ,spring_data_mongodb ,兩個  整合nosql 資料庫dao層的框架,

本著熟悉的精神,選用了 spring_data_moongodb

最終 棄用 mybatis

首先 建立 maven 分模組專案,這個我就不說了 ,建立好後 引入依賴包

pom.xml

<dependencies>
			<!-- spring -->
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-context</artifactId>
				<version>4.2.0.RELEASE</version>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-aop</artifactId>
				<version>4.2.0.RELEASE</version>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-web</artifactId>
				<version>4.2.0.RELEASE</version>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-webmvc</artifactId>
				<version>4.2.0.RELEASE</version>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-tx</artifactId>
				<version>4.2.0.RELEASE</version>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-jdbc</artifactId>
				<version>4.2.0.RELEASE</version>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-orm</artifactId>
				<version>4.2.0.RELEASE</version>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-test</artifactId>
				<version>4.2.0.RELEASE</version>
			</dependency>
			<dependency>
				<groupId>org.springframework.security</groupId>
				<artifactId>spring-security-core</artifactId>
				<version>4.0.2.RELEASE</version>
			</dependency>
			<dependency>
				<groupId>org.springframework.security</groupId>
				<artifactId>spring-security-web</artifactId>
				<version>4.0.2.RELEASE</version>
			</dependency>
			<dependency>
				<groupId>org.springframework.security</groupId>
				<artifactId>spring-security-config</artifactId>
				<version>4.0.2.RELEASE</version>
			</dependency>
			<dependency>
				<groupId>org.springframework.security.oauth</groupId>
				<artifactId>spring-security-oauth2</artifactId>
				<version>2.0.7.RELEASE</version>
			</dependency>
			<!-- spring end -->
			<!-- apache -->
			<dependency>
				<groupId>org.apache.httpcomponents</groupId>
				<artifactId>httpclient</artifactId>
				<version>4.5</version>
			</dependency>
			<dependency>
				<groupId>org.apache.shiro</groupId>
				<artifactId>shiro-core</artifactId>
				<version>1.2.3</version>
			</dependency>
			<dependency>
				<groupId>org.apache.shiro</groupId>
				<artifactId>shiro-spring</artifactId>
				<version>1.2.3</version>
			</dependency>
			<!-- apache end -->
			<!-- commons -->
			<dependency>
				<groupId>commons-lang</groupId>
				<artifactId>commons-lang</artifactId>
				<version>2.5</version>
			</dependency>
			<dependency>
				<groupId>commons-httpclient</groupId>
				<artifactId>commons-httpclient</artifactId>
				<version>3.1</version>
			</dependency>
			<dependency>
				<groupId>commons-fileupload</groupId>
				<artifactId>commons-fileupload</artifactId>
				<version>1.2.2</version>
			</dependency>
			<dependency>
				<groupId>commons-io</groupId>
				<artifactId>commons-io</artifactId>
				<version>2.4</version>
			</dependency>
			<dependency>
				<groupId>commons-codec</groupId>
				<artifactId>commons-codec</artifactId>
				<version>1.6</version>
			</dependency>
			<dependency>
			    <groupId>org.quartz-scheduler</groupId>
			    <artifactId>quartz</artifactId>
			    <version>2.2.3</version>
			    <exclusions>
			    	<exclusion>
			    		<groupId>c3p0</groupId>
    					<artifactId>c3p0</artifactId>
			    	</exclusion>
			    </exclusions>
			</dependency>
			<dependency>
			    <groupId>dom4j</groupId>
			    <artifactId>dom4j</artifactId>
			    <version>1.6.1</version>
			</dependency>
			<!-- commons end -->
			<!-- json -->
			<dependency>
				<groupId>org.json</groupId>
				<artifactId>json</artifactId>
				<version>20141113</version>
			</dependency>
			<dependency>
				<groupId>com.alibaba</groupId>
				<artifactId>fastjson</artifactId>
				<version>1.2.0</version>
			</dependency>
			<dependency>
				<groupId>net.sf.json-lib</groupId>
				<artifactId>json-lib</artifactId>
				<version>2.4</version>
				<classifier>jdk15</classifier>
			</dependency>
			<!-- json end -->
			<!-- jackson -->
			<dependency>
				<groupId>org.codehaus.jackson</groupId>
				<artifactId>jackson-core-asl</artifactId>
				<version>1.9.9</version>
			</dependency>
			<dependency>
				<groupId>org.codehaus.jackson</groupId>
				<artifactId>jackson-mapper-asl</artifactId>
				<version>1.9.9</version>
			</dependency>
			<dependency>
				<groupId>com.fasterxml.jackson.core</groupId>
				<artifactId>jackson-core</artifactId>
				<version>2.6.1</version>
			</dependency>
			<dependency>
				<groupId>com.fasterxml.jackson.core</groupId>
				<artifactId>jackson-databind</artifactId>
				<version>2.6.1</version>
			</dependency>
			<dependency>
				<groupId>org.codehaus.jackson</groupId>
				<artifactId>jackson-jaxrs</artifactId>
				<version>1.9.9</version>
			</dependency>
			<dependency>
				<groupId>com.fasterxml.jackson.core</groupId>
				<artifactId>jackson-annotations</artifactId>
				<version>2.6.1</version>
			</dependency>
			<!-- jackson end -->
			<!-- google -->
			<dependency>
				<groupId>com.google.code.gson</groupId>
				<artifactId>gson</artifactId>
				<version>2.3</version>
			</dependency>
			<dependency>
				<groupId>com.google.guava</groupId>
				<artifactId>guava</artifactId>
				<version>19.0</version>
			</dependency>
			<!-- google end -->
			<!-- servlet -->
			<dependency>
				<groupId>javax.servlet</groupId>
				<artifactId>servlet-api</artifactId>
				<version>2.5</version>
				<scope>provided</scope>
			</dependency>
			<!-- servlet end -->
			<!-- 4j -->
			<dependency>
				<groupId>log4j</groupId>
				<artifactId>log4j</artifactId>
				<version>1.2.17</version>
			</dependency>
			<dependency>
				<groupId>org.slf4j</groupId>
				<artifactId>slf4j-api</artifactId>
				<version>1.7.12</version>
			</dependency>
			<dependency>
				<groupId>org.slf4j</groupId>
				<artifactId>slf4j-log4j12</artifactId>
				<version>1.7.12</version>
			</dependency>
			<dependency>
				<groupId>dom4j</groupId>
				<artifactId>dom4j</artifactId>
				<version>1.6.1</version>
			</dependency>
			<dependency>
				<groupId>org.jdom</groupId>
				<artifactId>jdom2</artifactId>
				<version>2.0.6</version>
			</dependency>
			<!-- 4j end -->
			<!-- mail -->
			<dependency>
				<groupId>javax.mail</groupId>
				<artifactId>mail</artifactId>
				<version>1.4</version>
			</dependency>
			<!-- mail end -->
			<!-- postgresql -->
			<dependency>
				<groupId>org.postgresql</groupId>
				<artifactId>postgresql</artifactId>
				<version>9.4-1202-jdbc42</version>
			</dependency>
			<dependency>
				<groupId>org.postgis</groupId>
				<artifactId>postgis-jdbc</artifactId>
				<version>1.3.3</version>
				<exclusions>
					<exclusion>
						<groupId>postgresql</groupId>
						<artifactId>postgresql</artifactId>
					</exclusion>
				</exclusions>
			</dependency>
			<!-- postgresql end -->
			<!-- mchange -->
			<dependency>
				<groupId>com.mchange</groupId>
				<artifactId>c3p0</artifactId>
				<version>0.9.5.2</version>
			</dependency>
			<!-- mchange end -->
			<!-- aspectj -->
			<dependency>
				<groupId>org.aspectj</groupId>
				<artifactId>aspectjrt</artifactId>
				<version>1.8.6</version>
			</dependency>
			<dependency>
				<groupId>org.aspectj</groupId>
				<artifactId>aspectjweaver</artifactId>
				<version>1.8.6</version>
			</dependency>
			<!-- aspectj end -->
			<!-- other -->
			<dependency>
				<groupId>org.jsoup</groupId>
				<artifactId>jsoup</artifactId>
				<version>1.8.3</version>
			</dependency>
			<dependency>
				<groupId>cn.jpush.api</groupId>
				<artifactId>jpush-client</artifactId>
				<version>3.2.6</version>
			</dependency>
			<dependency>
				<groupId>junit</groupId>
				<artifactId>junit</artifactId>
				<version>4.12</version>
			</dependency>
			<dependency>
				<groupId>jaxen</groupId>
				<artifactId>jaxen</artifactId>
				<version>1.1.6</version>
			</dependency>
			<dependency>
				<groupId>com.thoughtworks.xstream</groupId>
				<artifactId>xstream</artifactId>
				<version>1.4.7</version>
			</dependency>
			<dependency>
				<groupId>jstl</groupId>
				<artifactId>jstl</artifactId>
				<version>1.1.2</version>
			</dependency>
		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
		</dependency>
			<dependency>
				<groupId>redis.clients</groupId>
				<artifactId>jedis</artifactId>
				<version>2.8.1</version>
			</dependency>
			<!-- other -->
		 <dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.9</version>
		</dependency>
		 <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-excelant</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
		    <groupId>org.apache.poi</groupId>
		    <artifactId>poi-scratchpad</artifactId>
		    <version>3.9</version>
		</dependency>
		<dependency>
		    <groupId>org.springframework.data</groupId>
		    <artifactId>spring-data-mongodb</artifactId>
		    <version>1.7.1.RELEASE</version>
		</dependency>
		<dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.2.2</version>
        </dependency>
		</dependencies>
有些包是以後要用的 ,目前並沒有全用 ,主要的就是這兩個
		<dependency>
		    <groupId>org.springframework.data</groupId>
		    <artifactId>spring-data-mongodb</artifactId>
		    <version>1.7.1.RELEASE</version>
		</dependency>
		<dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.2.2</version>
        </dependency>

後面缺啥補啥

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	version="3.0">
	<display-name>Spring Web MVC Application</display-name>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
		classpath*:/applicationContext.xml,
		classpath*:/applicationContext-log4j.xml
	</param-value>
	</context-param>
	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>classpath:log4j.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>
	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/springmvc-servlet.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
    <filter>  
        <filter-name>shiroFilter</filter-name>  
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
        <init-param>  
            <param-name>targetFilterLifecycle</param-name>  
            <param-value>true</param-value>  
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>shiroFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping> 
    
	<filter>
		<filter-name>encoding</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

applicationContext.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:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:mongo="http://www.springframework.org/schema/data/mongo"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop.xsd  
    	http://www.springframework.org/schema/tx 
    	http://www.springframework.org/schema/tx/spring-tx.xsd  
    	http://www.springframework.org/schema/util 
    	http://www.springframework.org/schema/util/spring-util.xsd  
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
    	http://www.springframework.org/schema/data/mongo 
    	http://www.springframework.org/schema/data/mongo/spring-mongo.xsd  
    	http://www.springframework.org/schema/context 
    	http://www.springframework.org/schema/context/spring-context.xsd">
	<context:component-scan base-package="com.xueyou" />
	
	<!--開啟註解 -->
	<context:annotation-config />

	<!-- 開啟自動切面代理 -->
	<aop:aspectj-autoproxy />
	<mvc:annotation-driven>
		<mvc:message-converters>
			<bean id="messageConverter"
				class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
				<property name="objectMapper" ref="myObjectMapper">
				</property>
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>
	<!-- 獲取配置資源 -->
	<context:property-placeholder location="classpath:config.properties" ignore-unresolvable="true"/>
<!-- 
	<bean class="cn.mongo.util.SpringContextUtil"></bean> -->

	<mongo:mongo-client id="mongo" replica-set="${db.mongo.replicaSet}">
		<!-- connections-per-host: 每個主機答應的連線數(每個主機的連線池大小),當連線池被用光時,會被阻塞住 max-wait-time: 
			被阻塞執行緒從連線池獲取連線的最長等待時間(ms) connect-timeout:在建立(開啟)套接字連線時的超時時間(ms) socket-timeout:套接字超時時間;該值會被傳遞給Socket.setSoTimeout(int) 
			slave-ok:指明是否答應驅動從次要節點或者奴隸節點讀取資料 -->
			
		<mongo:client-options 
                connections-per-host="${db.mongo.connectionsPerHost}"
                min-connections-per-host="${db.mongo.minConnectionsPerHost}"
                threads-allowed-to-block-for-connection-multiplier="${db.mongo.threadsAllowedToBlockForConnectionMultiplier}"
                connect-timeout="${db.mongo.connectTimeout}"
                max-wait-time="${db.mongo.maxWaitTime}"
                socket-keep-alive="${db.mongo.socketKeepAlive}"
                socket-timeout="${db.mongo.socketTimeout}"
                max-connection-idle-time="${db.mongo.maxConnectionIdleTime}"
                max-connection-life-time="${db.mongo.maxConnectionLifeTime}"
                heartbeat-socket-timeout="${db.mongo.heartbeatSocketTimeout}"
                heartbeat-connect-timeout="${db.mongo.heartbeatConnectTimeout}"
                min-heartbeat-frequency="${db.mongo.minHeartbeatFrequency}"
                heartbeat-frequency="${db.mongo.heartbeatFrequency}"/>
	</mongo:mongo-client>
	<!-- 設定使用的資料庫 名 -->
	<mongo:db-factory id="mongoDbFactory" dbname="${db.mongo.dbname}" mongo-ref="mongo" />
	<!-- mongodb的模板 -->
	<mongo:template id="mongoTemplate" db-factory-ref="mongoDbFactory" write-concern="NORMAL"/>
	
    <!-- MongoDB GridFS Template 支援,操作mongodb存放的檔案 -->
   <!--  <mongo:mapping-converter id="converter" db-factory-ref="mongoDbFactory"
            base-package="com.xueyou.impl"/>
    <mongo:gridFsTemplate id="gridFsTemplcate" db-factory-ref="mongoDbFactory" converter-ref="converter" /> -->
</beans> 
springmvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	<mvc:resources location="/fonts/" mapping="/fonts/**" />
	<mvc:resources location="/images/" mapping="/images/**" />
	<mvc:resources location="/plugins/" mapping="/plugins/**" />
	<mvc:resources location="/javascripts/" mapping="/javascripts/**" />
	<mvc:resources location="/stylesheets/" mapping="/stylesheets/**" />
	
	<!-- <context:component-scan base-package="com.xueyou">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
	</context:component-scan> -->
	
	<default-servlet-handler />
	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/jsp/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	<beans:bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
		<beans:property name="defaultEncoding" value="UTF-8"></beans:property>
		<beans:property name="maxUploadSize" value="1048576000"></beans:property>
		<beans:property name="maxInMemorySize" value="1024000"></beans:property>
		<beans:property name="resolveLazily" value="true"></beans:property>
	</beans:bean>

</beans:beans>

config.properties
#mongodb  single,單個伺服器用
db.mongo.host=
db.mongo.port=

#mongo的資料庫名 登入名 密碼
db.mongo.dbname=
db.mongo.username=
db.mongo.password=

#replica ,部署伺服器叢集 例如 db.mongo.replicaSet=127.0.0.1:27017,127.0.0.1:27017,127.0.0.1:27017
db.mongo.replicaSet=

db.mongo.connectionsPerHost=50
db.mongo.threadsAllowedToBlockForConnectionMultiplier=50
db.mongo.minConnectionsPerHost=5
#\u8FDE\u63A5\u8D85\u65F6\u65F6\u95F4
db.mongo.connectTimeout=10000
#\u7B49\u5F85\u65F6\u95F4
db.mongo.maxWaitTime=120000
#Socket\u8D85\u65F6\u65F6\u95F4
db.mongo.socketTimeout=0
db.mongo.socketKeepAlive=true

db.mongo.maxConnectionIdleTime=1500
db.mongo.maxConnectionLifeTime=0
#mongo slave
db.mongo.heartbeatSocketTimeout=1000
db.mongo.heartbeatConnectTimeout=1500
db.mongo.minHeartbeatFrequency=5
db.mongo.heartbeatFrequency=10


像是 日誌什麼的我就不貼了

MyObjectMapper.java

@Component
public class MyObjectMapper extends ObjectMapper {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public MyObjectMapper() {
		super();
		this.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
		this.setTimeZone(TimeZone.getDefault());
		// this.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
	}
}

controller
@Controller
@RequestMapping("/")
public class MongoTest{
	
	@Autowired
	private TestInsert testInsertImpl;
	
	@RequestMapping("/testInsert")
	public String testInsert(Model model){
		DBObject obj = new BasicDBObject();
		obj.put("name", "張三");
		String id = testInsertImpl.insertOne(obj);
		model.addAttribute("id", id);
		return "other";
	}
}
service
public interface TestInsert {

	String insertOne(DBObject obj);
}

impl
@Service
public class TestInsertImpl extends MongoTemplateInjection implements TestInsert {

	//插入單個文件
	@Override
	public String insertOne(DBObject obj) {
		// TODO Auto-generated method stub
		mongoTemplate.getCollection("testadd").insert(obj);
		return obj.get("_id").toString();
	}

}
MongoTemplateInjection.java
public class MongoTemplateInjection {
	
	@Autowired
	public MongoTemplate mongoTemplate; 		/* mongodb模板*/
}

執行結果