spring+mongodb的整合

mongodb介绍

MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。

MongoDB is an open-source, document database designed for ease of development and scaling. The Manual introduces key concepts in MongoDB, presents the query language, and provides operational and administrative considerations and procedures as well as a comprehensive reference section.

引入mongodb的包

使用mongodb提供的java api包是:

org.mongodb:mongo-java-driver

与spring整合,则需要引入另一个包:

org.springframework.data:spring-data-mongodb

maven引入配置–maven仓库:

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.1.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>1.8.0.RELEASE</version>
</dependency>

mongodb配置

在spring的配置文件中,找到标签,加入mongo的xml命名空间:

xmlns:mongo="http://www.springframework.org/schema/data/mongo"

同时在xsi:schemaLocation加入xsd的定义:

http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo.xsd

mongo-client

<mongo:mongo-client id="mongoClient" host="${mongo.host}" port="${mongo.port}">

host是mongodb服务器的地址,默认127.0.0.1;port是mongodb的服务器端口号,默认是27017。如果需要认证,在1.7版本后需要这样写:

<mongo:mongo-client id="mongoClient" host="${mongo.host}" port="${mongo.port}" credentials="${mongo.user}:${mongo.pwd}@${mongo.defaultDbName}">

credentials的配置形式是:用户名:密码@默认数据库。

client-options

<mongo:client-options
    connections-per-host="${mongo.connectionsPerHost}"
    min-connections-per-host="${mongo.minConnectionsPerHost}"
    threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
    connect-timeout="${mongo.connectTimeout}"
    max-wait-time="${mongo.maxWaitTime}"
    socket-keep-alive="${mongo.socketKeepAlive}"
    socket-timeout="${mongo.socketTimeout}"
    description="${mongo.description}"
    max-connection-idle-time="${mongo.maxConnectionIdleTime}"
    max-connection-life-time="${mongo.maxConnectionLifeTime}"
    heartbeat-socket-timeout="${mongo.heartbeatSocketTimeout}"
    heartbeat-connect-timeout="${mongo.heartbeatConnectTimeout}"
    min-heartbeat-frequency="${mongo.minHeartbeatFrequency}"
    heartbeat-frequency="${mongo.heartbeatFrequency}"

/>

1.7版本+不支持mongo,支持mongo-client,options为client-options,如果使用mongo并且使用useCredentials,则会出现Usage of ‘UserCredentials’ with ‘MongoClient’ is no longer supported提示,编译出错。
根据某些教程甚至是官网也能看到下面这种认证配置,但是经测试在1.8的版本中不起任何作用。

credentials="mongodb://${mongo.user}:${mongo.pwd}@${mongo.host}:${mongo.port}/${mongo.defaultDbName}"

mongoDbFactory

<mongo:db-factory id="mongoDbFactory"
                      dbname="${mongo.defaultDbName}"
                      mongo-ref="mongoClient"/>

上面配置中,在1.7以前的版本中,用户的认证可以放在这一部分,但是1.7以后就会包上面useCredentials的错误提示,所以,如果要认证,就需要将用户名和密码等信息放在mongo-client的credentials字段中。

下面给出1.7版本之前的配置:

<mongo:db-factory id="mongoDbFactory"
                      dbname="${mongo.defaultDbName}"
                      host="${mongo.host}"
                      port="${mongo.port}"
                      username="${mongo.user}"
                      password="${mongo.pwd}"
                      mongo-ref="mongoClient"/>

mongoTemplate

mongoTemplate是spring提供的mongodb模板,有两种配置方式。
方式1:

<mongo:template id="mongoTemplate" db-factory-ref="mongoDbFactory" write-concern="NORMAL"/>

方式2:

bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg ref="mongoDbFactory" />
    </bean>

GridFS Template

MongoDB GridFS Template 支持,操作mongodb存放的文件。

<mongo:mapping-converter id="converter" db-factory-ref="mongoDbFactory" base-package="cn.joyven.web.dao"/>
<mongo:gridFsTemplate id="gridFsTemplcate" db-factory-ref="mongoDbFactory" converter-ref="converter" />

扫描MongoRepository
mongodb bean的仓库目录,会自动扫描扩展了MongoRepository接口的接口进行注入。

<mongo:repositories base-package="cn.joyven.web.repository" />

