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. ...
随机推荐
- 打包java程序生成exe
打包java程序生成exe 目标 我们知道c++的控制台程序编译运行以后就会生成一个exe可执行文件,在电脑上可以直接双击运行,但是java是跨平台的语言,编译运行以后的字节码文件.class是和平台 ...
- 一文教你看懂大数据的技术生态圈:Hadoop,hive,spark
转自:https://www.cnblogs.com/reed/p/7730360.html 大数据本身是个很宽泛的概念,Hadoop生态圈(或者泛生态圈)基本上都是为了处理超过单机尺度的数据处理而诞 ...
- Java 读取excel 文件流
public static void initType(String path) { try { //1 获取excel文件流 excel xls 文件 暂不支持xlsx if (path.conta ...
- 干货分享:Neutron的PPT,帮助你理解Neutron的各种细节
深入解析Neutron http://files.cnblogs.com/popsuper1982/Neutron.pptx 经典的三节点部署 架构 怎么理解? 更加深入:Tap Interface ...
- Java笔试题:给定一个ReadOnlyClass的对象roc,能否把这个对象的age值改成30?
在Java笔试面试中,经常会遇到代码题,今天我们就来看一则Java代码笔试题. 有如下代码: Class ReadOnlyClass { private Integer age=20; public ...
- [Swift]LeetCode20. 有效的括号 | Valid Parentheses
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...
- [Swift]LeetCode139. 单词拆分 | Word Break
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine ...
- [Swift]LeetCode303. 区域和检索 - 数组不可变 | Range Sum Query - Immutable
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...
- [Swift]LeetCode398. 随机数索引 | Random Pick Index
Given an array of integers with possible duplicates, randomly output the index of a given target num ...
- Python档案袋(异常与异常捕获 )
无异常捕获 程序遇到异常会中断 print( xxx ) print("---- 完 -----") 得到结果为: 有异常捕获 程序遇到异常会进入异常处理,并继续执行下面程序 tr ...