spring 将Mongo设置为Sping Boot

ipakzgxi  于 12个月前  发布在  Spring
关注(0)|答案(8)|浏览(150)

我正在使用spring Boot web应用程序,它连接到mongo db,它可以开箱即用。我只使用以下属性:

spring.data.mongodb.host=myHost
spring.data.mongodb.port=27017
spring.data.mongodb.database=myDatabase
spring.data.mongo.repositories.enabled=true
spring.data.mongodb.username=myUser
spring.data.mongodb.password=myPassword

字符串
MongoDB的默认超时是10秒。我想配置超时。我尝试了spring.data.mongodb.socketTimeout=2spring.data.mongodb.connectionTimeout=2
没有一个属性可以工作。我可以在属性中指定一些东西,Spring框架会处理它,或者有人可以通过声明Bean来给予示例。

ua4mk5z4

ua4mk5z41#

要遵循您的主题,这将是最好的回答您的问题。看起来你想在您的application.properties文件中设置超时。
为此:

而不是

spring.data.mongodb.host=myHost
spring.data.mongodb.port=27017
spring.data.mongodb.database=myDatabase

spring.data.mongodb.username=myUser
spring.data.mongodb.password=myPassword

字符串

试试这个

spring.data.mongodb.uri=mongodb://myUser:myPassword@myHost:27017,myHost:27017/myDatabase?serverSelectionTimeoutMS=2000&connectTimeoutMS=2000
spring.data.mongodb.database=myDatabase
spring.data.mongo.repositories.enabled=true


将时间(以毫秒为单位)修改为所需时间。

li9yvcax

li9yvcax2#

这将覆盖Sping Boot 自动配置:

@Configuration
public class MongoDbSettings {

    @Bean
    public MongoClientOptions mongoOptions() {
        return MongoClientOptions.builder().socketTimeout(2000).build();
    }

}

字符串

s2j5cfk0

s2j5cfk03#

对于使用Reactive MongoDb的Spring Data :
我的情况有点不同(我有关闭连接-抛出“Caused by:java.lang.IllegalStateException:state should be:open”)
但是你可以用这个来做你的案子。

应用程序.yml:

spring.data.mongodb:
  host: localhost
  database: myDb
  port: 27017
  username: admin
  password: test

字符串
如果您的实现使用MongoReactiveAutoConfiguration来创建bean,那么您可以使用此bean进行配置:

@Bean
public MongoClientSettings mongoClientSettings() {
    final MongoClientSettings clientSettings = MongoClientSettings.builder()
            .retryWrites(true)
            .applyToConnectionPoolSettings((ConnectionPoolSettings.Builder builder) -> {
                builder.maxSize(300) //connections count
                        .minSize(100)
                        .maxConnectionLifeTime(0, TimeUnit.MILLISECONDS)
                        .maxConnectionIdleTime(0, TimeUnit.MILLISECONDS)
                        .maxWaitTime(5000, TimeUnit.MILLISECONDS)
                        .maxWaitQueueSize(5000);
            })
            .applyToSocketSettings(builder -> {
                builder.connectTimeout(2000, TimeUnit.MILLISECONDS);
            })
            .applicationName("app")
            .build();

    return clientSettings;
}

xhv8bpkk

xhv8bpkk4#

MongoClientOptions是一个具有所需属性的类。

以编程方式如果您已经以编程方式配置了MongoDB,那么下面的代码片段可以帮助您。

DB mongoDb;

MongoClient mongoClient = new MongoClient(new ServerAddress(url, port), 
                            MongoClientOptions.builder()
                            .socketTimeout(3000)
                            .minHeartbeatFrequency(25)
                            .heartbeatSocketTimeout(3000)
                            .build());
mongoDb = mongoClient.getDB(dbname);

字符串

XML配置-高级

<beans>

  <mongo:mongo host="localhost" port="27017">
    <mongo:options connections-per-host="8"
                   threads-allowed-to-block-for-connection-multiplier="4"
                   connect-timeout="1000"
                   max-wait-time="1500}"
                   auto-connect-retry="true"
                   socket-keep-alive="true"
                   socket-timeout="1500"
                   slave-ok="true"
                   write-number="1"
                   write-timeout="0"
                   write-fsync="true"/>
  </mongo:mongo/>

</beans>


另请参阅此处以获取完整的文档。

ssm49v7z

ssm49v7z5#

这个问题很老了,但对于所有那些有Mongo DB JAVA驱动程序超时问题的人来说:设置maxConnectionIdleTime属性。
Spring Boot 示例:

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.annotation.PreDestroy;
import java.net.UnknownHostException;

@Configuration
@ConditionalOnClass(MongoClient.class)
@EnableConfigurationProperties(MongoProperties.class)
@ConditionalOnMissingBean(type = "org.springframework.data.mongodb.MongoDbFactory")
public class MongoAutoConfiguration {
    @Autowired
    private MongoProperties properties;

    @Autowired(required = false)
    private MongoClientOptions options;

    @Autowired
    private Environment environment;

    private MongoClient mongo;

    @PreDestroy
    public void close() {
        if (this.mongo != null) {
            this.mongo.close();
        }
    }

