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. ...
随机推荐
- 201771010126 王燕《面向对象程序设计(Java)》第九周学习总结
实验九 异常.断言与日志 实验时间 2018-10-25 1.实验目的与要求 (1) 掌握java异常处理技术: 异常积极处理方法:使用try子句捕获异常 异常小计处理方法:抛出throw异常类 (2 ...
- Java内存模型锦集
[内存操作与内存屏障] 内存模型操作: lock(锁定) : 作用与主内存的变量, 它把一个变量标识为一条线程独占的状态 unlock(解锁) : 作用于主内存变量, 它把一个处于锁定状态的变量释放出 ...
- 03-es6语法 Promise 和 es8语法 async await 的了解和基本使用
//Promise // 1.说明 : Promise 是 es6 中提出的新语法 // 2.作用 : 用 '用户编写同步代码' 的方式 '处理异步' 的一种解决方案 // 3.以前 : 处理异步 , ...
- Android Studio 直播弹幕
我只是搬运:https://blog.csdn.net/HighForehead/article/details/55520199 写的很好很详细,挺有参考价值的 demo直通车:https://do ...
- idea远程打断点
(1)用如下方式启动jar java -Xdebug -Xrunjdwp:transport=dt_socket,address=5005,server=y,suspend=y -jar durati ...
- C# 窗体打开拖动到窗体的文件
private void Form3_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats ...
- 基于Java的ArrayList和LinkedList的实现与总结
一.定义MyList接口,包含列表常见方法: import java.util.Iterator; /** * 线性表(列表)的接口定义 */ public interface MyList<T ...
- [Swift]LeetCode459. 重复的子字符串 | Repeated Substring Pattern
Given a non-empty string check if it can be constructed by taking a substring of it and appending mu ...
- [Swift]LeetCode654. 最大二叉树 | Maximum Binary Tree
Given an integer array with no duplicates. A maximum tree building on this array is defined as follo ...
- [Swift]LeetCode835. 图像重叠 | Image Overlap
Two images A and B are given, represented as binary, square matrices of the same size. (A binary ma ...