4

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

gradle引入配置:

    //mongodb
    compile 'org.springframework.data:spring-data-mongodb:1.8.0.RELEASE'
    compile 'org.mongodb:mongo-java-driver:3.1.0'

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的配置文件中,找到<bean>标签,加入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-clientcredentials字段中。

下面给出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

配置暂时就说这么多,等有时间了写个demo,实现一个restful接口,效果如下:
图片描述
图1 restful api
图片描述
图2 yii2实现的数据展示


Joyven
630 声望34 粉丝

不学无(用之)术,不安于现状,总想鼓捣点什么,或者总想尝试一些什么新鲜事物。