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, 所有的都公用一个行不行?(待优化)

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

原文地址:https://www.cnblogs.com/milicool/p/10021681.html

时间: 2024-11-06 03:52:31

springboot整合mongo多数据源的相关文章

SpringBoot整合Mybatis多数据源 (AOP+注解)

SpringBoot整合Mybatis多数据源 (AOP+注解) 1.pom.xml文件(开发用的JDK 10) <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:s

SpringBoot整合MYBATIS,多数据源,事务,支持JAVA -JAR 启动.

用了一段时间SpringBoot,之前配置MYBATIS ,在打包WAR 放到tomcat下正常,但是WAR已经过时了,现在流行直接打包JAR 丢到DOCKER 里,无奈JAR 启动的时候MAPPER 扫描有问题,只能说之前整合MYBATIS 的方式不对. 这次的整合应该是不存在加载顺序引起的问题,使用了一段时间,妥妥的,记录下来 pom.xml <parent> <groupId>org.springframework.boot</groupId> <artif

springboot 整合 mybatis 多数据源配置

一.mysql的多数据源的配置 1. 项目结构 包名 说明 com.kk.configuration 数据库配置层 com.kk.testcss.controller 控制层 com.kk.testcss.dao 数据库操作层,又分了不同的两个包,分别操作数据源1 和 数据源2 com.kk.testcss.service 业务逻辑层 com.kk.model 实体类 com.kk.Application 启动类 2.数据库配置 springboot 主配置文件 application.prop

springboot整合阿里druid数据源

全配置在application配置文件(方式1) maven依赖 <!--druid的启动器--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.17</version> </dependency> <!--这里不加jdbc依

Springboot整合Druid数据源

Druid是阿里巴巴的一个开源的JDBC组件,该组件由数据库连接池.插件框架和SQL解析器组成,主要功能如下: 1.DruidDriver 代理Driver,能够提供基于Filter-Chain模式的插件体系. 2.DruidDataSource 高效可管理的数据库连接池. 3.SQLParser解析器兼容所有的JDBC数据库,如:Mysql,Oracle.SQL Server数据库. 同时它结合了C3P0.DBCP.PROXOOL等DB池的优点,加入了日志监控,在稳定性.可扩展性和性能方便具有

Spring-boot集成pg、mongo多数据源

spring boot集成pg.mongo多数据源 修改POM文件,增加相应Jar包 12345678910111213 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency><dependency> <groupId

springboot整合mybatis(SSM开发环境搭建)

0.项目结构: 1.application.properties中配置整合mybatis的配置文件.mybatis扫描别名的基本包与数据源 server.port=80 logging.level.org.springframework=DEBUG #springboot mybatis #jiazai mybatis peizhiwenjian mybatis.mapper-locations = classpath:mapper/*Mapper.xml mybatis.config-loca

SpringBoot系列十二:SpringBoot整合 Shiro

1.概念:SpringBoot 整合 Shiro 2.具体内容 Shiro 是现在最为流行的权限认证开发框架,与它起名的只有最初的 SpringSecurity(这个开发框架非常不好用,但是千万不要 以为 SpringSecurity 没有用处,它在 SpringCloud 阶段将发挥重大的作用).但是现在如果要想整合 Shiro 开发框架有一点很遗憾, SpringBoot 没有直接的配置支持,它不像整合所谓的 Kafka.Redis.DataSource,也就是说如果要想整合 Shiro 开

SpringBoot整合Kafka和Storm

前言 本篇文章主要介绍的是SpringBoot整合kafka和storm以及在这过程遇到的一些问题和解决方案. kafka和storm的相关知识 如果你对kafka和storm熟悉的话,这一段可以直接跳过!如果不熟,也可以看看我之前写的博客.一些相关博客如下. kafka 和 storm的环境安装 地址:http://www.panchengming.com/2018/01/26/pancm70/ kafka的相关使用 地址:http://www.panchengming.com/2018/01