spring boot(四) 多数据源
前言
前一篇中我们使用spring boot+mybatis创建了单一数据源,其中单一数据源不需要我们自己手动创建,spring boot自动配置在程序启动时会替我们创建好数据源。
准备工作
application.yml中配置connection的4个属性
spring:
datasource:
read:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.80.129:3306/test
username: root
password: 123456
write:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.80.129:3306/test
username: root
password: 123456
多数据源创建方法
1、多数据源主要是需要我们手动来创建DataSource、SqlSessionFactory、SqlSessionTemplate。这里我们基于同一个库来创建读写分离的数据源。这里两个方法的返回值都是javax.sql.DataSource。
@Configuration
public class DataSourceConfig { @Primary
@Bean(name="readDataSource")
@ConfigurationProperties(prefix = "spring.datasource.read")
public DataSource readDataSource(){
return DataSourceBuilder.create().build();
} @Bean(name="writeDataSource")
@ConfigurationProperties(prefix = "spring.datasource.write")
public DataSource writeDataSource(){
return DataSourceBuilder.create().build();
} }
2、读写分离的配置类。也就是分别创建读写的SqlSessionFactory和SqlSessionTemplate
@Configuration
@MapperScan(basePackages = {"com.zhangfei.dao.read"},sqlSessionFactoryRef = "readSqlSessionFactory")
public class MyBatisDbAConfig { @Autowired
@Qualifier("readDataSource")
private DataSource dataSource; @Bean
public SqlSessionFactory readSqlSessionFactory() throws Exception{
SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resource=resolver.getResources("classpath:mybatis/read/*.xml");
sqlSessionFactoryBean.setMapperLocations(resource); return sqlSessionFactoryBean.getObject();
} @Bean
public SqlSessionTemplate readSqlSession() throws Exception{
SqlSessionTemplate sqlSessionTemplate=new SqlSessionTemplate(readSqlSessionFactory()); return sqlSessionTemplate;
}
}
@Configuration
@MapperScan(basePackages = {"com.zhangfei.dao.write"},sqlSessionFactoryRef = "writeSqlSessionFactory")
public class MyBatisDbBConfig { @Autowired
@Qualifier("writeDataSource")
private DataSource dataSource; @Bean
public SqlSessionFactory writeSqlSessionFactory() throws Exception{
SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resource=resolver.getResources("classpath:mybatis/write/*.xml");
sqlSessionFactoryBean.setMapperLocations(resource); return sqlSessionFactoryBean.getObject();
} @Bean
public SqlSessionTemplate writeSqlSession() throws Exception{
SqlSessionTemplate sqlSessionTemplate=new SqlSessionTemplate(writeSqlSessionFactory()); return sqlSessionTemplate;
} }
3、read包下的dao接口
public interface StudentReadDao {
List<Student> getStudentList();
Student getById(long id);
}
4、wite包下的dao接口
public interface StudentWriteDao {
int delete(long id);
int insert(Student student);
int update(Student student);
}
5、分别创建读写的mapper文件。我本地分别创建了:resources/mybatis/read/studentdao.xml、/resources/mybatis/write/studentdao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhangfei.dao.read.StudentReadDao">
<select id="getStudentList" resultType="com.zhangfei.entity.Student">
select * from student;
</select> <select id="getById" resultType="com.zhangfei.entity.Student">
select * from student where id=#{id};
</select> </mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhangfei.dao.write.StudentWriteDao"> <insert id="insert" parameterType="com.zhangfei.entity.Student">
insert into student (name,age) values (#{name},#{age})
</insert> <update id="update" parameterType="com.zhangfei.entity.Student">
update student set name=#{name},age=#{age} where id=#{id}
</update> <delete id="delete" parameterType="long">
delete from student where id=#{id}
</delete>
</mapper>
OK。以上几部就搞定了读写分离的准备工作,接着就可以在controller里调用了。 准备工作完成后,还有重要的一点就是需要在程序入口处排除springboot自动属性提供的数据源 @SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@RestController
@RequestMapping("/student")
public class StudentController { @Autowired
StudentReadDao studentDao; @GetMapping("/getbyid/{id}/")
public Student getById(@PathVariable("id")long id){ Student student=studentDao.getById(id);
return student;
} @GetMapping("/all/")
public List<Student> getAll(){
return studentDao.getStudentList();
} }
总结
好了,基本上又是3分钟就搞定了SpringBoot+MyBatis多数据源或者叫做读写分离的工作。那么不知道你又没有反问我们手动创建的DataSource具体类型是什么呢? 这里我们在这里只写了javax.sql.DataSource接口。 我本地用的是springboot 2.0.2 ,当前 DataSourceBuilder 只支持3种类型的数据源: com.zaxxer.hikari.HikariDataSource、org.apache.tomcat.jdbc.pool.DataSource、org.apache.commons.dbcp2.BasicDataSource。可以在DataSourceBuilder类中看到相关代码。那么现在这种情况因为我们引用的内嵌tomcat,所以我们这里返回的数据源类型是org.apache.tomcat.jdbc.pool.DataSource。 可以用instanceof验证一下具体的数据源类型。
spring boot(四) 多数据源的更多相关文章
- Spring Boot(四) Mybatis-MySql
Spring Boot(四) Mybatis-MySql 0.准备数据库表 -- ---------------------------- -- Table structure for person ...
- Spring Boot配置多数据源并实现Druid自动切换
原文:https://blog.csdn.net/acquaintanceship/article/details/75350653 Spring Boot配置多数据源配置yml文件主数据源配置从数据 ...
- spring boot项目自定义数据源,mybatisplus分页、逻辑删除无效解决方法
Spring Boot项目中数据源的配置可以通过两种方式实现: 1.application.yml或者application.properties配置 2.注入DataSource及SqlSessio ...
- Spring Boot与多数据源那点事儿~
持续原创输出,点击上方蓝字关注我 目录 前言 写这篇文章的目的 什么是多数据源? 何时用到多数据源? 整合单一的数据源 整合Mybatis 多数据源如何整合? 什么是动态数据源? 数据源切换如何保证线 ...
- Spring Boot + Druid 多数据源绑定
date: 2019-12-19 14:40:00 updated: 2019-12-19 15:10:00 Spring Boot + Druid 多数据源绑定 版本环境:Spring Boot 2 ...
- 工具篇-Spring boot JPA多数据源
写这篇博文是因为这个东西坑太多,首先说明下边实现的多数据源不是动态切换的,应该算是静态的. 坑一.pom文件 pom中spring boot以及mysql connector的版本一定要注意. < ...
- spring boot 配置双数据源mysql、sqlServer
背景:原来一直都是使用mysql数据库,在application.properties 中配置数据库信息 spring.datasource.url=jdbc:mysql://xxxx/test sp ...
- spring boot:shardingsphere多数据源,支持未分表的数据源(shardingjdbc 4.1.1)
一,为什么要给shardingsphere配置多数据源? 1,shardingjdbc默认接管了所有的数据源, 如果我们有多个非分表的库时,则最多只能设置一个为默认数据库, 其他的非分表数据库不能访问 ...
- spring boot(四):thymeleaf使用详解
在上篇文章springboot(二):web综合开发中简单介绍了一下thymeleaf,这篇文章将更加全面详细的介绍thymeleaf的使用.thymeleaf 是新一代的模板引擎,在spring4. ...
随机推荐
- comutil
使用该工具库,通常包含comsuppw.lib.kernel32.lib. _com_util::ConvertBSTRToString 将VT_BSTR类型转换为普通字符串.
- spark streaming中维护kafka偏移量到外部介质
spark streaming中维护kafka偏移量到外部介质 以kafka偏移量维护到redis为例. redis存储格式 使用的数据结构为string,其中key为topic:partition, ...
- RequireJS简单实用说明
OM前端框架说明 om前端框架采用RequireJS,RequireJS 是一个JavaScript模块加载器.它非常适合在浏览器中使用, 它非常适合在浏览器中使用,但它也可以用在其他脚本环境, 就 ...
- Java工作原理:JVM,内存回收及其他
JAVA虚拟机系列文章 http://developer.51cto.com/art/201001/176550.htm Java语言引入了Java虚拟机,具有跨平台运行的功能,能够很好地适应各种We ...
- node06
1.数据库: server端:数据存在 client端:管理工具,node mysql内有两个单位: 库:类似文件夹,容纳表 表:存储数据 行:一条数据 列(字段,域):一个数据项 主键:数据的唯一标 ...
- 清理 zabbix 历史数据, 缩减 mysql 空间
zabbix 由于历史数据过大, 因此导致磁盘空间暴涨, 下面是结局方法步骤 1. 停止 ZABBIX SERER 操作 [root@gd02-qa-plxt2-nodomain-web-95 ~] ...
- mongodb建立索引
创建索引 索引:以提升查询速度 语法:db.集合.ensureIndex({属性:1}),1表示升序,-1表示降序 具体操作:db.t255.ensureIndex({name:1}) db.t1.f ...
- position 几个属性的作用
//定位一般都会配合left 和 top 一起使用; //静态定位 : 元素默认位置; 不脱标 不常用position:static; //相对定位 : 相对于元素本身之前的位置进行定位;不脱标pos ...
- django 标签的使用
首先重建一个common的app 然后创建__init__使common成为一个包 注意templatetags 名字使固定的 并在下面创建一个名字为fitter的过滤器 注册过滤器app htm ...
- OO第一次博客作业
OO第一次博客作业 一.三次作业的bug反省 1.自己发现别人的问题 (1)输入处理的问题,比如第一次作业,主要就是处理输入的字符串,然后有同学的正则表达式有问题,则对于一些错误输入就不能正确判断. ...