mongodb和spring整合

本文深入分析了使用MongoDB时遇到的问题,包括文档对象转换、时间存储和聚合查询效率,并提供了相应的解决方案。重点介绍了如何通过配置管理器进行有效的MongoDB连接和初始化,确保稳定性和安全性。
mongo使用有一段时间了,感觉有不少坑,以后在使用时还是要权衡搞清楚利弊才好。mongodb中时间的存储、聚合查询的效率等等还是要多注意。
使用mongo首先要面临的是文档对象转换问题,如果是使用spring data mongodb框架的话框架已经给你解决不必担心,但是如果使用原生的mongo各语言版本驱动去开发的话还是要自己去封装。
下面是用java的mongodb驱动去做的。

1.首先使用的包mongo-java-driver-2.7.1.jar和sping

2.编写mongo连接管理类和配置信息基础类

/**
* 
* mongodb 配置
* @author lcq
*
*/
public class MongoConfig {

     private String userName;//用户名  
     private String pwd;//密码  
     private String[] host;//主机地址  
     private int[] port;//端口地址  
     private String dbName;//数据库名  
     private int connectionsPerHost = 20;//每台主机最大连接数  
     private int threadsAllowedToBlockForConnectionMultiplier = 10;//线程队列数  
     private boolean authentication = false;//是否需要身份验证  

     public String getUserName() {
          return userName;
     }

     public void setUserName(String userName) {
          this.userName = userName;
     }

     public String getPwd() {
          return pwd;
     }

     public void setPwd(String pwd) {
          this.pwd = pwd;
     }

     public String[] getHost() {
          return host;
     }

     public void setHost(String[] host) {
          this.host = host;
     }

     public int[] getPort() {
          return port;
     }

     public void setPort(int[] port) {
          this.port = port;
     }

     public String getDbName() {
          return dbName;
     }

     public void setDbName(String dbName) {
          this.dbName = dbName;
     }

     public int getConnectionsPerHost() {
          return connectionsPerHost;
     }

     public void setConnectionsPerHost(int connectionsPerHost) {
          this.connectionsPerHost = connectionsPerHost;
     }

     public int getThreadsAllowedToBlockForConnectionMultiplier() {
          return threadsAllowedToBlockForConnectionMultiplier;
     }

     public void setThreadsAllowedToBlockForConnectionMultiplier(int threadsAllowedToBlockForConnectionMultiplier) {
          this.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier;
     }

     public boolean isAuthentication() {
          return authentication;
     }

     public void setAuthentication(boolean authentication) {
          this.authentication = authentication;
     }
}

import java.util.ArrayList;
import java.util.List;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoOptions;
import com.mongodb.ReadPreference;
import com.mongodb.ServerAddress;

/**
* mongodb 管理器
* @author lcq
*
*/
public class MongoManager {

     private static Mongo mongo;
     private DB db;
     private MongoConfig mongoConfig;

     public MongoConfig getMongoConfig() {
          return this.mongoConfig;
     }

     public void setMongoConfig(MongoConfig mongoConfig) {
          this.mongoConfig = mongoConfig;
     }

     /** 
     * @param dbName 
     * @param userName 
     * @param pwd 
     * 实例化dbName一个DB 
     */
     public void init() {
          if (mongoConfig.getHost() == null || mongoConfig.getHost().length == 0) {
               throw new NumberFormatException("host is null");
          }
          if (mongoConfig.getPort() == null || mongoConfig.getPort().length == 0) {
               throw new NumberFormatException("port is null");
          }
          if (mongoConfig.getHost().length != mongoConfig.getPort().length) {
               throw new NumberFormatException("host's length is not equals port's length");
          }
          try {
               //服务列表  
               List<ServerAddress> replicaSetSeeds = new ArrayList<ServerAddress>();
               for (int i = 0; i < mongoConfig.getHost().length; i++) {
                    replicaSetSeeds.add(new ServerAddress(mongoConfig.getHost()[i], mongoConfig.getPort()[i]));
               }
               //连接池参数设置  
               MongoOptions options = new MongoOptions();
               options.connectionsPerHost = mongoConfig.getConnectionsPerHost();
               options.threadsAllowedToBlockForConnectionMultiplier = mongoConfig.getThreadsAllowedToBlockForConnectionMultiplier();
               mongo = new Mongo(replicaSetSeeds, options);
               //从服务器可读  
               mongo.setReadPreference(ReadPreference.SECONDARY);
          } catch (Exception e) {
               e.printStackTrace();
          }
          db = mongo.getDB(mongoConfig.getDbName());
          if (mongoConfig.isAuthentication() && !db.isAuthenticated()) {
               if (mongoConfig.getUserName() == null || "".equals(mongoConfig.getUserName())) {
                    throw new NumberFormatException("userName is null");
               }
               if (mongoConfig.getPwd() == null || "".equals(mongoConfig.getPwd())) {
                    throw new NumberFormatException("pwd is null");
               }
               db.authenticate(mongoConfig.getUserName(), mongoConfig.getPwd().toCharArray());
          }
     }

     /** 
     * @param tableName 
     * @return 
     *   
     *   
     * @Description: 获取表tableName的链接DBCollection 
     */
     public DBCollection getDBCollection(String tableName) {
          return db.getCollection(tableName);
     }

}

3.配置spring bean

<?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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
    <bean id="mongoConfig" class="com.shangde.common.util.mongodb.MongoConfig">
        <property name="host" value="127.0.0.1"/>
        <property name="port" value="27017"/>
        <property name="dbName" value="test"/>
    </bean>
    <bean id="mongoManager" class="com.shangde.common.util.mongodb.MongoManager" init-method="init">
        <property name="mongoConfig" ref="mongoConfig"/>
    </bean>
</beans>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值