MongoSocketReadException: Exception receiving message 问题解决方案

问题描述

通过系统访问MongoDB数据库,经过一段时间直接再次访问数据时,出现异常报错

019-10-23 10:49:26.796 ERROR 11368 --- [nio-8081-exec-9] c.a.d.m.advice.**  : Exception receiving message; nested exception is com.mongodb.MongoSocketReadException: Exception receiving message
org.springframework.data.mongodb.UncategorizedMongoDbException: Exception receiving message; nested exception is com.mongodb.MongoSocketReadException: Exception receiving message

经查找发现是因为MongDB服务器经过一段时间会把Java保持的连接状态变成close_wait,于是就出现了项目访问数据库报错情况。

解决方案

mongoDB配置

#自动重连 
mongo.autoConnectRetry=true 
#scoket保持活动 
mongo.socketKeepAlive= true 
#scoket超时时间 
mongo.socketTimeout=XX

增强MongoDb设置
在Springboot项目的mongoDB配置中发现没有max-connection-idle-time等相关配置,查找相关资料发现了spring-boot-starter-data-mongodb增强包
1.在使用了spring-boot-starter-data-mongodb的项目中,增加以下依赖

#自动重连 
<dependency>
    <groupId>com.spring4all</groupId>
    <artifactId>mongodb-plus-spring-boot-starter</artifactId>
    <version>1.0.0.RELEASE</version>
</dependency>

2.在应用主类上增加==@EnableMongoPlus==注解,比如:

@EnableMongoPlus
@SpringBootApplication
@ServletComponentScan
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

可用配置参数

spring.data.mongodb.option.min-connection-per-host=0
spring.data.mongodb.option.max-connection-per-host=100
spring.data.mongodb.option.threads-allowed-to-block-for-connection-multiplier=5
spring.data.mongodb.option.server-selection-timeout=30000
spring.data.mongodb.option.max-wait-time=120000
spring.data.mongodb.option.max-connection-idle-time=0
spring.data.mongodb.option.max-connection-life-time=0
spring.data.mongodb.option.connect-timeout=10000
spring.data.mongodb.option.socket-timeout=0

spring.data.mongodb.option.socket-keep-alive=false
spring.data.mongodb.option.ssl-enabled=false
spring.data.mongodb.option.ssl-invalid-host-name-allowed=false
spring.data.mongodb.option.always-use-m-beans=false

spring.data.mongodb.option.heartbeat-socket-timeout=20000
spring.data.mongodb.option.heartbeat-connect-timeout=20000
spring.data.mongodb.option.min-heartbeat-frequency=500
spring.data.mongodb.option.heartbeat-frequency=10000
spring.data.mongodb.option.local-threshold=15

上述配置值均为默认值

你可能感兴趣的:(JAVA学习,MongoDB,Spring,Boot)