SpringBoot整合MongoDB实现自定义连接池

发布时间: 3年前 (2021-06-22)浏览: 903评论: 0

https://www.it610.com/article/1305666975371923456.htm

  1. 依赖如下

            
                org.springframework.boot
                spring-boot-configuration-processor
                true
            
    
            
                org.springframework.boot
                spring-boot-starter-data-mongodb
            
            
                org.projectlombok
                lombok
                true
            
            
                org.springframework.boot
                spring-boot-starter-test
                test

     

  2. 自定义配置(application.properties) 

    spring.mongodb.address=localhost:27017
    # 设置集群所需副本集名称
    #spring.mongodb.replica-set=rs0
    spring.mongodb.database=demo
    spring.mongodb.username=root
    spring.mongodb.password=abc123
    spring.mongodb.authentication-database=admin
    
    # Configure spring.data.mongodbDB Pool
    # 每个主机的最小连接数
    spring.mongodb.min-connections-per-host=10
    spring.mongodb.max-connections-per-host=100
    # 设置允许阻塞等待连接的线程数
    spring.mongodb.threads-allowed-to-block-for-connection-multiplier=5
    # 设置服务器选择超时:定义客户端在抛出异常之前等待服务器返回成功的时间 (毫秒)
    spring.mongodb.server-selection-timeout=30000
    # 设置线程阻塞等待连接的最大等待时间(毫秒)
    spring.mongodb.max-wait-time=120000
    # 设置连接的最大空闲时间
    spring.mongodb.max-connection-idle-time=0
    # 设置连接的最长成名周期
    spring.mongodb.max-connection-life-time=0
    # 设置连接超时时间(三次握手所需要的时间)
    spring.mongodb.connect-timeout=10000
    # 设置套接字超时时间(等待数据所需要的时间)
    spring.mongodb.socket-timeout=0
    # 设置套接字是否保持长连接
    spring.mongodb.socket-keep-alive=true
    # 是否使用ssl连接
    spring.mongodb.ssl-enabled=false
    # 定义是否使用无效的主机名,默认为false
    spring.mongodb.ssl-invalid-host-name-allowed=false
    # 设置框架是否使用MBeans,jdk5以下使用
    spring.mongodb.always-use-m-beans=false
    # 设置用于集群心跳的连接套接字超时时间
    spring.mongodb.heartbeat-socket-timeout=20000
    # 设置用于集群心跳的连接超时时间
    spring.mongodb.heartbeat-connect-timeout=20000
    # 设置心跳频率,驱动器确定集群中每个服务器当前状态的频率,默认10000(毫秒)
    spring.mongodb.min-heartbeat-frequency=500
    # 设置最小心跳频率,如果驱动器必须要检查服务器服务器的状态,则最少会等待这个时间,默认500(毫秒)
    spring.mongodb.heartbeat-frequency=10000
    # 设置可接受延时差
    spring.mongodb.local-threshold=15

     

  3. 导入自定义配置的实体

    /**
     * @Author: zjh
     * @Date: 2019-08-07
     * @Description: mongodb相关设置属性
     */
    @Component
    @ConfigurationProperties(prefix = "spring.mongodb")
    @Setter
    @Getter
    public class MongoSettingProperties {
        private List address;
        private String replicaSet;
        private String database;
        private String username;
        private String password;
        private String authenticationDatabase;
    
        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;
    }

     

  4. 设置Configuration

    @Configuration
    @EnableConfigurationProperties()
    public class MongoConfig {
    
        @Bean
        public MongoDbFactory mongoDbFactory(MongoSettingProperties properties) {
            //创建MongoDBFactory
            return new SimpleMongoDbFactory(mongoClient(properties), properties.getDatabase());
        }
    
        private MongoClientOptions mongoClientOptions(MongoSettingProperties properties) {
            System.err.println("mongoClientOptions运行一遍");
            //客户端配置(连接数,副本集群验证)
            MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
            builder.connectionsPerHost(properties.getMaxConnectionsPerHost())
                    .minConnectionsPerHost(properties.getMinConnectionsPerHost());
            if (Objects.nonNull(properties.getReplicaSet())) {
                builder.requiredReplicaSetName(properties.getReplicaSet());
            }
            builder.threadsAllowedToBlockForConnectionMultiplier(properties.getThreadsAllowedToBlockForConnectionMultiplier())
                    .serverSelectionTimeout(properties.getServerSelectionTimeout())
                    .maxWaitTime(properties.getMaxWaitTime())
                    .maxConnectionIdleTime(properties.getMaxConnectionIdleTime())
                    .maxConnectionLifeTime(properties.getMaxConnectionLifeTime())
                    .connectTimeout(properties.getConnectTimeout())
                    .socketTimeout(properties.getSocketTimeout())
    //                .socketKeepAlive(properties.getSocketKeepAlive())//已经默认设置为true
                    .sslEnabled(properties.getSslEnabled())
                    .sslInvalidHostNameAllowed(properties.getSslInvalidHostNameAllowed())
                    .alwaysUseMBeans(properties.getAlwaysUseMBeans())
                    .heartbeatFrequency(properties.getHeartbeatFrequency())
                    .minHeartbeatFrequency(properties.getMinHeartbeatFrequency())
                    .heartbeatConnectTimeout(properties.getHeartbeatConnectTimeout())
                    .heartbeatSocketTimeout(properties.getHeartbeatSocketTimeout())
                    .localThreshold(properties.getLocalThreshold());
            return builder.build();
        }
    
        @Bean
        public MongoClient mongoClient(MongoSettingProperties properties) {
            System.err.println("mongoClient运行一遍");
            //配置mongodb地址列表
            List 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);
            }
            System.out.println("获得的地址端口号是:" + serverAddresses.toString());
            MongoClient mongoClient;
    
            if (Objects.nonNull(properties.getUsername())) {
                //创建认证客户端
                MongoCredential scramSha1Credential = MongoCredential.createScramSha1Credential(properties.getUsername()
                        , properties.getAuthenticationDatabase() != null
                                ? properties.getAuthenticationDatabase() : properties.getDatabase(),
                        properties.getPassword().toCharArray());
                mongoClient = new MongoClient(serverAddresses, scramSha1Credential, mongoClientOptions(properties));
            } else {
                //创建非认证客户端
                mongoClient = new MongoClient(serverAddresses, mongoClientOptions(properties));
            }
    
    
            return mongoClient;
        }
    }

       

    之后就可以愉快的使用继续使用MongoDB-data了,


标签:

上一篇: @Scheduled注解各参数详解
下一篇: maven项目打包成WAR包提示:程序包***不存在的解决方案

相关文章暂无相关
评论列表暂无评论
发表评论
验证码

«   2024年4月   »
1234567
891011121314
15161718192021
22232425262728
2930
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
    文章归档
    网站收藏
    友情链接
    • RainbowSoft Studio Z-Blog
    • 订阅本站的 RSS 2.0 新闻聚合
    ︿
    Top