springboot整合mongo多数据源

Posted otherCoding

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot整合mongo多数据源相关的知识,希望对你有一定的参考价值。

该实例已测试

POM.XML

 <!-- Spring Boot mongodb 依赖-->
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-mongodb</artifactId>
 </dependency>

application.yml

 1  data:
 2         mongodb:
 3             primary:
 4                 uri: 192.168.0.103:27870
 5                 database: 
 6                 username: 
 7                 password: 
 8                 authentication-database: 
 9             second:
10                 uri: 192.168.0.103:27870
11                 database: 
12                 username: 
13                 password: 
14                 authentication-database: 
15             connectionsPerHost: 10
16             options:
17                 min-connections-per-host: 8
18                 threads-allowed-to-block-for-connection-multiplier: 4
19                 max-wait-time: 1500
20                 socket-timeout: 1500

AbstractMongoConfig

  1 package com.haoyun.common.config.mongo;
  2 
  3 import com.mongodb.MongoClient;
  4 import com.mongodb.MongoClientOptions;
  5 import com.mongodb.MongoCredential;
  6 import com.mongodb.ServerAddress;
  7 import org.springframework.beans.factory.annotation.Value;
  8 import org.springframework.data.mongodb.MongoDbFactory;
  9 import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
 10 
 11 import java.util.ArrayList;
 12 import java.util.List;
 13 
 14 public class AbstractMongoConfig {
 15 
 16     protected List<String>    uri;
 17     protected String          username;
 18     protected String          password;
 19     protected String          authenticationDatabase;
 20     protected String          database;
 21 
 22     @Value("${spring.data.mongodb.connectionsPerHost}")
 23     private Integer connectionsPerHost;
 24 
 25     @Value("${spring.data.mongodb.options.min-connections-per-host}")
 26     private Integer minConnectionsPerHost;
 27 
 28     @Value("${spring.data.mongodb.options.threads-allowed-to-block-for-connection-multiplier}")
 29     private Integer threadsAllowedToBlockForConnectionMultiplier;
 30 
 31     @Value("${spring.data.mongodb.options.max-wait-time}")
 32     private Integer maxWaitTime;
 33 
 34     @Value("${spring.data.mongodb.options.socket-timeout}")
 35     private Integer socketTimeout;
 36 
 37     //覆盖默认的MongoDbFacotry
 38     public MongoDbFactory mongoDbFactory() {
 39         //客户端配置(连接数、副本集群验证)
 40         MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
 41         builder.connectionsPerHost(this.connectionsPerHost);
 42         builder.minConnectionsPerHost(this.minConnectionsPerHost);
 43         builder.threadsAllowedToBlockForConnectionMultiplier(this.threadsAllowedToBlockForConnectionMultiplier);
 44         builder.maxWaitTime(this.maxWaitTime);
 45         builder.socketTimeout(this.socketTimeout);
 46 
 47         MongoClientOptions mongoClientOptions = builder.build();
 48 
 49         List<ServerAddress> serverAddresses = new ArrayList<>();
 50         List<String> address = this.uri;
 51         for (String add : address) {
 52             String[] str = add.split(":");
 53             ServerAddress serverAddress = new ServerAddress(str[0], Integer.parseInt(str[1]));
 54             serverAddresses.add(serverAddress);
 55         }
 56 
 57         // 连接认证
 58         List<MongoCredential> mongoCredentialList = new ArrayList<>();
 59         if (this.username != null) {
 60             mongoCredentialList.add(MongoCredential.createScramSha1Credential(
 61                     this.username,
 62                     this.authenticationDatabase != null ? this.authenticationDatabase : this.database,
 63                     this.password.toCharArray()));
 64         }
 65         System.out.println("mongoCredentialList:" + mongoCredentialList.toString());
 66 
 67         //创建客户端和Factory
 68         MongoClient mongoClient = new MongoClient(serverAddresses, mongoCredentialList, mongoClientOptions);
 69         MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, this.database);
 70 
 71         return mongoDbFactory;
 72     }
 73 
 74     public List<String> getUri() {
 75         return uri;
 76     }
 77 
 78     public void setUri(List<String> uri) {
 79         this.uri = uri;
 80     }
 81 
 82     public String getUsername() {
 83         return username;
 84     }
 85 
 86     public void setUsername(String username) {
 87         this.username = username;
 88     }
 89 
 90     public String getPassword() {
 91         return password;
 92     }
 93 
 94     public void setPassword(String password) {
 95         this.password = password;
 96     }
 97 
 98     public String getAuthenticationDatabase() {
 99         return authenticationDatabase;
100     }
101 
102     public void setAuthenticationDatabase(String authenticationDatabase) {
103         this.authenticationDatabase = authenticationDatabase;
104     }
105 
106     public String getDatabase() {
107         return database;
108     }
109 
110     public void setDatabase(String database) {
111         this.database = database;
112     }
113 }

PrimaryMongoConfig

 1 package com.haoyun.common.config.mongo;
 2 
 3 import org.springframework.boot.context.properties.ConfigurationProperties;
 4 import org.springframework.context.annotation.Bean;
 5 import org.springframework.context.annotation.Configuration;
 6 import org.springframework.context.annotation.Primary;
 7 import org.springframework.data.mongodb.core.MongoTemplate;
 8 
 9 /**
10  * @author milicool
11  * Created on 2018/11/26
12  */
13 @Configuration
14 @ConfigurationProperties(prefix = "spring.data.mongodb.primary")
15 public class PrimaryMongoConfig extends AbstractMongoConfig {
16 
17     @Primary
18     @Bean(name = "mongoTemplate")
19     public MongoTemplate getMongoTemplate() {
20         return new MongoTemplate(mongoDbFactory());
21     }
22 }