    @Bean
    @ConditionalOnMissingBean
    public MongoClient mongo() throws UnknownHostException {
        this.options = options.builder().maxConnectionIdleTime(1000 * 60 * 4).build();
        this.mongo = this.properties.createMongoClient(this.options, this.environment);
        return this.mongo;
    }
}

字符串
非常有用的链接:Java DriverJAVA-2535 com.mongodb.MongoSocketWriteException ......

cgyqldqp

cgyqldqp6#

这个问题是专门针对Sping Boot 的。我使用了下面的方法,效果很好,请建议是否有一种方法可以不使用new而使用Spring来配置它。

import java.util.ArrayList;
 import java.util.List;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
 import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
 import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
 import com.mongodb.Mongo;
 import com.mongodb.MongoClient;
 import com.mongodb.MongoClientOptions;
 import com.mongodb.MongoCredential;
 import com.mongodb.ServerAddress;

 @Configuration
 @EnableMongoRepositories("com.myapp.repository")
 public class SpringMongoConfig extends AbstractMongoConfiguration {

@Value("${myapp.mongodb.host}")
private String host;

@Value("${myapp.mongodb.port}")
private int port;

@Value("${myapp.mongodb.database}")
private String mongoDB;

@Value("${myapp.mongodb.userName}")
private String userName;

@Value("${myapp.mongodb.password}")
private String password;

@Value("${myapp.mongodb.socketTimeoutMS}")
private int socketTimeout;

@Value("${myapp.mongodb.connectionTimeoutMS}")
private int connectionTimeout;

@Override
public MongoMappingContext mongoMappingContext() throws ClassNotFoundException {
return super.mongoMappingContext();
}

@Override
@Bean
public Mongo mongo() throws Exception {

List<ServerAddress> servers = new ArrayList<ServerAddress>();
servers.add(new ServerAddress(host, port));

List<MongoCredential> creds = new ArrayList<MongoCredential>();
creds.add(MongoCredential.createCredential(userName, mongoDB, password.toCharArray()));

MongoClientOptions builder = MongoClientOptions.builder().socketTimeout(socketTimeout).connectTimeout(connectionTimeout).build();

return new MongoClient(servers, creds, builder);
}

@Override
protected String getDatabaseName() {
return mongoDB;
}
}

字符串

r7xajy2e

r7xajy2e7#

如果你只想自定义一个或其他MongoClientSettings,而不是返回一个所有设置都已填充的设置,最好使用以下方法:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.mongo.MongoClientSettingsBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
public class MongoDbSettings {

    private static final int CONNECTION_POOL_SIZE = 10;
    private static final int CONNECTION_POOL_MIN_SIZE = 1;
    private static final int CONNECTION_POOL_MAX_IDLE_TIME = 3;
    private static final int CONNECTION_POOL_MAX_WAIT_TIME = 10;
    private static final int CONNECTION_TIMEOUT = 3;

    @Value("${spring.application.name}")
    private String applicationName;

    @Bean
    public MongoClientSettingsBuilderCustomizer mongoClientSettingsBuilderCustomizer() {
        return custom -> custom.applyToSocketSettings(builder ->
                        builder.connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
                                .readTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS))
                .applyToConnectionPoolSettings(builder ->
                        builder.maxSize(CONNECTION_POOL_SIZE)
                                .minSize(CONNECTION_POOL_MIN_SIZE)
                                .maxConnectionIdleTime(CONNECTION_POOL_MAX_IDLE_TIME, TimeUnit.SECONDS)
                                .maxWaitTime(CONNECTION_POOL_MAX_WAIT_TIME, TimeUnit.SECONDS))
                .applyToClusterSettings(builder ->
                        builder.serverSelectionTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS))
                .applicationName(applicationName)
                ;
    }

字符串

r6vfmomb

r6vfmomb8#

我找到了以下文件,其中有一个可能的解决方案。
https://www.programmersought.com/article/1927319190/
其中提到以下内容:

spring.data.mongodb.address=172.16.250.234:27017,172.16.250.239:27017,172.16.250.240:27017
spring.data.mongodb.replica-set=rs0
spring.data.mongodb.database=test
spring.data.mongodb.username=admin
spring.data.mongodb.password=admin

# Configure spring.data.mongodbDB Pool
spring.data.mongodb.min-connections-per-host=10
spring.data.mongodb.max-connections-per-host=100
spring.data.mongodb.threads-allowed-to-block-for-connection-multiplier=5
spring.data.mongodb.server-selection-timeout=30000
spring.data.mongodb.max-wait-time=120000
spring.data.mongodb.max-connection-idel-time=0
spring.data.mongodb.max-connection-life-time=0
spring.data.mongodb.connect-timeout=10000
spring.data.mongodb.socket-timeout=0
spring.data.mongodb.socket-keep-alive=false
spring.data.mongodb.ssl-enabled=false
spring.data.mongodb.ssl-invalid-host-name-allowed=false
spring.data.mongodb.always-use-m-beans=false
spring.data.mongodb.heartbeat-socket-timeout=20000
spring.data.mongodb.heartbeat-connect-timeout=20000
spring.data.mongodb.min-heartbeat-frequency=500
spring.data.mongodb.heartbeat-frequency=10000
spring.data.mongodb.local-threshold=15
spring.data.mongodb.authentication-database=auth_dev

字符串
我现在试着测试它,以确保它是工作,但它至少似乎是可信的。

相关问题