MongoDB( 二 ) MongoDB的连接以及基础配置、连接池配置

7 篇文章 1 订阅

目录

(一) MongoDB的连接

更多连接实例

MongoDB的Java application.yml 写法

普通不设密码Mongo连接方式:

普通设置密码Mongo连接方式

 (二) MongoDB的Java连接配置

将application.yml里有关Mongo的配置映射成JAVA实体类

 配置MongoDBConfig

关于部分mongo低版本配置类提示失效问题

认证客户端

非认证客户端



前面说了mongo的简介以及mongo的数据结构 (MongoDB Java操作教程 ( 一 ) MongoDB 简介) , 这篇说下mongo在Java下的连接以及配置

(一) MongoDB的连接

标准 URI 连接语法:

mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
  • mongodb:// 这是固定的格式,必须要指定。

  • username:password@ 可选项,如果设置,在连接数据库服务器之后,驱动都会尝试登录这个数据库

  • host1 必须的指定至少一个host, host1 是这个URI唯一要填写的。它指定了要连接服务器的地址。如果要连接复制集,请指定多个主机地址。

  • portX 可选的指定端口,如果不填,默认为27017

  • /database 如果指定username:password@,连接并验证登录指定数据库。若不指定,默认打开 test 数据库。

  • ?options 是连接选项。如果不使用/database,则前面需要加上/。所有连接选项都是键值对name=value,键值对之间通过&或;(分号)隔开

标准的连接格式包含了多个选项(options),如下所示:

选项描述
replicaSet=name验证replica set的名称。 Impliesconnect=replicaSet.
slaveOk=true|false
  • true:在connect=direct模式下,驱动会连接第一台机器,即使这台服务器不是主。在connect=replicaSet模式下,驱动会发送所有的写请求到主并且把读取操作分布在其他从服务器。
  • false: 在 connect=direct模式下,驱动会自动找寻主服务器. 在connect=replicaSet 模式下,驱动仅仅连接主服务器,并且所有的读写命令都连接到主服务器。
safe=true|false
    • true: 在执行更新操作之后,驱动都会发送getLastError命令来确保更新成功。(还要参考 wtimeoutMS).
false: 在每次更新之后,驱动不会发送getLastError来确保更新成功。
w=n驱动添加 { w : n } 到getLastError命令. 应用于safe=true。
wtimeoutMS=ms驱动添加 { wtimeout : ms } 到 getlasterror 命令. 应用于 safe=true.
fsync=true|false
  • true: 驱动添加 { fsync : true } 到 getlasterror 命令.应用于 safe=true.
  • false: 驱动不会添加到getLastError命令中。
journal=true|false如果设置为 true, 同步到 journal (在提交到数据库前写入到实体中). 应用于 safe=true
connectTimeoutMS=ms可以打开连接的时间。
socketTimeoutMS=ms发送和接受sockets的时间。

使用用户名和密码连接登录到指定数据库,格式如下:

mongodb://admin:123456@localhost/test

更多连接实例

连接本地数据库服务器,端口是默认的。

mongodb://localhost

使用用户名huang,密码shuaige登录localhost的admin数据库。

mongodb://huang:shuaige@localhost

使用用户名huang,密码shuaige登录localhost的kkk数据库。

mongodb://huang:shuaige@localhost/kkk

连接 replica pair, 服务器1为example1.com服务器2为example2。

mongodb://example1.com:27017,example2.com:27017

连接 replica set 三台服务器 (端口 27017, 27018, 和27019):

mongodb://localhost,localhost:27018,localhost:27019

连接 replica set 三台服务器, 写入操作应用在主服务器 并且分布查询到从服务器。

mongodb://host1,host2,host3/?slaveOk=true

直接连接第一个服务器,无论是replica set一部分或者主服务器或者从服务器。

mongodb://host1,host2,host3/?connect=direct;slaveOk=true

当你的连接服务器有优先级,还需要列出所有服务器,你可以使用上述连接方式。

安全模式连接到localhost:

mongodb://localhost/?safe=true

以安全模式连接到replica set,并且等待至少两个复制服务器成功写入,超时时间设置为2秒。

mongodb://host1,host2,host3/?safe=true;w=2;wtimeoutMS=2000

MongoDB的Java application.yml 写法

普通不设密码Mongo连接方式:

spring:
  data:
    mongodb:
      uri: mongodb://localhost:27017/test

又或者

 

普通设置密码Mongo连接方式

spring:
  data:
    mongodb:
      uri: mongodb://root:123456@localhost:27017/test

又或者 (Mongo连接池配置)