完整的配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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-2.5.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/data/mongo
        http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
    ">


    <context:annotation-config/>

    <context:component-scan base-package="cn.joyven.web.*"/>

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
        <property name="ignoreResourceNotFound" value="true"/>
        <property name="locations">
            <list>
                <!-- 越靠后越有效,取到最后一个有效的未知 -->
                <value>classpath:conf/properties/*.properties</value>
            </list>
        </property>
    </bean>

    <!-- 1.7版本+不支持mongo,支持mongo-client,options为client-options -->
    <!-- Usage of 'UserCredentials' with 'MongoClient' is no longer supported -->
    <!-- 配置mongodb连接池 ,创建mongoClient实例-->
    <!--credentials="mongodb://${mongo.user}:${mongo.pwd}@${mongo.host}:${mongo.port}/${mongo
    .defaultDbName}"为什么不起作用
    如果需要验证,mongo-client需要加这句: credentials="${mongo.user}:${mongo.pwd}@${mongo.defaultDbName}"
    -->
    <mongo:mongo-client id="mongoClient"  host="${mongo.host}" port="${mongo.port}">
        <mongo:client-options
                connections-per-host="${mongo.connectionsPerHost}"
                min-connections-per-host="${mongo.minConnectionsPerHost}"
                threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
                connect-timeout="${mongo.connectTimeout}"
                max-wait-time="${mongo.maxWaitTime}"
                socket-keep-alive="${mongo.socketKeepAlive}"
                socket-timeout="${mongo.socketTimeout}"
                description="${mongo.description}"
                max-connection-idle-time="${mongo.maxConnectionIdleTime}"
                max-connection-life-time="${mongo.maxConnectionLifeTime}"
                heartbeat-socket-timeout="${mongo.heartbeatSocketTimeout}"
                heartbeat-connect-timeout="${mongo.heartbeatConnectTimeout}"
                min-heartbeat-frequency="${mongo.minHeartbeatFrequency}"
                heartbeat-frequency="${mongo.heartbeatFrequency}"

        />
    </mongo:mongo-client>

    <!-- dbname="${mongo.defaultDbName}" host="${mongo.host}"
                      port="${mongo.port}" username="${mongo.user}" password="${mongo.pwd}"
                      mongo-ref="mongoClient" -->
    <mongo:db-factory id="mongoDbFactory"
                      dbname="${mongo.defaultDbName}"
                      mongo-ref="mongoClient"/>

    <!-- 1.Spring提供的mongodb操作模板-->
    <mongo:template id="mongoTemplate" db-factory-ref="mongoDbFactory" write-concern="NORMAL"/>
    <!-- 2.Spring提供的mongodb操作模板-->
    <!--<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg ref="mongoDbFactory" />
    </bean>-->


    <!-- MongoDB GridFS Template 支持,操作mongodb存放的文件 -->
    <mongo:mapping-converter id="converter" db-factory-ref="mongoDbFactory"
                             base-package="cn.idongjia.web.dao"/>
    <mongo:gridFsTemplate id="gridFsTemplcate" db-factory-ref="mongoDbFactory" converter-ref="converter" />

    <!-- mongodb bean的仓库目录,会自动扫描扩展了MongoRepository接口的接口进行注入 -->
    <mongo:repositories base-package="cn.joyven.web.repository" />

    <!--激活注解-->
    <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>

</beans>

注意:这里面的spring的配置并不是完整的,至于你需要加载什么,另行配置。这里保留了bean和content的配置,主要开启注解配置需要content,而bean是spring的最基本的粒度,在spring中一切class皆为bean。

properties配置

mongo.host=127.0.0.1
mongo.port=27017
mongo.defaultDbName=log
mongo.user=joyven
mongo.pwd=123456
mongo.connectionsPerHost=10
mongo.threadsAllowedToBlockForConnectionMultiplier=5
mongo.minConnectionsPerHost=5
#连接超时时间
mongo.connectTimeout=10000
#等待时间
mongo.maxWaitTime=120000
#Socket超时时间
mongo.socketTimeout=0
mongo.socketKeepAlive=true

mongo.description=joyven test mongodb database
mongo.maxConnectionIdleTime=1500
mongo.maxConnectionLifeTime=0
#mongo slave
mongo.heartbeatSocketTimeout=1000
mongo.heartbeatConnectTimeout=1500
mongo.minHeartbeatFrequency=5
mongo.heartbeatFrequency=10

原文地址:https://segmentfault.com/a/1190000005829384

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值