Spring+mongodb集群集成(吐血教程) 转自:http://blog.csdn.net/qq_16497617/article/details/52817335

前一篇文章中介绍了在window系统下部署mongodb集群,按照教程一步步实现的话应该都可以在本机部署成功了,上篇文章末尾也提到了,想集成到SSM框架中去,网上资料基本都是单个mongodb数据库的,集群的例子很少,有几个也残缺不全,抽时间研究了一下,最终在SSM框架中成功集成,在文章末尾我会把spring中集成的源代码发一下,SSM框架中集成基本类似,其实主要就是jar包问题,单个mongodb集成实例,这篇文章写得很详细,我也是根据这篇文章改编的。

单个数据库连接:<mongo:mongo host="192.168.1.141" port="27017"/>

集群连接:

[java] view plain copy
  1. <context:property-placeholder location="classpath*:mongodb.properties" />   
  2.          <mongo:mongo id="mongo" replica-set="${mongo.config.replica.set.address}">    
  3.          <mongo:options connections-per-host="100"  
  4.     threads-allowed-to-block-for-connection-multiplier="50"  
  5.     auto-connect-retry="true"/>  
  6.        
  7.     </mongo:mongo>   

集群与单个连接相比只是加了个replice-set属性,但是因为jar包的问题可能导致不支持,


修改这个jar包后会发现各种jar包报错,一个一个改下来,最后如下:


特别要注意的是:jar包不同配置文件中的写法是不一样的,同时,在代码中的增删改查的方法参数的顺序也是不一样的,特别蛋疼。。。。

下面上集群的目录树结构:



首先是MongoTest类,程序入口:


[java] view plain copy
  1. package com.mongo.test;  
  2.   
  3. import java.util.List;  
  4. import org.apache.commons.logging.Log;  
  5. import org.apache.commons.logging.LogFactory;  
  6. import org.springframework.context.ApplicationContext;  
  7. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  8. import com.mongo.bean.Person;  
  9. import com.mongo.dao.AbstractRepository;  
  10. import com.mongo.dao.impl.PersonRepository;  
  11.   
  12. /** 
  13.  * Spring+MongoDB集群集成实例 
  14.  * @author YinGuiChun 
  15.  * @date 20161014 
  16.  */  
  17. public class MongoTest {  
  18.   
  19.     private static Log log = LogFactory.getLog(MongoTest.class.getName());  
  20.       
  21.     private  AbstractRepository pr=null;  
  22.       
  23.     /**初始化*/  
  24.     public void init(){  
  25.          log.debug("开始启动");  
  26.          ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");  
  27.           pr= (PersonRepository)ctx.getBean("personRepository");  
  28.     }  
  29.     /**添加*/  
  30.     public void insert(){  
  31.         for(int i=0;i<5;i++){  
  32.             Person p=new Person("name"+i,i);//插入姓名和年齡  
  33.              pr.insert(p);  
  34.              log.debug("添加成功");  
  35.         }  
  36.           
  37.     }  
  38.     /**刪除一条信息*/  
  39.     public void deleteOne(){  
  40.         String id="57edd4506ab8e4b1f9e99e02";  
  41.         pr.removeOne(id);  
  42.         Person p= pr.findOne(id);  
  43.         log.debug(p);  
  44.     }  
  45.     /**刪除多条信息*/  
  46.     public void removeAll(){  
  47.         pr.removeAll();  
  48.     }  
  49.     /**根据输入的ID查找对象*/  
  50.     public void findOne(){  
  51.         String id="57edd4506ab8e4b1f9e99e01";  
  52.         Person p= pr.findOne(id);  
  53.         log.debug(p);  
  54.     }  
  55.     /**查询所有*/  
  56.     public void listAll(){  
  57.         List<Person> list=pr.findAll();  
  58.         log.debug("查询结果如下:");  
  59.         for (Person p:list){  
  60.             log.debug(p.toString());  
  61.         }  
  62.     }  
  63.       
  64.     public void findAndModify(){  
  65.         String id="57f9f163d12818b23aa3dbf9";  
  66.         Person p= pr.findOne(id);  
  67.         p.setName("upda");  
  68.         pr.insert(p);  
  69.     }  
  70.       
  71.     /**测试方法*/  
  72.     public void start(){  
  73.         init();  
  74. //      insert();//添加数据  
  75. //      deleteOne();//删除单条数据  
  76. //      removeAll();//删除所有数据  
  77. //      findOne();//查询单条数据  
  78.         listAll();//查询所有数据  
  79. //      findAndModify();  
  80.     }  
  81.       
  82.     /**main函数*/  
  83.     public static void main(String[] args) {  
  84.         MongoTest t=new MongoTest();  
  85.         t.start();  
  86.     }  
  87.   
  88. }  