spring:
  data:
    mongodb:
      host: ip地址
      port: 27017
      database: 数据库
      username: 账号
      password: 密码


      # 以下条件并非必须 只是连接池配置参数x 
      option:
        #连接池最小连接数
        min-connection-per-host: 0
        #对mongo实例来说,每个host允许链接的最大链接数,这些链接空闲时会放入池中,如果链接被耗尽,任何请求链接的操作会被阻塞等待链接可用,推荐配置10
        max-connection-per-host: 10
        #线程队列数,此值和连接池的乘积为最大连接数,超出这个数会让请求线程等待
        threads-allowed-to-block-for-connection-multiplier: 5
        #单位为ms,默认0,无限时间,客户端访问服务器的超时时间
        server-selection-timeout: 30000
        #一个线程等待链接可用的最大等待毫秒数,0表示不等待,负数表示等待时间不确定,推荐配置120000
        max-wait-time: 120000
        #线程最大空闲时间,默认0,无限制
        max-connection-idle-time: 60000
        #线程的生命时间
        max-connection-life-time: 0
        #链接超时的毫秒数,0表示不超时,此参数只用在新建一个新链接时,推荐配置10,000
        connect-timeout: 10000
        #客户端连接到数据库后,等待数据返回的最大等待时间,默认为0,无限制
        #此参数表示socket I/O读写超时时间,推荐为不超时,即 0    Socket.setSoTimeout(int)
        socket-timeout: 60000
        
        ## 正常情况下无需以下参数

        #该标志用于控制socket保持活动的功能,通过防火墙保持连接活着
        #keep alive标志,默认false
        socket-keep-alive: true
        #驱动是否使用ssl进行连接,默认是false
        ssl-enabled: false
        #定义是否允许使用无效的主机名
        ssl-invalid-host-name-allowed: false
        #设置由驱动程序注册的JMX bean是否应该始终是mbean,而不管VM是Java 6还是更大
        always-use-m-beans: false
        #集群心跳连接的socket超时时间
        heartbeat-socket-timeout: 20000
        #集群心跳连接的超时时间
        heartbeat-connect-timeout: 20000
        #驱动重新检查服务器状态最少等待时间
        min-heartbeat-frequency: 500
        #驱动用来确保集群中服务器状态的心跳频率
        heartbeat-frequency: 10000
        #设置本地阈值
        local-threshold: 15

 (二) MongoDB的Java连接配置

将application.yml里有关Mongo的配置映射成JAVA实体类

package com.sgcc.eip.cmc.switchs.benchmark.boot.config;


import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

/**
*@Component 将该类交由Spring容器管理
*@ConfigurationProperties prefix 具体映射那些文件前缀路径
*@RefreshScope 是spring cloud提供的一种特殊的scope实现,用来实现配置、实例热加载。
*/
@Component
@ConfigurationProperties(prefix = "spring.data.mongodb")
@RefreshScope
public class MongoDataModelProperties {

    private String host;
    private Integer port;
    private String database;
    private String username;
    // 笔者这里并未将密码字段设置为password  而是采用了secretcode
    private String secretcode;
    private String authenticationDatabase;
/*
    ## 以下参数我这选择省略
    private List<String> address;
    private String replicaSet;
    private Integer minConnectionsPerHost = 0;
    private Integer maxConnectionsPerHost = 100;
    private Integer threadsAllowedToBlockForConnectionMultiplier = 5;
    private Integer serverSelectionTimeout = 30000;
    private Integer maxWaitTime = 120000;
    private Integer maxConnectionIdleTime = 0;
    private Integer maxConnectionLifeTime = 0;
    private Integer connectTimeout = 10000;
    private Integer socketTimeout = 0;
    private Boolean socketKeepAlive = false;
    private Boolean sslEnabled = false;
    private Boolean sslInvalidHostNameAllowed = false;
    private Boolean alwaysUseMBeans = false;
    private Integer heartbeatConnectTimeout = 20000;
    private Integer heartbeatSocketTimeout = 20000;
    private Integer minHeartbeatFrequency = 500;
    private Integer heartbeatFrequency = 10000;
    private Integer localThreshold = 15;*/

    public String getHost() {
        return host;
    }

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

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public String getDatabase() {
        return database;
    }

    public void setDatabase(String database) {
        this.database = database;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getSecretcode() {
        return secretcode;
    }

    public void setSecretcode(String secretcode) {
        this.secretcode = secretcode;
    }

    public String getAuthenticationDatabase() {
        return authenticationDatabase;
    }

    public void setAuthenticationDatabase(String authenticationDatabase) {
        this.authenticationDatabase = authenticationDatabase;
    }
}

 配置MongoDBConfig

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.sgcc.eip.cmc.suite.common.log.Logger;
import com.sgcc.eip.cmc.suite.common.log.LoggerFactory;;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;

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

@Configuration
public class MongoConfiguration {


    @Autowired
    MongoSettingsProperties properties;


    // mongoTemplate 可直接注入并进行一些mongo数据库的增删改查操作
    @Primary
    @Bean(name = "mongoTemplate")
    public MongoTemplate getMongoTemplate() throws Exception {
        return new MongoTemplate(mongoDbFactory(properties));
    }
   

