Spring整合MongoDB3.0開發

1、Maven依賴

    (需要注意的是,按照MongoDB官方的說法,mongDB3.0的JAVA驅動至少得選擇2.13以上版本,下面是以spring-data-mongodb的1.6.2.RELEASE作爲依賴,必須要exclusion排除mongo-java-driver,spring-data-mongodb該版本的mongoDB java 驅動不能正確的運行在MongoDB3.0上):

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>org.springframework.core</artifactId>
	<version>${springframwork.croe.version}</version>
</dependency>
<dependency>
	<groupId>org.springframework.data</groupId>
	<artifactId>spring-data-mongodb</artifactId>
	<version>1.6.2.RELEASE</version>
	<!-- MongoDB3.0驅動需要單獨配置 -->
	<exclusions>
		<exclusion>
			<groupId>org.mongodb</groupId>
			<artifactId>mongo-java-driver</artifactId>
		</exclusion>
	</exclusions>
</dependency>
<dependency>
	<groupId>org.mongodb</groupId>
	<artifactId>mongo-java-driver</artifactId>
	<version>2.13.0-rc2</version>
</dependency>

 

2、mongodb.properties,文件放置到conf/mongo目錄下

im.hs.server.mongo.replicaSet=192.168.62.154:17018,192.168.62.153:17018,192.168.62.152:17018
im.hs.server.mongo.dbName=hezx
im.hs.server.mongo.username=admin
im.hs.server.mongo.password=admin123

 

3、spring-mongo.xml,文件放置到conf/mongo目錄下

<?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:ss="http://www.springframework.org/schema/security"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	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/jee http://www.springframework.org/schema/jee/spring-jee.xsd
	http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context.xsd
	http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
	http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.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">

    <!-- Spring自動將該包目錄下標記爲@Service的所有類作爲spring的Bean -->
	<context:component-scan base-package="com.gaojiasoft.test.mongo.service" />

	<!-- <aop:aspectj-autoproxy proxy-target-class="true"/> -->

	<bean id="mongodbPropertyConfig"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="order" value="1" />
		<property name="ignoreUnresolvablePlaceholders" value="true" />
		<property name="locations">
			<list>
				<value>classpath:conf/mongo/mongodb.properties</value>
			</list>
		</property>
		<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
	</bean>

	<mongo:mongo id="mongo" replica-set="${im.hs.server.mongo.replicaSet}">
		<mongo:options connections-per-host="400"
			threads-allowed-to-block-for-connection-multiplier="100"
			connect-timeout="10000" max-wait-time="15000" auto-connect-retry="true"
			socket-keep-alive="true" socket-timeout="15000" slave-ok="true"
			write-number="0" write-timeout="0" write-fsync="true" />
	</mongo:mongo>


	<!-- message數據庫連接池配置開始 -->
	<!-- 連接工廠 指定db名 -->
	<mongo:db-factory id="mongoDbFactory" dbname="${im.hs.server.mongo.dbName}"
		mongo-ref="mongo" username="${im.hs.server.mongo.username}" password="${im.hs.server.mongo.password}" />


	<!-- 對象映射成mongodb的一個collection的 -->
	<mongo:mapping-converter id="mongoDbconverter"
		db-factory-ref="mongoDbFactory" />

	<!-- mongodb的操作對象 -->
	<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
		<constructor-arg ref="mongoDbFactory" />
		<constructor-arg ref="mongoDbconverter" />
	</bean>
</beans>


4、Message.java(消息實體Bean,將消息存儲到mongoDB的Message Collection中)

 

package com.gaojiasoft.test.mongo.bean;

import java.io.Serializable;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;


/**
 * 
* @ClassName: Message 
* @Description: 消息實體Bean,從MessagePacket轉換而成,是TCP協議經過JSON解析後的消息實體Bean。
* @author 何志雄 001
* @company 南京高嘉軟件技術有限公司
* @date 2015年3月16日 下午4:48:19
 */
//指定使用mongodb的Message集合,spring操作該對象的時候知道存取哪個集合
@Document(collection = "Message")
public class Message implements Serializable, Comparable<Message> {
    
    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = 1L;
    
    /**
     * 文檔id
     */
    @Id
    private String id;
    

    /**
     * 消息id
     */
    private String messageId;

    /**
     * 發送者id
     */
    private String from;

    /**
     * 接收者id
     */
    private String to;

    /**
     * 發送時間
     */
    private Long sendate;

    /**
     * 消息內容
     */
    private String content;

    /**
     * 消息類型
     */
    private int genre;
    
    /**
     * 發送者暱稱
     */
    private String sender;
    
    /**
     * 序列號
     */
    private Long sequence;
    
    
    /**
     * at列表
     */
    private String remind;
    
    /**
     * header_id
     */
    private String header_id;
    
    /**
     * header_from
     */
    private String header_from;
    
    /**
     * header_to
     */
    private String header_to;
    
    /**
     * header_opCode
     */
    private String header_opCode;
    
    /**
     * version
     */
    private String version;
    
    /**
     * protocol
     */
    private String protocol;
    
    /**
     * body
     */
    private String body;
    
    /**
     * org
     */
    private String org;
    
    /**
     * createTime
     */
    private Long createTime; 
    
    /**
     * 狀態
     */
    private int status;
    
    /**
     * userid,domain,resource
     */
    private String from_fulljid;
    
