0

springboot2整合mongodb连接池

连接池配置如下:

# 连接池配置
minConnectionsPerHost: 10     #每个host的最小TCP连接数
maxConnectionsPerHost: 100    #每个host的最大TCP连接数
#计算允许多少个线程阻塞等待可用TCP连接时的乘数,算法: threadsAllowedToBlockForConnectionMultiplier*connectionsPerHost,当前配置允许10*20个线程阻塞
threadsAllowedToBlockForConnectionMultiplier: 5
serverSelectionTimeout : 30000    # 为多长时间内找不到合适服务器时候就决定放弃的时间间隔
maxWaitTime: 120000               #应用程序处理线程从连接池中获取Collection,对应的网络等待时间。单位毫秒数,0表示
maxConnectionIdleTime: 0          #线程池中连接的最大空闲时间, 0标志Udine空闲时间没有限制,超过这个时间会被关闭.
maxConnectionLifeTime: 0          #线程池中连接的最长生存时间. 0表示没有限制. 超过寿命的会被关闭,必要时通过新连接进行替换.
connectTimeout: 10000             #每次创建Connection,对应的网络等待。单位毫秒数, 0表示没有限制
socketTimeout: 0                  #MonogoDB Server的Socket通信过程中的网络等待时间。单位毫秒数,默认配置为0,也就是没有限制
socketKeepAlive: false            #socket是否保活
sslEnabled: false
sslInvalidHostNameAllowed: false
alwaysUseMBeans: false
heartbeatConnectTimeout: 20000    #设置用于集群心跳的连接的连接超时
heartbeatSocketTimeout: 20000     #设置用于集群心跳的连接的套接字超时
minHeartbeatFrequency: 500        #设置最小心跳频率。 如果驱动程序必须经常重新检查服务器的可用性,它将至少在上一次检查后等待很长时间,以避免浪费精力。 默认值为500毫秒
heartbeatFrequency: 10000         #设置心跳频率。 这是驱动程序将尝试确定群集中每个服务器的当前状态的频率。 默认值为10,000毫秒
localThreshold: 15                #用于服务器选择的一个参考阈值,单位为毫秒。如果对于某个操作存在多个合适的服务器,则以该选项的值来确定

mongdb配做类:

@Data
@Configuration
@ConfigurationProperties(prefix = "spring.data.mongodb.center")
public class CenterMongoConfiguration {
    // MongoDB Properties

    private ArrayList<String> addresses;
    private String database, username, password;
    private int port;
    @Autowired
    MongoSettingsProperties properties;

    /**
     * 覆盖容器中默认的MongoDbFacotry Bean
     */
    @Bean
    public MongoDbFactory mongoDbFactory() {
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        builder.connectionsPerHost(properties.getMaxConnectionsPerHost());
        builder.minConnectionsPerHost(properties.getMinConnectionsPerHost());
        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<ServerAddress>();
        for (String address : addresses) {
            String[] hostAndPort = address.split(":");
            String host = hostAndPort[0];
            Integer port = Integer.parseInt(hostAndPort[1]);
            ServerAddress serverAddress = new ServerAddress(host, port);
            serverAddresses.add(serverAddress);
        }

        char[] newPassword = EncryptUtils.deStr(password).toCharArray();
        // 连接认证
        MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(username, database, newPassword);
        //创建认证客户端
        MongoClient mongoClient = new MongoClient(serverAddresses, mongoCredential, mongoClientOptions);
        // 创建MongoDbFactory
        MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, database);
        return mongoDbFactory;
    }

    //这是第二个数据库源,不需要注解 @Primary
    @Bean(name = "centerMongoTemplate")
    public MongoTemplate getMongoTemplate(MongoDbFactory mongoDbFactory) throws Exception {
        return new MongoTemplate(mongoDbFactory);
    }

    @Bean
    public MongoCustomConversions mongoCustomConversions() {
        List<Converter<?, ?>> converterList = new ArrayList<>();
        converterList.add(new StringToBigDecimalConverter());
        return new MongoCustomConversions(converterList);
    }

    @Bean(name="mongoTransactionManager")
    public MongoTransactionManager mongoTransactionManager(MongoDbFactory mongoDbFactory) {
        return new MongoTransactionManager(mongoDbFactory);
    }
}

