spring配置mongodb连接副本集多个节点

来源:互联网 发布:java员工管理系统简历 编辑:程序博客网 时间:2024/06/04 18:56

mongodb版本3.4.x


1、配置副本集

先配置副本集,可参考我之前写的文章:http://blog.csdn.net/fuck487/article/details/78287362

注意:必须配置仲裁节点,本来我以为仲裁节点作用不大,后来发现如果没配置仲裁节点,即使代码配置了多节点连接,一旦主节点关闭了,程序不会正常切到备用节点。

后来又验证了下:

要么1个主节点,1个从节点,1个仲裁

要么1个主节点,2个从节点

就是共大于等于3个节点,主节点关闭了,子节点

才能正常切换


2、spring配置(带密码的)

<?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:p="http://www.springframework.org/schema/p"       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-4.3.xsd            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd              http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd             http://www.springframework.org/schema/data/repository http://www.springframework.org/schema/data/repository/spring-repository-1.5.xsd">           <!-- mongodb 版本3.4.7 --><!--mongodb credentials的配置形式是:用户名:密码@默认数据库  --><!-- <mongo:mongo-client id="mongoClient" host="${db.host}" port="${db.port}" credentials="${db.user}:${db.pwd}@${db.name}"></mongo:mongo-client> -->        <!-- replica-set 副本集连接 -->    <!-- replica-set格式:ip1:port,ip2:port --><mongo:mongo-client id="mongoClient" replica-set="${db.replica-set}" credentials="${db.user}:${db.pwd}@${db.name}"><mongo:client-options                connections-per-host="100"        /></mongo:mongo-client><mongo:db-factory id="mongoDbFactory" dbname="${db.name}" mongo-ref="mongoClient"/>            <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">        <constructor-arg ref="mongoDbFactory" />    </bean>      </beans>


其中主要是通过 replica-set="${db.replica-set}"来配置副本集

 replica-set的格式为ip1:port1,ip2:port2

只需要添加主从节点,不需要添加仲裁节点


3、属性文件

#mongodb-configdb.port=40000db.host=127.0.0.1db.user=devdb.pwd=123456db.name=isdbdb.replica-set=127.0.0.1:40000,127.0.0.1:40001




原创粉丝点击