mongodb超时配置
springboot.version=2.3.5.RELEASEspring-cloud-dependencies.version=Hoxton.SR9xml中引入<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mo
·
springboot.version=2.3.5.RELEASE
spring-cloud-dependencies.version=Hoxton.SR9
xml中引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
yml中引入
spring:
data:
mongodb:
uri: mongodb://192.168.1.93:27017/rongtong_goods
readTimeout: 0
connectTimeout: 10000
集群或者用户配置如下
##mongodb://user:pwd@ip1:port1,ip2:port2/database?replicaSet=myReplicaSet
新建配置类和启动setting配置
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Data
@ConfigurationProperties(prefix = "spring.data.mongodb")
public class MongoSettingProperties {
private Integer readTimeout;
private Integer connectTimeout;
}
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import java.util.concurrent.TimeUnit;
@Configuration
@EnableConfigurationProperties(MongoSettingProperties.class)
@ConditionalOnClass(MongoClient.class)
@AutoConfigureBefore(MongoAutoConfiguration.class)
public class MongoDbAutoConfiguration {
@Bean
@Order(0)
public MongoClientSettings mongoClientSettings(MongoSettingProperties setting) {
return MongoClientSettings.builder()
.applyToSocketSettings(i ->
i.readTimeout(setting.getReadTimeout(), TimeUnit.MILLISECONDS)
.connectTimeout(setting.getConnectTimeout(), TimeUnit.MILLISECONDS)
).build();
}
}
如果想禁用mongo或Mq自动加载添加
@SpringBootApplication(exclude = {RabbitAutoConfiguration.class, MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
之后自己配置启动
@Bean
public MongoTemplate mongoOptions() {
return new MongoTemplate(createMongoDBClient(), "数据库db名称");
}
public MongoClient createMongoDBClient(){
return MongoClients.create(
MongoClientSettings.builder()
.applyToConnectionPoolSettings(i ->
i.minSize(minSize)
.maxSize(maxSize))
.applyConnectionString(new ConnectionString("上面入住的uri"))
.applyToSocketSettings(i ->
i.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
.readTimeout(socketTimeout, TimeUnit.MILLISECONDS)
)
.build()
);
}
更多推荐
已为社区贡献1条内容
所有评论(0)