启动服务一开始mongodb在连接池里面都很正常,查询和修改都是正常的,现在停下来一断时间不访问,再次访问页面的时候,查询是没什么问题,但一旦开始插入的时候,报错,且第一次报错后,点击同意的按钮成功了,接下里操作都是成功的,除非等待一段时间后再操作,又会出现上述的问题,报错代码:
2022-12-20 23:39:09.402 [http-nio-9006-exec-9] INFO com.qy.controller.CenterFeignController – ————————–
2022-12-20 23:39:09.406 [http-nio-9006-exec-9] INFO org.mongodb.driver.connection – Closed connection [connectionId{localValue:42, serverValue:458276}] to s-acv121321-pub.mongodb.rds.aliyuncs.com:3717 because there was a socket exception raised by this connection.
2022-12-20 23:39:09.407 [http-nio-9006-exec-9] INFO org.mongodb.driver.connection – Closed connection [connectionId{localValue:38, serverValue:757657}] to s-acv121321-pub.mongodb.rds.aliyuncs.com:3717 because there was a socket exception raised by this connection.
2022-12-20 23:39:09.418 [http-nio-9006-exec-9] INFO com.qy.controller.CenterFeignController – insertUserCustomer exception
{“@type”:”org.springframework.data.mongodb.UncategorizedMongoDbException”,”cause”:{“@type”:”com.mongodb.MongoSocketWriteException”,”cause”:
{“@type”:”java.net.SocketException”,”localizedMessage”:”Connection reset”,”message”:”Connection reset”,
“stackTrace”:[{“className”:”java.net.SocketOutputStream”,”fileName”:”SocketOutputStream.java”,
“lineNumber”:115,”methodName”:”socketWrite”,”nativeMethod”:false},{“className”:”java.net.SocketOutputStream”,”fileName”:
“SocketOutputStream.java”,”lineNumber”:155,”methodName”:”write”,”nativeMethod”:false},
{“className”:”com.mongodb.internal.connection.SocketStream”,”fileName”:”SocketStream.java”,”lineNumber”:99,”methodName”:”write”,”nativeMethod”:false}
,{“className”:”com.mongodb.internal.connection.InternalStreamConnection”,”fileName”:”InternalStreamConnection.java”,”lineNumber”:430,”methodName”:”sendMessage”,”nativeMethod”:false},
{“className”:”com.mongodb.internal.connection.InternalStreamConnection”,”fileName”:”InternalStreamConnection.java”,”lineNumber”:273,”methodName”:”sendCommandMessage”,”nativeMethod”:false},
{“className”:”com.mongodb.internal.connection.InternalStreamConnection”,”fileName”:”InternalStreamConnection.java”,”lineNumber”:257,”methodName”:”sendAndReceive”,”nativeMethod”:false},
{“className”:”com.mongodb.internal.connection.UsageTrackingInternalConnection”,”fileName”:”UsageTrackingInternalConnection.java”,”lineNumber”:99,”methodName”:”sendAndReceive”,”nativeMethod”:false},
{“className”:”com.mongodb.internal.connection.DefaultConnectionPool$PooledConnection”,”fileName”:”DefaultConnectionPool.java”,”lineNumber”:450,”methodName”:”sendAndReceive”,”nativeMethod”:false},
{“className”:”com.mongodb.internal.connection.CommandProtocolImpl”,”fileName”:”CommandProtocolImpl.java”,”lineNumber”:72,”methodName”:”execute”,”nativeMethod”:false},
{“className”:”com.mongodb.internal.connection.DefaultServer$DefaultServerProtocolExecutor”,”fileName”:”DefaultServer.java”,”lineNumber”:218,”methodName”:”execute”,”nativeMethod”:false},
{“className”:”com.mongodb.internal.connection.DefaultServerConnection”,”fileName”:”DefaultServerConnection.java”,”lineNumber”:269,”methodName”:”executeProtocol”,”nativeMethod”:false},
{“className”:”com.mongodb.internal.connection.DefaultServerConnection”,”fileName”:”DefaultServerConnection.java”,”lineNumber”:131,”methodName”:”command”,”nativeMethod”:false},
{“className”:”com.mongodb.operation.MixedBulkWriteOperation”,”fileName”:”MixedBulkWriteOperation.java”,”lineNumber”:435,”methodName”:”executeCommand”,”nativeMethod”:false},
{“className”:”com.mongodb.operation.MixedBulkWriteOperation”,”fileName”:”MixedBulkWriteOperation.java”,”lineNumber”:261,”methodName”:”executeBulkWriteBatch”,”nativeMethod”:false}
,{“className”:”com.mongodb.operation.MixedBulkWriteOperation”,”fileName”:”MixedBulkWriteOperation.java”,”lineNumber”:72,”methodName”:”access$700″,”nativeMethod”:false},
{“className”:”com.mongodb.operation.MixedBulkWriteOperation$1″,”fileName”:”MixedBulkWriteOperation.java”,”lineNumber”:205,”methodName”:”call”,”nativeMethod”:false},
{“className”:”com.mongodb.operation.MixedBulkWriteOperation$1″,”fileName”:”MixedBulkWriteOperation.java”,”lineNumber”:196,”methodName”:”call”,”nativeMethod”:false},
{“className”:”com.mongodb.operation.OperationHelper”,”fileName”:”OperationHelper.java”,”lineNumber”:501,”methodName”:”withReleasableConnection”,”nativeMethod”:false},
{“className”:”com.mongodb.operation.MixedBulkWriteOperation”,”fileName”:”MixedBulkWriteOperation.java”,”lineNumber”:196,”methodName”:”execute”,”nativeMethod”:false},
{“className”:”com.mongodb.operation.MixedBulkWriteOperation”,”fileName”:”MixedBulkWriteOperation.java”,”lineNumber”:71,”methodName”:”execute”,”nativeMethod”:false},
{“className”:”com.mongodb.client.internal.MongoClientDelegate$DelegateOperationExecutor”,”fileName”:”MongoClientDelegate.java”,”lineNumber”:206,”methodName”:”execute”,”nativeMethod”:false},
{“className”:”com.mongodb.client.internal.MongoCollectionImpl”,”fileName”:”MongoCollectionImpl.java”,”lineNumber”:1048,”methodName”:”executeSingleWriteRequest”,”nativeMethod”:false},
{“className”:”com.mongodb.client.internal.MongoCollectionImpl”,”fileName”:”MongoCollectionImpl.java”,”lineNumber”:498,”methodName”:”executeInsertOne”,”nativeMethod”:false},
{“className”:”com.mongodb.client.internal.MongoCollectionImpl”,”fileName”:”MongoCollectionImpl.java”,”lineNumber”:482,”methodName”:”insertOne”,”nativeMethod”:false},
{“className”:”com.mongodb.client.internal.MongoCollectionImpl”,”fileName”:”MongoCollectionImpl.java”,”lineNumber”:476,”methodName”:”insertOne”,”nativeMethod”:false},
{“className”:”org.springframework.data.mongodb.core.MongoTemplate”,”fileName”:”MongoTemplate.java”,”lineNumber”:1500,”methodName”:”lambda$insertDocument$16″,”nativeMethod”:false},
{“className”:”org.springframework.data.mongodb.core.MongoTemplate”,”fileName”:”MongoTemplate.java”,”lineNumber”:585,”methodName”:”execute”,”nativeMethod”:false},
{“className”:”org.springframework.data.mongodb.core.MongoTemplate”,”fileName”:”MongoTemplate.java”,”lineNumber”:1494,”methodName”:”insertDocument”,”nativeMethod”:false},
{“className”:”org.springframework.data.mongodb.core.MongoTemplate”,”fileName”:”MongoTemplate.java”,”lineNumber”:1294,”methodName”:”doInsert”,”nativeMethod”:false},
{“className”:”org.springframework.data.mongodb.core.MongoTemplate”,”fileName”:”MongoTemplate.java”,”lineNumber”:1226,”methodName”:”insert”,”nativeMethod”:false},
{“className”:”org.springframework.data.mongodb.core.MongoTemplate”,”fileName”:”MongoTemplate.java”,”lineNumber”:1211,”methodName”:”insert”,”nativeMethod”:false},
{“className”:”com.qy.service.impl.CenterFeignServiceImpl”,”fileName”:”CenterFeignServiceImpl.java”,”lineNumber”:49,”methodName”:”insertUserCustomer”,”nativeMethod”:false},
{“className”:”com.qy.service.impl.CenterFeignServiceImpl$$FastClassBySpringCGLIB$$d8e4da75″,”fileName”:”<generated>”,”lineNumber”:-1,”methodName”:”invoke”,”nativeMethod”:false},
{“className”:”org.springframework.cglib.proxy.MethodProxy”,”fileName”:”MethodProxy.java”,”lineNumber”:218,”methodName”:”invoke”,”nativeMethod”:false},
{“className”:”org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor”,”fileName”:”CglibAopProxy.java”,”lineNumber”:685,”methodName”:”intercept”,”nativeMethod”:false},
{“className”:”com.qy.service.impl.CenterFeignServiceImpl$$EnhancerBySpringCGLIB$$c56273c1″,”fileName”:”<generated>”,”lineNumber”:-1,”methodName”:”insertUserCustomer”,”nativeMethod”:false},
{“className”:”com.qy.controller.CenterFeignController”,”fileName”:”CenterFeignController.java”,”lineNumber”:40,”methodName”:”insertUserCustomer”,”nativeMethod”:false},
{“className”:”com.qy.controller.CenterFeignController$$FastClassBySpringCGLIB$$b2716f7f”,”fileName”:”<generated>”,”lineNumber”:-1,”methodName”:”invoke”,”nativeMethod”:false},
{“className”:”org.springframework.cglib.proxy.MethodProxy”,”fileName”:”MethodProxy.java”,”lineNumber”:218,”methodName”:”invoke”,”nativeMethod”:false},
{“className”:”org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation”,”fileName”:”CglibAopProxy.java”,”lineNumber”:769,”methodName”:”invokeJoinpoint”,”nativeMethod”:false},
{“className”:”org.springframework.aop.framework.ReflectiveMethodInvocation”,”fileName”:”ReflectiveMethodInvocation.java”,”lineNumber”:163,”methodName”:”proceed”,”nativeMethod”:false},
{“className”:”org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation”,”fileName”:”CglibAopProxy.java”,”lineNumber”:747,”methodName”:”proceed”,”nativeMethod”:false},{“

已回答的问题