博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
从零搭建自己的SpringBoot后台框架(十一)
阅读量:6150 次
发布时间:2019-06-21

本文共 6817 字,大约阅读时间需要 22 分钟。

Hello大家好,本章我们配置多数据源功能 。有问题可以联系我mr_beany@163.com。另求各路大神指点,感谢

一:配置数据源

修改application.properties

spring.datasource.db1.driver-class-name=com.mysql.jdbc.Driverspring.datasource.db1.url=jdbc:mysql://localhost:3333/demo?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&autoReconnect=true&failOverReadOnly=falsespring.datasource.db1.username=rootspring.datasource.db1.password=123456spring.datasource.db1.initialSize=5spring.datasource.db1.minIdle=5spring.datasource.db1.maxActive=20#连接等待超时时间spring.datasource.db1.maxWait=60000#配置隔多久进行一次检测(检测可以关闭的空闲连接)spring.datasource.db1.timeBetweenEvictionRunsMillis=60000#配置连接在池中的最小生存时间spring.datasource.db1.minEvictableIdleTimeMillis=300000spring.datasource.db1.validationQuery=SELECT 1 FROM DUALspring.datasource.db1.testWhileIdle=truespring.datasource.db1.testOnBorrow=falsespring.datasource.db1.testOnReturn=false# 打开PSCache,并且指定每个连接上PSCache的大小spring.datasource.db1.poolPreparedStatements=truespring.datasource.db1.maxPoolPreparedStatementPerConnectionSize=20# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙spring.datasource.db1.filters=stat,wall,slf4j# 通过connectProperties属性来打开mergeSql功能;慢SQL记录spring.datasource.db1.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000spring.datasource.db2.driver-class-name=com.mysql.jdbc.Driverspring.datasource.db2.url=jdbc:mysql://localhost:3306/chuchen?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&autoReconnect=true&failOverReadOnly=falsespring.datasource.db2.username=rootspring.datasource.db2.password=123456spring.datasource.db2.initialSize=5spring.datasource.db2.minIdle=5spring.datasource.db2.maxActive=20#连接等待超时时间spring.datasource.db2.maxWait=60000#配置隔多久进行一次检测(检测可以关闭的空闲连接)spring.datasource.db2.timeBetweenEvictionRunsMillis=60000#配置连接在池中的最小生存时间spring.datasource.db2.minEvictableIdleTimeMillis=300000spring.datasource.db2.validationQuery=SELECT 1 FROM DUALspring.datasource.db2.testWhileIdle=truespring.datasource.db2.testOnBorrow=falsespring.datasource.db2.testOnReturn=false# 打开PSCache,并且指定每个连接上PSCache的大小spring.datasource.db2.poolPreparedStatements=truespring.datasource.db2.maxPoolPreparedStatementPerConnectionSize=20# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙spring.datasource.db2.filters=stat,wall,slf4j# 通过connectProperties属性来打开mergeSql功能;慢SQL记录spring.datasource.db2.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000复制代码

注意修改为自己的数据库连接

二:创建数据源配置

MysqlDataSource1Config