SecondMongoConfig

 1 package com.haoyun.common.config.mongo;
 2 
 3 import org.springframework.boot.context.properties.ConfigurationProperties;
 4 import org.springframework.context.annotation.Bean;
 5 import org.springframework.context.annotation.Configuration;
 6 import org.springframework.data.mongodb.core.MongoTemplate;
 7 
 8 /**
 9  * @author milicool
10  * Created on 2018/11/26
11  */
12 @Configuration
13 @ConfigurationProperties(prefix="spring.data.mongodb.second")
14 public class SecondMongoConfig extends AbstractMongoConfig {
15 
16     @Bean(name = "secondMmongoTemplate")
17     public MongoTemplate getMongoTemplate() {
18         return new MongoTemplate(mongoDbFactory());
19     }
20 }

MongoDao

 1 package com.haoyun.common.jdbc;
 2 
 3 import com.mongodb.client.result.UpdateResult;
 4 import org.springframework.data.mongodb.core.MongoTemplate;
 5 import org.springframework.data.mongodb.core.aggregation.Aggregation;
 6 import org.springframework.data.mongodb.core.query.Query;
 7 import org.springframework.data.mongodb.core.query.Update;
 8 import org.springframework.stereotype.Repository;
 9 
10 import javax.annotation.Resource;
11 import java.util.List;
12 
13 
14 @Repository("mongoDao")
15 public class MongoDao {
16 
17     @Resource(name = "mongoTemplate")
18     private MongoTemplate mongoTemplate;
19 
20     public void insert(Object o, String collectionName) {
21         mongoTemplate.insert(o, collectionName);
22     }
23 
24     public <T> T findOne(Query query, String collectionName, Class<T> clazz) {
25         return mongoTemplate.findOne(query, clazz, collectionName);
26     }
27 
28     public <T> List<T> findAll(Query query, String collectionName, Class<T> clazz) {
29         return mongoTemplate.find(query, clazz, collectionName);
30     }
31 
32     public int update(Query query, Update update, String collectionName) {
33         UpdateResult writeResult = mongoTemplate.upsert(query, update, collectionName);
34         return (int) writeResult.getModifiedCount();
35     }
36 
37     public void createCollection(String collectionName) {
38         mongoTemplate.createCollection(collectionName);
39     }
40 
41     public <T> void remove(Query query, String collectionName) {
42         mongoTemplate.remove(query, collectionName);
43     }
44 
45     public long count(Query query, String collectionName) {
46         return mongoTemplate.count(query, collectionName);
47     }
48 
49     public <T> T findAndModify(Query query, Update update, String collectionName, Class<T> clazz) {
50         return mongoTemplate.findAndModify(query, update, clazz, collectionName);
51     }
52 
53     public <T> List<T> findAggregation(Aggregation agg, String collectionName, Class<T> clazz) {
54         return mongoTemplate.aggregate(agg, collectionName, clazz).getMappedResults();
55     }
56 
57 
58 }

SecondMongoDao

package com.haoyun.common.jdbc;

import com.mongodb.client.result.UpdateResult;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

@Repository("secondMongoDao")
public class SecondMongoDao {

    @Resource(name = "secondMmongoTemplate")
    private MongoTemplate mongoTemplate;

    public void insert(Object o, String collectionName) {
        mongoTemplate.insert(o, collectionName);
    }

    public <T> T findOne(Query query, String collectionName, Class<T> clazz) {
        return mongoTemplate.findOne(query, clazz, collectionName);
    }

    public <T> List<T> findAll(Query query, String collectionName, Class<T> clazz) {
        return mongoTemplate.find(query, clazz, collectionName);
    }

    public int update(Query query, Update update, String collectionName) {
        UpdateResult writeResult = mongoTemplate.upsert(query, update, collectionName);
        return (int) writeResult.getModifiedCount();
    }

    public void createCollection(String collectionName) {
        mongoTemplate.createCollection(collectionName);
    }

    public <T> void remove(Query query, String collectionName) {
        mongoTemplate.remove(query, collectionName);
    }

    public long count(Query query, String collectionName) {
        return mongoTemplate.count(query, collectionName);
    }

    public <T> T findAndModify(Query query, Update update, String collectionName, Class<T> clazz) {
        return mongoTemplate.findAndModify(query, update, clazz, collectionName);
    }

    public <T> List<T> findAggregation(Aggregation agg, String collectionName, Class<T> clazz) {
        return mongoTemplate.aggregate(agg, collectionName, clazz).getMappedResults();
    }


}

引入

测试

结语

有两处不爽的地方,为啥加一个数据源就要多个config和Dao, 所有的都公用一个行不行?(待优化)

长路漫漫, 走过了村落, 却忘记了你的脸庞

 

 

以上是关于springboot整合mongo多数据源的主要内容,如果未能解决你的问题,请参考以下文章

全栈编程系列SpringBoot整合Shiro(含KickoutSessionControlFilter并发在线人数控制以及不生效问题配置启动异常No SecurityManager...)(代码片段

MongoDB简介与应用场景Docker安装Mongo整合SpringBoot实现CRUD

Java:SpringBoot整合hibernate-validator实现入参数据校验

springboot Thymeleaf 整合

springboot集成mongo

解决SpringBoot 整合 MongoDB,继承MongoRepository的Repo接口无法注入异常