spring-data-mongodb配置连接池
解决方法:
1.启动类添加bean
@Bean
public MongoDbFactory mongoDbFactory(MongoProperties mongo) throws Exception {
MongoCredential credential = MongoCredential
.createScramSha1Credential(mongo.getUsername(), mongo.getDatabase(), mongo.getPassword());
MongoClientOptions options = MongoClientOptions
.builder()
.minConnectionsPerHost(20)//最小连接数
.connectionsPerHost(200) //最大连接数
.connectTimeout(10000)//超时时间
.threadsAllowedToBlockForConnectionMultiplier(5)//当连接超过connectionsPerHost时,最多(connectionsPerHost*这个值)500个线程等待一个链接,推荐配置为5
.maxConnectionIdleTime(1000*10)// 最大空闲连接时长,不用的连接超过这个时间时回收
.socketTimeout((int) TimeUnit.MINUTES.toMillis(1)) // socket 超时时间
.build();
// MongoDB地址列表
List<ServerAddress> list = new ArrayList<ServerAddress>();
for (String address : mongo.getUri().split(",")) {
String[] hostAndPort = address.split(":");
String host = hostAndPort[0];
Integer port = Integer.parseInt(hostAndPort[1]);
ServerAddress serverAddress = new ServerAddress(host, port);
list.add(serverAddress);
}
MongoClient mongoClient = new MongoClient(list, credential, options);
return new SimpleMongoDbFactory(mongoClient,mongo.getDatabase());
}
2.yml文件配置:
spring:
data:
mongodb:
uri: 144.175.135.110:27017
username: surt
password: 123456
database: ddddd