package com.example.demo.core.configurer.dataSource;import com.alibaba.druid.pool.DruidDataSource;import org.apache.ibatis.session.SqlSessionFactory;import org.mybatis.spring.SqlSessionFactoryBean;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Primary;import org.springframework.core.io.Resource;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import org.springframework.jdbc.datasource.DataSourceTransactionManager;import org.springframework.transaction.annotation.EnableTransactionManagement;import tk.mybatis.spring.annotation.MapperScan;import javax.sql.DataSource;@Configuration@EnableTransactionManagement@MapperScan(basePackages = {
"com.example.demo.dao.db1"})public class MysqlDataSource1Config { @Bean(name = "primaryDataSource") //需设置主数据源 @Primary @ConfigurationProperties(prefix="spring.datasource.db1") public DataSource dataSource(){ //跟之前不一样了 return new DruidDataSource(); } @Bean(name = "primaryTransactionManager") @Primary public DataSourceTransactionManager masterTransactionManager() { return new DataSourceTransactionManager(dataSource()); } @Bean(name="primarySqlSessionFactory") @Primary public SqlSessionFactory sqlSessionFactory(@Qualifier("primaryDataSource")DataSource primaryDataSource) throws Exception { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(primaryDataSource); Resource[] mapperLocations = new PathMatchingResourcePatternResolver().getResources("classpath:mapper/db1/*.xml"); sessionFactory.setMapperLocations(mapperLocations); return sessionFactory.getObject(); }}复制代码

MysqlDataSource2Config

package com.example.demo.core.configurer.dataSource;import com.alibaba.druid.pool.DruidDataSource;import org.apache.ibatis.session.SqlSessionFactory;import org.mybatis.spring.SqlSessionFactoryBean;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.io.Resource;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import tk.mybatis.spring.annotation.MapperScan;import javax.sql.DataSource;@Configuration@MapperScan(basePackages = {
"com.example.demo.dao.db2"}, sqlSessionFactoryRef = "secondSqlSessionFactory")public class MysqlDataSource2Config { @Bean(name = "secondDataSource") @ConfigurationProperties(prefix = "spring.datasource.db2") public DataSource dataSource() { return new DruidDataSource(); } @Bean(name = "secondSqlSessionFactory") public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSource()); Resource[] mapperLocations = new PathMatchingResourcePatternResolver().getResources("classpath:mapper/db2/*.xml"); sessionFactory.setMapperLocations(mapperLocations); return sessionFactory.getObject(); }}复制代码

三:修改目录结构

目录结构如下图,db1为主数据源,db2为从数据源,这样根据访问dao层不同,会自动进行数据源切换

四:功能测试

输入http://localhost:8080/userInfo/selectAll

结果:

{    "code": 200,    "data": {        ....省略        "list": [            {                "id": "1",                "userName": "Mr_初晨"            },            {                "id": "2",                "userName": "Mr_初晨"            }        ],        .....省略    },    "msg": "success"}复制代码

输入http://localhost:8080/userLabel/list

结果:

{    "code": 200,    "data": {        ....省略        "list": [             {                "createTime": 1523283547000,                "id": "24084baed3c6409a8619a635bf4428a1",                "labelId": "4",                "userId": "1"            }        ],        .....省略    },    "msg": "success"}复制代码

输入http://localhost:8080/druid/datasource.html

也可以看见有两个数据源

项目地址

码云地址:

GitHub地址:

写文章不易,如对您有帮助,请帮忙点下star

结尾

配置多数据源功能已完成,后续功能接下来陆续更新,有问题可以联系我mr_beany@163.com。另求各路大神指点,感谢大家。

转载地址:http://mhmya.baihongyu.com/

你可能感兴趣的文章
[TC13761]Mutalisk
查看>>
Data Wrangling文摘:Non-tidy-data
查看>>
while()
查看>>
常用限制input的方法
查看>>
IIS7下使用urlrewriter.dll配置
查看>>
并行程序设计学习心得1——并行计算机存储
查看>>
JAVA入门到精通-第86讲-半双工/全双工
查看>>
bulk
查看>>
js document.activeElement 获得焦点的元素
查看>>
C++ 迭代器运算
查看>>
【支持iOS11】UITableView左滑删除自定义 - 实现多选项并使用自定义图片
查看>>
day6-if,while,for的快速掌握
查看>>
JavaWeb学习笔记(十四)--JSP语法
查看>>
【算法笔记】多线程斐波那契数列
查看>>
java8函数式编程实例
查看>>
jqgrid滚动条宽度/列显示不全问题
查看>>
在mac OS10.10下安装 cocoapods遇到的一些问题
查看>>
angularjs表达式中的HTML内容,如何不转义,直接表现为html元素
查看>>
css技巧
查看>>
Tyvj 1728 普通平衡树
查看>>