package com.walker.jdbc.mongo;
|
|
import com.mongodb.MongoClientSettings;
|
import com.mongodb.MongoCredential;
|
import com.mongodb.ServerAddress;
|
import com.mongodb.client.MongoClient;
|
import com.mongodb.client.MongoClients;
|
import com.walker.infrastructure.utils.StringUtils;
|
import org.springframework.data.mongodb.MongoDatabaseFactory;
|
import org.springframework.data.mongodb.core.MongoTemplate;
|
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
|
|
import java.util.Arrays;
|
import java.util.concurrent.TimeUnit;
|
|
public class MongoTemplateFactory {
|
|
public MongoTemplate createTemplate(MongoProperty mongoProperty){
|
return this.createTemplate(mongoProperty.getIp(), mongoProperty.getPort(), mongoProperty.getDatabase()
|
, mongoProperty.getUserName(), mongoProperty.getPassword(), mongoProperty.getMaxSize()
|
, mongoProperty.getMinSize(), mongoProperty.getMaxIdleTimeSeconds(), mongoProperty.getMaxWaitTimeSeconds());
|
}
|
|
public MongoTemplate createTemplate(String ip, int port, String database
|
, String userName, String password, int maxSize, int minSize, long maxIdleTimeSeconds, long maxWaitTimeSeconds){
|
if(StringUtils.isEmpty(ip) || StringUtils.isEmpty(database)){
|
throw new IllegalArgumentException("ip, database必须设置");
|
}
|
ServerAddress serverAddress = new ServerAddress(ip, port);
|
MongoClientSettings settings = MongoClientSettings.builder()
|
.applyToClusterSettings(builder -> builder.hosts(Arrays.asList(serverAddress)))
|
.credential(MongoCredential.createCredential(userName, database, password.toCharArray()))
|
.applyToConnectionPoolSettings(builder -> builder.maxSize(maxSize).minSize(minSize)
|
.maxConnectionIdleTime(maxIdleTimeSeconds, TimeUnit.SECONDS)
|
.maxWaitTime(maxWaitTimeSeconds, TimeUnit.SECONDS))
|
.build();
|
MongoClient mongoClient = MongoClients.create(settings);
|
|
MongoDatabaseFactory dbFactory = new SimpleMongoClientDatabaseFactory(mongoClient, database);
|
// if(StringUtils.isNotEmpty(userName) && StringUtils.isNotEmpty(password)){
|
// // 存在密码
|
// dbFactory = new SimpleMongoClientDatabaseFactory()
|
// } else {
|
// // 没有密码
|
// }
|
return new MongoTemplate(dbFactory);
|
}
|
}
|