spring boot 基础篇 -- 阿里多数据源
这块是比较基础的配置,阿里数据库配置还是比较好用的,并且可以用来监控数据源的情况。废话不多说,下面看代码。
基于maven项目,在pom.xml中添加引用:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.11</version>
</dependency>
配置文件如下:
server.port=9090
logging.level.tk.mybatis=TRACE druid1.type=com.alibaba.druid.pool.DruidDataSource
druid1.url=jdbc:mysql://192.168.0.190:3306/bestPractices
druid1.driver-class=com.mysql.jdbc.Driver
druid1.username=root
druid1.password=youeDATA2016_
druid1.initial-size=1
druid1.min-idle=1
druid1.max-active=20
druid1.test-on-borrow=true
druid1.filters=stat,wall,log4j
druid1.poolPreparedStatements=true
druid1.datasource.maxPoolPreparedStatementPerConnectionSize=20
druid1.datasource.logAbandoned=true druid2.type=com.alibaba.druid.pool.DruidDataSource
druid2.url=jdbc:mysql://192.168.0.190:3306/bestPracticesTwo
druid2.driver-class=com.mysql.jdbc.Driver
druid2.username=root
druid2.password=youeDATA2016_
druid2.initial-size=1
druid2.min-idle=1
druid2.max-active=20
druid2.test-on-borrow=true
druid2.filters=stat,wall,log4j
druid2.poolPreparedStatements=true
druid2.datasource.maxPoolPreparedStatementPerConnectionSize=20
druid2.datasource.logAbandoned=true spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
mybatis.type-aliases-package=bp.model
mybatis.mapper-locations=classpath:mybatis/mybatis-config.xml
mapper.mappers=bp.util.MyMapper
#mapper.not-empty=false
#mapper.identity=MYSQL
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.dialect=com.github.pagehelper.dialect.helper.MySqlDialect
pagehelper.params=count=countSql
pagehelper.autoDialect=true
pagehelper.closeConn=false
pagehelper.offsetAsPageNum=true spring.http.encoding.force=true
spring.redis.database= 0
spring.redis.host= 192.168.237.128
spring.redis.port= 6379
spring.redis.pool.max-active= 8
spring.redis.pool.max-idle= 8
spring.redis.pool.max-wait=-1
spring.redis.pool.min-idle=0
spring.redis.timeout= 1500
配置文件:数据源1
package bp.config; import java.sql.SQLException; import javax.sql.DataSource; import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager; import com.alibaba.druid.pool.DruidDataSource; /**
* 数据源1
*/
@Configuration
@EnableConfigurationProperties(DruidProperties1.class)
@AutoConfigureBefore(DataSourceAutoConfiguration.class)
@ConditionalOnClass(DruidDataSource.class)
@MapperScan(basePackages = "bp.mapper.mapper1", sqlSessionTemplateRef = "SqlSessionTemplate1")
public class DataSource1Config {
@Autowired
private DruidProperties1 properties; @Bean(name = "DataSource1")
@ConditionalOnProperty(prefix = "druid1", name = "url")
@Primary
public DataSource dataSource() throws SQLException {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(properties.getUrl());
dataSource.setUsername(properties.getUsername());
dataSource.setPassword(properties.getPassword());
dataSource.setFilters(properties.getFilters());
if (properties.getInitialSize() > 0) {
dataSource.setInitialSize(properties.getInitialSize());
}
if (properties.getMinIdle() > 0) {
dataSource.setMinIdle(properties.getMinIdle());
}
if (properties.getMaxActive() > 0) {
dataSource.setMaxActive(properties.getMaxActive());
}
dataSource.setTestOnBorrow(properties.isTestOnBorrow());
try {
dataSource.init();
} catch (SQLException e) {
throw new RuntimeException(e);
}
return dataSource;
} @Bean(name = "SqlSessionFactory1")
@Primary
public SqlSessionFactory test1SqlSessionFactory(@Qualifier("DataSource1") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
bean.setDataSource(dataSource);
bean.setConfigLocation(resolver.getResource("classpath:mybatis/mybatis-config.xml"));
bean.setMapperLocations(resolver.getResources("bp/mapper/mapper1/*.xml"));
return bean.getObject();
} @Bean(name = "TransactionManager1")
@Primary
public DataSourceTransactionManager test1TransactionManager(@Qualifier("DataSource1") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
} @Bean(name = "SqlSessionTemplate1")
@Primary
public SqlSessionTemplate test1SqlSessionTemplate(@Qualifier("SqlSessionFactory1") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
} }
数据源2:
package bp.config; import java.sql.SQLException; import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager; import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.alibaba.druid.support.spring.stat.DruidStatInterceptor; import javax.annotation.Resource;
import javax.sql.DataSource; /**
* 数据源2
*/
@Configuration
@EnableConfigurationProperties(DruidProperties2.class)
@AutoConfigureBefore(DataSourceAutoConfiguration.class)
@ConditionalOnClass(DruidDataSource.class)
@MapperScan(basePackages = "bp.mapper.mapper2", sqlSessionTemplateRef = "SqlSessionTemplate2")
public class DataSource2Config { @Autowired
private DruidProperties2 properties; @Bean(name = "DataSource2")
@ConditionalOnProperty(prefix = "druid2", name = "url")
public DataSource dataSource() throws SQLException {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(properties.getUrl());
dataSource.setUsername(properties.getUsername());
dataSource.setPassword(properties.getPassword());
dataSource.setFilters(properties.getFilters());
if (properties.getInitialSize() > 0) {
dataSource.setInitialSize(properties.getInitialSize());
}
if (properties.getMinIdle() > 0) {
dataSource.setMinIdle(properties.getMinIdle());
}
if (properties.getMaxActive() > 0) {
dataSource.setMaxActive(properties.getMaxActive());
}
dataSource.setTestOnBorrow(properties.isTestOnBorrow());
try {
dataSource.init();
} catch (SQLException e) {
throw new RuntimeException(e);
}
return dataSource;
} @Bean(name = "SqlSessionFactory2")
public SqlSessionFactory test2SqlSessionFactory(@Qualifier("DataSource2") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
bean.setDataSource(dataSource);
bean.setConfigLocation(resolver.getResource("classpath:mybatis/mybatis-config.xml"));
bean.setMapperLocations(resolver.getResources("bp/mapper/mapper2/*.xml"));
return bean.getObject();
} @Bean(name = "TransactionManager2")
public DataSourceTransactionManager test2TransactionManager(@Qualifier("DataSource2") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
} @Bean(name = "SqlSessionTemplate2")
public SqlSessionTemplate test2SqlSessionTemplate(@Qualifier("SqlSessionFactory2") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
} }
启动项目就发现是双数据源了
spring boot 基础篇 -- 阿里多数据源的更多相关文章
- spring boot 基础篇 -- 定时任务
在日常项目中,常常会碰到定时监控项目中某个业务的变化,下面是spring boot 集成的定时任务具体配置: @Component public class IndexWarningScheduled ...
- spring boot 基础篇 -- 集成接口测试Swagger
一.在pom.xml加入Swagger jar包引入 <dependency> <groupId>io.springfox</groupId> <artifa ...
- spring boot 基础篇 -- 自带图片服务器
我们平时在日常项目中经常会遇到图片的上传和访问的情景,平时我们可能习惯于把图片传到resource或者项项目中的某个位置,这样会有一个缺点,当我们重新项目打包时,这些图片会丢失.为了解决这一缺点,我们 ...
- spring boot基础学习教程
Spring boot 标签(空格分隔): springboot HelloWorld 什么是spring boot Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新 ...
- Spring Boot 基础
Spring Boot 基础 Spring Boot 项目(参考1) 提供了一个类似ASP.NET MVC的默认模板一样的标准样板,直接集成了一系列的组件并使用了默认的配置.使用Spring Boot ...
- Spring Boot 基础教程系列学习文档
Spring Boot基础教程1-Spring Tool Suite工具的安装 Spring Boot基础教程2-RESTfull API简单项目的快速搭建 Spring Boot基础教程3-配置文件 ...
- Spring Boot HikariCP 一 ——集成多数据源
其实这里介绍的东西主要是参考的另外一篇文章,数据库读写分离的. 参考文章就把链接贴出来,里面有那位的代码,简单明了https://gitee.com/comven/dynamic-datasource ...
- Spring Boot数据访问之动态数据源切换之使用注解式AOP优化
在Spring Boot数据访问之多数据源配置及数据源动态切换 - 池塘里洗澡的鸭子 - 博客园 (cnblogs.com)中详述了如何配置多数据源及多数据源之间的动态切换.但是需要读数据库的地方,就 ...
- Spring boot 提高篇
Spring boot 提高篇 上篇文章介绍了Spring boot初级教程:构建微服务:Spring boot 入门篇,方便大家快速入门.了解实践Spring boot特性:本篇文章接着上篇内容继续 ...
随机推荐
- 前端基础 DOM & BOM
推荐阅读:http://www.cnblogs.com/yuanchenqi/articles/6893904.html#_label3 BOM对象 window 对象 所有浏览器都支持 window ...
- Hadoop权威指南读书笔记
本书中提到的Hadoop项目简述 Common:一组分布式文件系统和通用I/O的组件与接口(序列化.javaRPC和持久化数据结构). Avro:一种支持高效.跨语言的RPC以及永久存储数据的序列化系 ...
- Python之异常处理(Day27)
一.错误和异常 part1: 1.语法错误(这种错误,根本过不了python解释器的语法检测,必须在程序执行前就改正) #语法错误示范一 if #语法错误示范二 def test: pass #语法错 ...
- Django基础(一)_URLconf、Views、template、ORM
一 什么是web框架? 框架,即framework,特指为解决一个开放性问题而设计的具有一定约束性的支撑结构,使用框架可以帮你快速开发特定的系统,简单地说,就是你用别人搭建好的舞台来做表演. 对于所有 ...
- NetCDF 介绍
NetCDF 1 NetCDF 1.1概述(Overview) NetCDF (network Common Data Form) is a set of software libraries and ...
- [笔记]如何将传统的回调函数转换为C#5.0支持的await格式
C#5.0引入了编译器支持的 async 和 await 关键字,这就为开发者提供了使用同步思想写异步代码的方便. 但是有些传统函数仅提供了异步回调实现,如何对其封装,使其可以享受await的便利呢? ...
- iOS 事件响应者链的学习(也有叫 UI连锁链)
当发生事件响应的时候,必须知道由谁来响应事件.在iOS中,由响应链来对事件进行响应,所有的事件响应的类都是继承于UIResponder的子类,响应链是一个由不同对象组成的层次结构,其中每个对象将依次获 ...
- 022_Hadoop中的数据类型(Writable、WritableComparable、Comparator、RawComparator…)
1. 在hadoop中所有的key/value都必须实现Writable接口,有两个方法,分别用于读(反序列化)和写(序列化)操作.
- Mycat实现Mysql数据库读写分离
Linux和Windows环境下搭建Mycat数据读写分离 前提需要:1.服务器装有JVM虚拟机,就是JDK.2.两个Mysql数据库已经实现主从复制,参考:https://www.cnblogs.c ...
- for语句中多重定义
"}; vector<string> vecStr(Arr, Arr + sizeof(Arr)/sizeof(string)); , sz = vecStr.size(); i ...