在SpringBoot中,可以通过引入 spring-boot-starter-data-mongodb 依赖来实现spring-data-mongodb 的自动配置。但是,默认情况下,该依赖并没有提供连接池配置的功能。因此,需要自行重写 MongoDbFactory,实现MongoDB客户端连接的参数配置扩展。
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
配置文件
@Setter
@Getter
@Component
@PropertySource(value = "classpath:application-mongodb.yml")
@ConfigurationProperties(prefix = "spring.data.mongodb")
public class MongoSettingsProperties
{
private List<String> address;
private String replicaSet;
private String database;
private String username;
private String password;
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 socketK