在mongodb环境搭建好之后,程序运行首先运行insert()方法,,插入几条数据,然后用可视化工具连上mongodb库看下是否数据已经插入,在执行listAll(),查询所有方法,看下控制台是否有数据输出,如果能正常输出,就说明你这个集成成功了一半了,关闭一个库试试,数据如果还有的话,那肯定是已经集成成功了。继续上代码:


AbstractRepository.java

[java] view plain copy
  1. package com.mongo.dao;  
  2.   
  3. import java.util.List;  
  4. import com.mongo.bean.Person;  
  5.   
  6. public interface AbstractRepository {  
  7.       
  8.     /** 
  9.      * 添加对象 
  10.      */  
  11.     public void insert(Person person);   
  12.       
  13.     /** 
  14.      *根据ID查找对象 
  15.      */  
  16.     public Person findOne(String id);     
  17.     /** 
  18.      * 查询所有 
  19.      */  
  20.     public List<Person> findAll();     
  21.       
  22.     public List<Person> findByRegex(String regex);  
  23.     /** 
  24.      * 删除指定的ID对象 
  25.      */  
  26.     public void removeOne(String name);     
  27.     /** 
  28.      * 删除所有 
  29.      */  
  30.     public void removeAll();     
  31.     /** 
  32.      * 通过name找到并修改 
  33.      */  
  34.     public void findAndModify(String id);  
  35.   
  36.       
  37.   
  38.       
  39. }  

PersonRepository.java
[java] view plain copy
  1. package com.mongo.dao.impl;  
  2.   
  3. import java.util.List;  
  4. import java.util.regex.Pattern;  
  5. import org.springframework.data.mongodb.core.MongoTemplate;  
  6. import org.springframework.data.mongodb.core.query.Criteria;  
  7. import org.springframework.data.mongodb.core.query.Query;  
  8. import org.springframework.data.mongodb.core.query.Update;  
  9. import com.mongo.bean.Person;  
  10. import com.mongo.dao.AbstractRepository;  
  11.   
  12. public class PersonRepository implements AbstractRepository {  
  13.   
  14.     protected MongoTemplate mongoTemplate;    
  15.   
  16.     public List<Person> findAll() {  
  17.         return getMongoTemplate().find(new Query(), Person.class,"personTest");     
  18.   
  19.     }  
  20.       
  21.     /**修改符合条件的第一条记录*/  
  22.     public void findAndModify(String id) {  
  23.         Query myQuery=new Query(Criteria.where("id").is(id));  
  24.         System.out.println(myQuery.toString());  
  25.         getMongoTemplate().updateFirst(myQuery, Update.update("age"34),"personTest");  
  26.           
  27.     }  
  28.   
  29.     public List<Person> findByRegex(String regex) {  
  30.          Pattern pattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);     
  31.           Criteria criteria = new Criteria("name").regex(pattern.toString());     
  32.             return getMongoTemplate().find(new Query(criteria), Person.class,"personTest");     
  33.   
  34.     }  
  35.   
  36.     public Person findOne(String id) {  
  37.          return getMongoTemplate().findOne(new Query(Criteria.where("id").is(id)), Person.class,"personTest");     
  38.   
  39.     }  
  40.   
  41.     public void insert(Person person) {  
  42.         getMongoTemplate().save( person,"personTest");  
  43.     }  
  44.   
  45.     public void removeAll() {  
  46.         List<Person> list = this.findAll();     
  47.         if(list != null){     
  48.             for(Person person : list){     
  49.                 getMongoTemplate().remove(person);  
  50.             }     
  51.         }     
  52.   
  53.     }  
  54.   
  55.     public void removeOne(String id) {  
  56.         Criteria criteria = Criteria.where("id").in(id);     
  57.         if(criteria != null){     
  58.              Query query = new Query(criteria);     
  59.              if(query != null){  
  60.              getMongoTemplate().remove( query, Person.class,"personTest");  
  61.              }  
  62.         }     
  63.   
  64.     }  
  65.   
  66.     public MongoTemplate getMongoTemplate() {  
  67.         return mongoTemplate;  
  68.     }  
  69.   
  70.     public void setMongoTemplate(MongoTemplate mongoTemplate) {  
  71.         this.mongoTemplate = mongoTemplate;  
  72.     }  
  73.       
  74.   
  75. }  

