shikeying
2024-01-11 3b67e947e36133e2a40eb2737b15ea375e157ea0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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);
    }
}