    private String to_fulljid;
    /**
     * @return the id
     */
    public String getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     * @return the content
     */
    public String getContent() {
        return content;
    }

    /**
     * @param content the content to set
     */
    public void setContent(String content) {
        this.content = content;
    }

    /**
     * @return the messageId
     */
    public String getMessageId() {
        return messageId;
    }

    /**
     * @param messageId the messageId to set
     */
    public void setMessageId(String messageId) {
        this.messageId = messageId;
    }

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public Long getSendate() {
        return sendate;
    }

    public void setSendate(Long sendate) {
        this.sendate = sendate;
    }

    public int getGenre() {
        return genre;
    }

    public void setGenre(int genre) {
        this.genre = genre;
    }

    public String getSender() {
        return sender;
    }

    public void setSender(String sender) {
        this.sender = sender;
    }

    public String getRemind() {
        return remind;
    }

    public void setRemind(String remind) {
        this.remind = remind;
    }

    public String getHeader_id() {
        return header_id;
    }

    public void setHeader_id(String header_id) {
        this.header_id = header_id;
    }

    public String getHeader_from() {
        return header_from;
    }

    public void setHeader_from(String header_from) {
        this.header_from = header_from;
    }

    public String getHeader_to() {
        return header_to;
    }

    public void setHeader_to(String header_to) {
        this.header_to = header_to;
    }

    public String getHeader_opCode() {
        return header_opCode;
    }

    public void setHeader_opCode(String header_opCode) {
        this.header_opCode = header_opCode;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getProtocol() {
        return protocol;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public String getOrg() {
        return org;
    }

    public void setOrg(String org) {
        this.org = org;
    }

    public Long getSequence() {
        return sequence;
    }

    public void setSequence(Long sequence) {
        this.sequence = sequence;
    }

    public Long getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Long createTime) {
        this.createTime = createTime;
    }

    @Override
    public int compareTo(Message o) {
         if (o.sequence < this.sequence)
                return 1;
            else if (o.sequence > this.sequence)
                return -1;
            else
                return 0;
    }
    
    //此處影響性能
    @Override
    public String toString(){
        return this.messageId + "|" + this.from + "|" + this.to + "|"+this.sendate+"|"
                +(this.content!=null?this.content.replaceAll("\n", ""):"")+"|"+this.genre+"|"+this.sender+"|"+this.sequence+"|" 
                + this.header_from+"|"+this.header_opCode+"|" +this.remind+"|"+(this.body!=null?this.body.replaceAll("\n", ""):"");
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getFrom_fulljid() {
        return from_fulljid;
    }

    public void setFrom_fulljid(String from_fulljid) {
        this.from_fulljid = from_fulljid;
    }

    public String getTo_fulljid() {
        return to_fulljid;
    }

    public void setTo_fulljid(String to_fulljid) {
        this.to_fulljid = to_fulljid;
    }

}

 

5、MessageServiceImpl.java(MongDB業務操作Bean)

package com.gaojiasoft.test.mongo.service;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.data.mongodb.core.query.Query;

import com.gaojiasoft.test.mongo.bean.Message;

//聲明作爲Spring的Bean,Bean的名稱是messageService
@Service("messageService")
public class MessageServiceImpl{

	private Logger logger = LoggerFactory.getLogger("MessageServiceImpl");

	@Autowired
	private MongoTemplate mongoTemplate;

	public void messageStore(String json) {

		Message message = new Message();
		// protocol
		message.setProtocol("protocol");
		// version
		message.setVersion("version");
		// header_from
		message.setHeader_from("header/from");
		// Header_to
		message.setHeader_to("header/to");
		// Header_id header/id
		message.setHeader_id("header/id");

		message.setHeader_opCode("opCode");

		message.setFrom_fulljid("fromFullJid");
		// barejid
		message.setFrom("from");
		// body_to
		message.setTo_fulljid("toFullJid");
		// barejid
		message.setTo("toBareID");

		message.setSendate(new Date().getTime());

		message.setMessageId("messageId");

		message.setGenre(1);

		// body_sender
		message.setSender("sender");
		// body_content
		message.setContent("content");
		// body_remind
		message.setRemind("remind");

		// body
		message.setBody("this is chat message");
		// sequence
		message.setSequence(new Date().getTime());
		// org
		message.setOrg("org");
		// createTime
		message.setCreateTime(new Date().getTime());
		// log
		logger.info(message.toString());
		// save
		logger.debug("begin save to mongo!");
		try {
			mongoTemplate.save(message);
			Query query = new Query();
			logger.debug("Message count:"
					+ mongoTemplate.count(query, "Message"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.debug("end save to mongo!");
	}
}


6、MongoTest.java(Junit測試程序,每秒鐘插入1條數據,並查詢集合中的數據數量)

package com.gaojiasoft.test.mongo;

import org.junit.Test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.gaojiasoft.test.mongo.service.MessageServiceImpl;

public class MongoTest {

	private static ConfigurableApplicationContext context;

	MessageServiceImpl service;

	@Test
	public void testSayHello() throws InterruptedException {
		context = new ClassPathXmlApplicationContext(
				"classpath:conf/mongo/spring-mongo.xml");
		service = (MessageServiceImpl) context.getBean("messageService");
		while(true)
		{
			service.messageStore(null);
			Thread.sleep(1000);
		}
	}
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章