前一篇文章中介绍了在window系统下部署mongodb集群,按照教程一步步实现的话应该都可以在本机部署成功了,上篇文章末尾也提到了,想集成到SSM框架中去,网上资料基本都是单个mongodb数据库的,集群的例子很少,有几个也残缺不全,抽时间研究了一下,最终在SSM框架中成功集成,在文章末尾我会把spring中集成的源代码发一下,SSM框架中集成基本类似,其实主要就是jar包问题,单个mongodb集成实例,这篇文章写得很详细,我也是根据这篇文章改编的。
单个数据库连接:<mongo:mongo host="192.168.1.141" port="27017"/>
集群连接:
- <context:property-placeholder location="classpath*:mongodb.properties" />
- <mongo:mongo id="mongo" replica-set="${mongo.config.replica.set.address}">
- <mongo:options connections-per-host="100"
- threads-allowed-to-block-for-connection-multiplier="50"
- auto-connect-retry="true"/>
- </mongo:mongo>
集群与单个连接相比只是加了个replice-set属性,但是因为jar包的问题可能导致不支持,
修改这个jar包后会发现各种jar包报错,一个一个改下来,最后如下:
特别要注意的是:jar包不同配置文件中的写法是不一样的,同时,在代码中的增删改查的方法参数的顺序也是不一样的,特别蛋疼。。。。
下面上集群的目录树结构:
首先是MongoTest类,程序入口:
- package com.mongo.test;
- import java.util.List;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import com.mongo.bean.Person;
- import com.mongo.dao.AbstractRepository;
- import com.mongo.dao.impl.PersonRepository;
- /**
- * Spring+MongoDB集群集成实例
- * @author YinGuiChun
- * @date 20161014
- */
- public class MongoTest {
- private static Log log = LogFactory.getLog(MongoTest.class.getName());
- private AbstractRepository pr=null;
- /**初始化*/
- public void init(){
- log.debug("开始启动");
- ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
- pr= (PersonRepository)ctx.getBean("personRepository");
- }
- /**添加*/
- public void insert(){
- for(int i=0;i<5;i++){
- Person p=new Person("name"+i,i);//插入姓名和年齡
- pr.insert(p);
- log.debug("添加成功");
- }
- }
- /**刪除一条信息*/
- public void deleteOne(){
- String id="57edd4506ab8e4b1f9e99e02";
- pr.removeOne(id);
- Person p= pr.findOne(id);
- log.debug(p);
- }
- /**刪除多条信息*/
- public void removeAll(){
- pr.removeAll();
- }
- /**根据输入的ID查找对象*/
- public void findOne(){
- String id="57edd4506ab8e4b1f9e99e01";
- Person p= pr.findOne(id);
- log.debug(p);
- }
- /**查询所有*/
- public void listAll(){
- List<Person> list=pr.findAll();
- log.debug("查询结果如下:");
- for (Person p:list){
- log.debug(p.toString());
- }
- }
- public void findAndModify(){
- String id="57f9f163d12818b23aa3dbf9";
- Person p= pr.findOne(id);
- p.setName("upda");
- pr.insert(p);
- }
- /**测试方法*/
- public void start(){
- init();
- // insert();//添加数据
- // deleteOne();//删除单条数据
- // removeAll();//删除所有数据
- // findOne();//查询单条数据
- listAll();//查询所有数据
- // findAndModify();
- }
- /**main函数*/
- public static void main(String[] args) {
- MongoTest t=new MongoTest();
- t.start();
- }
- }
在mongodb环境搭建好之后,程序运行首先运行insert()方法,,插入几条数据,然后用可视化工具连上mongodb库看下是否数据已经插入,在执行listAll(),查询所有方法,看下控制台是否有数据输出,如果能正常输出,就说明你这个集成成功了一半了,关闭一个库试试,数据如果还有的话,那肯定是已经集成成功了。继续上代码:
AbstractRepository.java
- package com.mongo.dao;
- import java.util.List;
- import com.mongo.bean.Person;
- public interface AbstractRepository {
- /**
- * 添加对象
- */
- public void insert(Person person);
- /**
- *根据ID查找对象
- */
- public Person findOne(String id);
- /**
- * 查询所有
- */
- public List<Person> findAll();
- public List<Person> findByRegex(String regex);
- /**
- * 删除指定的ID对象
- */
- public void removeOne(String name);
- /**
- * 删除所有
- */
- public void removeAll();
- /**
- * 通过name找到并修改
- */
- public void findAndModify(String id);
- }
PersonRepository.java
- package com.mongo.dao.impl;
- import java.util.List;
- import java.util.regex.Pattern;
- import org.springframework.data.mongodb.core.MongoTemplate;
- import org.springframework.data.mongodb.core.query.Criteria;
- import org.springframework.data.mongodb.core.query.Query;
- import org.springframework.data.mongodb.core.query.Update;
- import com.mongo.bean.Person;
- import com.mongo.dao.AbstractRepository;
- public class PersonRepository implements AbstractRepository {
- protected MongoTemplate mongoTemplate;
- public List<Person> findAll() {
- return getMongoTemplate().find(new Query(), Person.class,"personTest");
- }
- /**修改符合条件的第一条记录*/
- public void findAndModify(String id) {
- Query myQuery=new Query(Criteria.where("id").is(id));
- System.out.println(myQuery.toString());
- getMongoTemplate().updateFirst(myQuery, Update.update("age", 34),"personTest");
- }
- public List<Person> findByRegex(String regex) {
- Pattern pattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
- Criteria criteria = new Criteria("name").regex(pattern.toString());
- return getMongoTemplate().find(new Query(criteria), Person.class,"personTest");
- }
- public Person findOne(String id) {
- return getMongoTemplate().findOne(new Query(Criteria.where("id").is(id)), Person.class,"personTest");
- }
- public void insert(Person person) {
- getMongoTemplate().save( person,"personTest");
- }
- public void removeAll() {
- List<Person> list = this.findAll();
- if(list != null){
- for(Person person : list){
- getMongoTemplate().remove(person);
- }
- }
- }
- public void removeOne(String id) {
- Criteria criteria = Criteria.where("id").in(id);
- if(criteria != null){
- Query query = new Query(criteria);
- if(query != null){
- getMongoTemplate().remove( query, Person.class,"personTest");
- }
- }
- }
- public MongoTemplate getMongoTemplate() {
- return mongoTemplate;
- }
- public void setMongoTemplate(MongoTemplate mongoTemplate) {
- this.mongoTemplate = mongoTemplate;
- }
- }
Person.java
- package com.mongo.bean;
- import java.io.Serializable;
- public class Person implements Serializable {
- private static final long serialVersionUID = 3617931430808763429L;
- private String id;
- private String name;
- private int age;
- public Person() {
- super();
- }
- public Person(String id, String name, int age) {
- super();
- this.id = id;
- this.name = name;
- this.age = age;
- }
- /**
- * @return the id
- */
- public String getId() {
- return id;
- }
- /**
- * @param id the id to set
- */
- public void setId(String id) {
- this.id = id;
- }
- /**
- * @return the name
- */
- public String getName() {
- return name;
- }
- /**
- * @param name the name to set
- */
- public void setName(String name) {
- this.name = name;
- }
- /**
- * @return the age
- */
- public int getAge() {
- return age;
- }
- /**
- * @param age the age to set
- */
- public void setAge(int age) {
- this.age = age;
- }
- /**
- *
- * @param name
- * @param age
- */
- public Person(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
- public String toString() {
- return "Person[id="+id+",name="+name+",age="+age+"]";
- }
- }
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: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.0.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.0.xsd">
- <context:property-placeholder location="classpath*:mongodb.properties" />
- <mongo:mongo id="mongo" replica-set="${mongo.config.replica.set.address}">
- <mongo:options connections-per-host="100"
- threads-allowed-to-block-for-connection-multiplier="50"
- auto-connect-retry="true"/>
- </mongo:mongo>
- <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
- <constructor-arg ref="mongo"/>
- <constructor-arg name="databaseName" value="dbTest"/>
- </bean>
- <bean id="personRepository" class="com.mongo.dao.impl.PersonRepository">
- <property name="mongoTemplate" ref="mongoTemplate"></property>
- </bean>
- <context:annotation-config />
- </beans>
mongodb.properties
- mongo.config.replica.set.address=192.168.1.141:27017,192.168.1.141:27018
- mongo.config.replica.set.name=testrs
- 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
关注公众号不定期发送各种源码、架构福利