    @Bean
    public MongoDbFactory mongoDbFactory(MongoSettingsProperties properties) {

        // 客户端配置(连接数,副本集群验证)
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();

/*
   以下参数为连接池配置 , 因为笔者注释了  , 所以此处也不做配置(非必须)
builder.connectionsPerHost(properties.getMaxConnectionsPerHost());
        builder.minConnectionsPerHost(properties.getMinConnectionsPerHost());
        if (properties.getReplicaSet() != null) {
            builder.requiredReplicaSetName(properties.getReplicaSet());
        }
        builder.threadsAllowedToBlockForConnectionMultiplier(
                properties.getThreadsAllowedToBlockForConnectionMultiplier());
        builder.serverSelectionTimeout(properties.getServerSelectionTimeout());
        builder.maxWaitTime(properties.getMaxWaitTime());
        builder.maxConnectionIdleTime(properties.getMaxConnectionIdleTime());
        builder.maxConnectionLifeTime(properties.getMaxConnectionLifeTime());
        builder.connectTimeout(properties.getConnectTimeout());
        builder.socketTimeout(properties.getSocketTimeout());
        // builder.socketKeepAlive(properties.getSocketKeepAlive());
        builder.sslEnabled(properties.getSslEnabled());
        builder.sslInvalidHostNameAllowed(properties.getSslInvalidHostNameAllowed());
        builder.alwaysUseMBeans(properties.getAlwaysUseMBeans());
        builder.heartbeatFrequency(properties.getHeartbeatFrequency());
        builder.minHeartbeatFrequency(properties.getMinHeartbeatFrequency());
        builder.heartbeatConnectTimeout(properties.getHeartbeatConnectTimeout());
        builder.heartbeatSocketTimeout(properties.getHeartbeatSocketTimeout());
        builder.localThreshold(properties.getLocalThreshold());*/

        MongoClientOptions mongoClientOptions = builder.build();

        // MongoDB地址列表

        /*List<ServerAddress> serverAddresses = new ArrayList<>();
        for (String address : properties.getAddress()) {
            String[] hostAndPort = address.split(":");
            String host = hostAndPort[0];
            Integer port = Integer.parseInt(hostAndPort[1]);
            ServerAddress serverAddress = new ServerAddress(host, port);
            serverAddresses.add(serverAddress);
        }*/


        String host = properties.getHost();
        Integer port = properties.getPort();
        ServerAddress serverAddress = new ServerAddress(host, port);

        MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(properties.getUsername(),
                properties.getAuthenticationDatabase() != null ? properties.getAuthenticationDatabase() : properties.getDatabase(),
                properties.getSecretcode().toCharArray());

        // 创建非认证客户端
        MongoClient mongoClient = new MongoClient(serverAddress, mongoCredential, mongoClientOptions);

        // 创建MongoDbFactory
        MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, properties.getDatabase());
        return mongoDbFactory;
    }

}

关于部分mongo低版本配置类提示失效问题

com.mongodb.client.MongoClient  代替  com.mongodb.MongoClient
org.springframework.data.mongodb.core.SimpleMongoClientDbFactory 代替  org.springframework.data.mongodb.core.SimpleMongoDbFactory 

随之变动的是创建认证客户端的连接方式 , 可以从上面的 直接 new MongoClient() 更改位如下配置

认证客户端

    @Bean
    public MongoDbFactory mongoDbFactory(MongoProperties properties) {
        String host = properties.getHost();
        Integer port = properties.getPort();
        ServerAddress serverAddress = new ServerAddress(host, port);
        MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(properties.getUsername(),
                properties.getAuthenticationDatabase() != null ? properties.getAuthenticationDatabase() : properties.getDatabase(),
                properties.getSecretcode().toCharArray());
        MongoClient mongoClient = MongoClients.create(MongoClientSettings.builder()
                .applyConnectionString(new ConnectionString("mongodb://" + serverAddress.toString()))
                .credential(mongoCredential).build(),null);
        // 创建MongoDbFactory
        MongoDbFactory mongoDbFactory = new SimpleMongoClientDbFactory(mongoClient, properties.getDatabase());
        return mongoDbFactory;
    }

非认证客户端

    @Bean
    public MongoDbFactory mongoDbFactory(MongoProperties properties) {
        String host = properties.getHost();
        Integer port = properties.getPort();
        ServerAddress serverAddress = new ServerAddress(host, port);
        MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(properties.getUsername(),
                properties.getAuthenticationDatabase() != null ? properties.getAuthenticationDatabase() : properties.getDatabase(),
                properties.getSecretcode().toCharArray());
        // 创建非认证客户端连接
        MongoClient mongoClient = MongoClients.create(MongoClientSettings.builder()
                .applyConnectionString(new ConnectionString("mongodb://" + serverAddress.toString())).build(),null);
        // 或者使用 创建非认证客户端连接
       //  new  MongoClientImpl(MongoClientSettings.builder().build() , null);
        // 创建MongoDbFactory
        MongoDbFactory mongoDbFactory = new SimpleMongoClientDbFactory(mongoClient, properties.getDatabase());
        return mongoDbFactory;
    }

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值