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>org.postgresql</groupId>		<artifactId>postgresql</artifactId>		<scope>runtime</scope>	</dependency><dependency>		<groupId>org.springframework.boot</groupId>		<artifactId>spring-boot-starter-jdbc</artifactId></dependency>

修改启动类,去除原有的数据源自动加载机制

1234567
@SpringBootApplication(        exclude = {DataSourceAutoConfiguration.class,                    PageHelperAutoConfiguration.class ,        		   MongoAutoConfiguration.class, MongoDataAutoConfiguration.class//禁用数据源自动配置        })@EnableEurekaClientpublic class MainApplication {、、、

编写application.yml文件,增加配置信息

1234567891011121314
spring:    # 默认的postgreSQL库  datasource:    pg:      url: jdbc:postgresql://127.0.0.1:5432/pgdb      username: us_wu      password: [email protected]      driver-class-name: org.postgresql.Driver    mg:      host: 127.0.0.1      username: aaa      password: aaa      database: mgdb      port: 27017

分别手动增加PG、mongo的数据源以及使用样例

pg

1234567891011121314151617181920212223242526272829303132333435363738394041424344
1、手动加载数据源@Configurationpublic class DataSourceConfig {    final  String cmspg="spring.datasource.pg";

    @Bean(name = "pgDS")    @ConfigurationProperties(prefix =pg)     public DataSource dataSource() {        return DataSourceBuilder.create().build();    }

2、创建pg配置文件,指定SqlSessionFactory以及要扫描的Dao@Configuration@MapperScan(basePackages = {"com.**.mapper.pg"}, sqlSessionFactoryRef = "sqlSessionFactory")public class PostgresDBConfig {

    @Autowired    @Qualifier("pgDS")    private DataSource pgDS;

    @Bean    public SqlSessionFactory sqlSessionFactory() throws Exception {        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();        factoryBean.setDataSource(pgDS);            return factoryBean.getObject();

    }

    @Bean    public SqlSessionTemplate sqlSessionTemplate() throws Exception {        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory()); // 使用上面配置的Factory        return template;    }}

3、编写Dao--注解形式@Repository@Mapperpublic interface StCableFiberMapper {

    @Select("SELECT * FROM st_cable_fiber WHERE id = #{id}")    St_cable_fiber findById(@Param("id") String id);

mongo

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
1、加载mongo配置信息public abstract class AbstractMongoConfigure {

		private String host, database, username, password;		private int port;		// Setter methods go here..

		/*		 * Method that creates MongoDbFactory Common to both of the MongoDb		 * connections		 */		public MongoDbFactory mongoDbFactory() throws Exception {			ServerAddress serverAddress = new ServerAddress(host, port);			List<MongoCredential> mongoCredentialList = new ArrayList<>();			mongoCredentialList.add(MongoCredential.createScramSha1Credential(username, database, password.toCharArray()));			return new SimpleMongoDbFactory(new MongoClient(serverAddress,mongoCredentialList), database);		}

		/*		 * Factory method to create the MongoTemplate		 */		abstract public MongoTemplate getMongoTemplate() throws Exception;}

@Configuration@EnableMongoRepositories(basePackages = {"com.**.mapper.mg"},mongoTemplateRef = "mongoTemplate") @ComponentScan@ConfigurationProperties(prefix = "spring.datasource.mg")public class MongoMasterConfig extends AbstractMongoConfigure{

	@Override	@Bean("mongoTemplate")	public MongoTemplate getMongoTemplate() throws Exception {		return new MongoTemplate(mongoDbFactory()); 	}

}2.1、编写Dao  MongoTemplate模式

@Repositorypublic class CmCableDetailRepo{

	@Autowired	private MongoTemplate mongoTemplate;

	public Page<Cm_Cable> findByLevelAndName(String areacode, int level,String name,int pageNum, int pageSize){

		PageRequest page = new PageRequest(pageNum, pageSize);		Query query = new Query();		Criteria criteria = new Criteria();		criteria.and("areacode").regex("^"+areacode);		if(level > -1){			criteria.and("cableSegment_level").is(level);		}		if(null != name && name.trim().length() > 0){			criteria.and("zh_label").regex(".*?"+name+".*");		}		query.addCriteria(criteria);		Long count = mongoTemplate.count(query, Cm_Cable.class);

		List<Cm_Cable> list = mongoTemplate.find(query.with(page), Cm_Cable.class);		return new PageImpl<Cm_Cable>(list, page, count);	}

2.2、MongoRepository模式@Repositorypublic interface CmCableDetailMapper extends MongoRepository<Cm_Cable, String>{

}

原文:大专栏  Spring-boot集成pg、mongo多数据源

原文地址:https://www.cnblogs.com/wangziqiang123/p/11657603.html

时间: 2024-08-30 10:40:17

Spring-boot集成pg、mongo多数据源的相关文章

170711、spring boot 集成shiro

这篇文章我们来学习如何使用Spring Boot集成Apache Shiro.安全应该是互联网公司的一道生命线,几乎任何的公司都会涉及到这方面的需求.在Java领域一般有Spring Security.Apache Shiro等安全框架,但是由于Spring Security过于庞大和复杂,大多数公司会选择Apache Shiro来使用,这篇文章会先介绍一下Apache Shiro,在结合Spring Boot给出使用案例. Apache Shiro What is Apache Shiro?

Spring Boot集成Jasypt安全框架

Jasypt安全框架提供了Spring的集成,主要是实现 PlaceholderConfigurerSupport类或者其子类. 在Sring 3.1之后,则推荐使用PropertySourcesPlaceholderConfigurer类作为属性替换配置类,这里Spring集成Jasypt则使用Jasypt对属性替换配置类的实现.EncryptablePropertySourcesPlaceholderConfigurer. 在Spring中集成比较容易,而且Jasypt官方也给出了配置Bea

Spring Boot 集成MyBatis

Spring Boot 集成MyBatis 在集成MyBatis前,我们先配置一个druid数据源. Spring Boot 系列 Spring Boot 入门 Spring Boot 属性配置和使用 Spring Boot 集成MyBatis Spring Boot 静态资源处理 Spring Boot - 配置排序依赖技巧 Spring Boot - DevTools 介绍 Spring Boot 集成druid druid有非常多个配置选项,使用Spring Boot 的配置文件能够方便的

Quartz与Spring Boot集成使用

上次自己搭建Quartz已经是几年前的事了,这次项目中需要定时任务,需要支持集群部署,想到比较轻量级的定时任务框架就是Quartz,于是来一波. 版本说明 通过搜索引擎很容易找到其官网,来到Document的页面,当前版本是2.2.x. 简单的搭建操作 通过Maven引入所需的包: <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId>

Spring Boot 集成 MyBatis(四)

Spring Boot 集成 MyBatis A.ORM框架是什么? 对象关系映射(Object Relational Mapping,简称 ORM)模式是一种为了解决面向对象与关系数据库存在的 互不匹配的现象技术.简单的说,ORM 是通过使用描述对象和数据库之间映射的元数据,将程序中的对象自 动持久化到关系数据库中. B.为什么需要ORM框架 当开发一个应用程序的时候(不使用 O/R Mapping),可能会写不少数据访问层的代码,用来从数据库保存. 删除.读取对象信息等.在 DAL 中写了很

Spring Boot集成Spring Scheduler和Quartz Scheduler

本文介绍了Spring Boot集成Spring Scheduler和Quartz Scheduler的基础知识,利用ShedLock解决Spring Scheduler多实例运行冲突,介绍了Quartz ScheduleBuilder.Calendar,介绍了动态创建Quartz Job的方法. GitHub源码 Spring Scheduler Spring Framework提供了简单.易用的Job调度框架Spring Scheduler. 示例 在Spring Boot中,只需两步即可启

spring boot 集成 dubbo 企业完整版

一.什么是Spring Boot ? 现阶段的 Spring Boot 可谓是太火了,为什么呢?因为使用方便.配置简洁.上手快速,那么它是什么?从官网上我们可以看到,它是 Spring 开源组织下的一个子项目,主要简化了 Spring 繁重的配置,而且 Spring Boot 内嵌了各种 Servlet 容器,如:Tomcat.Jetty 等 官方网站:http://projects.spring.io/spring-boot/ GitHub源码:https://github.com/sprin

spring boot 集成 hbase

spring boot 集成 hbase 会启动报错 主要因为Spring Boot内嵌了Web容器,方便对应用进行微服务化开发和部署.所以打算将HBase的业务应用作为一个单服务进行开发和发布,其他相关的子系统通过RESTful API来访问. 搭建项目环境时,需要注意的事项: 由于Spring Boot内嵌了Web容器,所以框架默认导入了依赖:tomcat-embed-core-8.5.5.jar.tomcat-embed-el-8.5.5.jar等包.而HBase的jar中包含了:serv

spring boot集成swagger2

做java Web的后端开发已经两年多了,一般都是开发完了接口,都把接口更新到wiki文档上,然后通知前端去文档上去查阅接口的详细描述, 当时经常接口会有变动,加参数或返回值夹字段,所以维护语线上一致的文档是一件非常麻烦的事情,前一段时间同事聊天说他们公司用的swagger2,这个不需要写文档,它是自动生成文档,只要会使用它提供的几个的注解就行,于是上网找了下资料,发现它于spring boot集成也非常方便.不废话直接看了代码. 首先,在maven项目的pom.xml加上他需要的依赖. <de

Kafka 入门和 Spring Boot 集成

Kafka 入门和 Spring Boot 集成 标签:博客 [TOC] 概述 kafka 是一个高性能的消息队列,也是一个分布式流处理平台(这里的流指的是数据流).由java 和 Scala 语言编写,最早由 LinkedIn 开发,并 2011年开源,现在由 Apache 开发维护. 应用场景 下面列举了一些kafka常见的应用场景. 消息队列 : Kafka 可以作为消息队列使用,可用于系统内异步解耦,流量削峰等场景. 应用监控:利用 Kafka 采集应用程序和服务器健康相关的指标,如应用