Person.java
[java] view plain copy
  1. package com.mongo.bean;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. public class Person implements Serializable {  
  6.   
  7.       
  8.     private static final long serialVersionUID = 3617931430808763429L;  
  9.       
  10.     private String id;     
  11.     private String name;     
  12.     private int age;  
  13.     public Person() {  
  14.         super();  
  15.     }  
  16.     public Person(String id, String name, int age) {  
  17.         super();  
  18.         this.id = id;  
  19.         this.name = name;  
  20.         this.age = age;  
  21.     }  
  22.     /** 
  23.      * @return the id 
  24.      */  
  25.     public String getId() {  
  26.         return id;  
  27.     }  
  28.     /** 
  29.      * @param id the id to set 
  30.      */  
  31.     public void setId(String id) {  
  32.         this.id = id;  
  33.     }  
  34.     /** 
  35.      * @return the name 
  36.      */  
  37.     public String getName() {  
  38.         return name;  
  39.     }  
  40.     /** 
  41.      * @param name the name to set 
  42.      */  
  43.     public void setName(String name) {  
  44.         this.name = name;  
  45.     }  
  46.     /** 
  47.      * @return the age 
  48.      */  
  49.     public int getAge() {  
  50.         return age;  
  51.     }  
  52.     /** 
  53.      * @param age the age to set 
  54.      */  
  55.     public void setAge(int age) {  
  56.         this.age = age;  
  57.     }  
  58.     /** 
  59.      *  
  60.      * @param name 
  61.      * @param age 
  62.      */  
  63.     public Person(String name, int age) {  
  64.         super();  
  65.         this.name = name;  
  66.         this.age = age;  
  67.     }     
  68.   
  69.      public String toString() {     
  70.             return "Person[id="+id+",name="+name+",age="+age+"]";     
  71.         }     
  72.   
  73.   
  74. }  

applicationContext.xml
[java] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"    
  3.           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
  4.           xmlns:context="http://www.springframework.org/schema/context"    
  5.           xmlns:mongo="http://www.springframework.org/schema/data/mongo"    
  6.           xsi:schemaLocation="http://www.springframework.org/schema/context     
  7.           http://www.springframework.org/schema/context/spring-context-3.0.xsd     
  8.           http://www.springframework.org/schema/data/mongo     
  9.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd     
  10.           http://www.springframework.org/schema/beans     
  11.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">   
  12.             
  13.     <context:property-placeholder location="classpath*:mongodb.properties" />   
  14.          <mongo:mongo id="mongo" replica-set="${mongo.config.replica.set.address}">    
  15.          <mongo:options connections-per-host="100"  
  16.     threads-allowed-to-block-for-connection-multiplier="50"  
  17.     auto-connect-retry="true"/>  
  18.        
  19.     </mongo:mongo>    
  20.       
  21.        <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">     
  22.         <constructor-arg ref="mongo"/>     
  23.         <constructor-arg name="databaseName" value="dbTest"/>     
  24.       </bean>     
  25.       
  26.      <bean id="personRepository" class="com.mongo.dao.impl.PersonRepository">     
  27.         <property name="mongoTemplate" ref="mongoTemplate"></property>     
  28.     </bean>     
  29.       
  30.      <context:annotation-config />  
  31.           
  32. </beans>   
  33.       

mongodb.properties
[java] view plain copy
  1. mongo.config.replica.set.address=192.168.1.141:27017,192.168.1.141:27018  
  2. mongo.config.replica.set.name=testrs  
  3. mongo.config.database=dbTest  

testrs是上一篇中集群给每个服务器添加的自定义标示,有的配置文件中会用到,我这里没用到

dbTest是我的数据库名,也是没用到,我这个配置文件只是一个简化版的,很多参数都省略了, 实际上只需要一个地址就行,单机和集群配置文件的区别就是这个


用到的所有jar包,在http://mvnrepository.com都可以下载到:

commons-beanutils-1.8.3.jar
commons-codec-1.3.jar
commons-collections-3.2.1.jar
commons-io-1.3.2.jar
commons-lang-2.5.jar
commons-logging.jar
commons-pool-1.4.jar
log4j-1.2.14.jar
mongo-java-driver-2.14.3.jar
slf4j-api-1.5.6.jar
slf4j-log4j12-1.5.6.jar
spring-aop-4.3.3.RELEASE.jar
spring-asm-3.2.0.M1.jar
spring-aspects-4.3.3.RELEASE.jar
spring-beans-4.3.3.RELEASE.jar
spring-context-4.3.3.RELEASE.jar
spring-context-support-4.3.3.RELEASE.jar
spring-core-4.3.3.RELEASE.jar
spring-data-commons-1.12.4.RELEASE.jar
spring-data-mongodb-1.9.4.RELEASE.jar
spring-data-mongodb-cross-store-1.9.4.RELEASE.jar
spring-data-mongodb-log4j-1.0.0.M2.jar
spring-expression-4.3.3.RELEASE.jar
spring-jdbc-4.3.3.RELEASE.jar
spring-tx-4.3.3.RELEASE.jar


最后附上两套源码下载地址:

两套源码下载地址

希望大家都能集成成功,技术交流群:148797838

关注公众号不定期发送各种源码、架构福利
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值