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. ...
随机推荐
- C#三目运算符
在编写项目的时候,会经常用到 if else 判断语句,但有些简单的判断或赋值,可以通过三目运算符来完成! 例如: int sex=0; string sexText=""; if ...
- 查找datatable 中的重复记录(只查询一个字段)
StringBuilder str = new StringBuilder(); var res = new ResParameter() { code = ResponseCode.exceptio ...
- Java for Android 第二周课上实验一
(一)命令行下程序开发 (二)IDEA下程序开发调试 Mac OS系统下使用的IDEA为 Netbeans (三)测试题我的学号后两位为10 使用简单的PHP小程序得我的题目为2:实现简单四则运算(能 ...
- centos7zabbix-agen安装
安装包下载地址:http://www.zabbix.com/download.php 下载对应rpm包 http://repo.zabbix.com/zabbix/ wget http://r ...
- 【RL-TCPnet网络教程】第14章 RL-TCPnet之TCP客户端
第14章 RL-TCPnet之TCP客户端 本章节为大家讲解RL-TCPnet的TCP客户端实现,学习本章节前,务必要优先学习第12章TCP传输控制协议基础知识.有了这些基础知识之后,再搞本 ...
- &和&&的共同点和区别、Java字符含义和Java创建对象的几种方式
一.&和&&的共同点和区别 1.&和&&的联系(共同点): &和&&都可以用作逻辑与运算符,但是要看使用时的具体条件来决定. 操 ...
- 【从零开始搭建自己的.NET Core Api框架】(一)创建项目并集成swagger:1.1 创建
系列目录 一. 创建项目并集成swagger 1.1 创建 1.2 完善 二. 搭建项目整体架构 三. 集成轻量级ORM框架——SqlSugar 3.1 搭建环境 3.2 实战篇:利用SqlSuga ...
- Java数据结构和算法 - 哈希表
Q: 如何快速地存取员工的信息? A: 假设现在要写一个程序,存取一个公司的员工记录,这个小公司大约有1000个员工,每个员工记录需要1024个字节的存储空间,因此整个数据库的大小约为1MB.一般的计 ...
- presto中ldaps配置完整流程
最近开始转战presto,至于前面章节中的Hbase,我也会持续更新,喜欢我的可以关注我.关于这个流程,我看过阿里云的的一篇文章,但看后还是不知所云,就写下了这篇博客,大家感兴趣的可以访问那篇文章—— ...
- IntelliJ IDEA 自定义方法注解模板
最近没啥事开始正式用Eclipse 转入 idea工具阵营,毕竟有70%的开发者在使用idea开发,所以它的魅力可想而知.刚上手大概有一天,就知道它为啥取名为 intelli(智能化)了,确实很智能, ...