博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
boot jndi数据源 spring_MyBatis 多数据源读写分离(注解实现)
阅读量:5253 次
发布时间:2019-06-14

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

点击上方 Java后端,选择 设为星标

优质文章,及时送达
fe740e7138ee0f36272aa623b1ed60ed.png

作者 | hy_xiaobin

来源 | juejin.im/post/5d8705e65188253f4b629f47

首 先需 要建立两个库进行测试,我这里使用的是master_test和slave_test两个库,两张库都有一张同样的表(偷懒,喜喜),表结构

表名  t_user

6a3294e82c940494086cc68e54eb32d4.png

表中分别添加两条不同数据,方便测试 主数据库记录name为xiaobin,从库为xiaoliu 开始使用Springboot 整合mybatis,首先引入pom文件

xml version="1.0" encoding="UTF-8"?> 
   
4.0.0modelVersion>    
       
org.springframework.bootgroupId>        
spring-boot-starter-parentartifactId>        
2.1.4.RELEASEversion>    parent>    
com.xiaobingroupId>    
mysql_master_slaveartifactId>    
1.0-SNAPSHOTversion>    
       
1.8java.version>        
1.18.6lombok.version>        
1.3.2mybatis.version>        
1.18.6lombox.version>    properties>    
               
           
org.springframework.bootgroupId>            
spring-boot-starter-webartifactId>        dependency>                
           
org.projectlombokgroupId>            
lombokartifactId>            
${lombok.version}version>        dependency>                
           
org.springframework.bootgroupId>            
spring-boot-starter-testartifactId>        dependency>                
           
org.projectlombokgroupId>            
lombokartifactId>            
${lombox.version}version>        dependency>                
           
org.mybatis.spring.bootgroupId>            
mybatis-spring-boot-starterartifactId>            
${mybatis.version}version>        dependency>                
           
mysqlgroupId>            
mysql-connector-javaartifactId>        dependency>        
           
org.springframework.bootgroupId>            
spring-boot-starter-jdbcartifactId>        dependency>                
           
com.alibabagroupId>            
druid-spring-boot-starterartifactId>            
1.1.10version>        dependency>                
           
org.springframework.bootgroupId>            
spring-boot-starter-aopartifactId>        dependency>    dependencies> project>

动态数据源配置

这里使用的数据源为druid,实现数据源之间的切换用@DataSource自定义注解,配置Aop进行切换 application.yml 配置文件

spring:     datasource:         type: com.alibaba.druid.pool.DruidDataSource         druid:           xiaobin-master:             driverClassName: com.mysql.jdbc.Driver             username: root             password: root             url: jdbc:mysql://localhost:3306/master_test?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8           xiaobin-slave:             driverClassName: com.mysql.jdbc.Driver             username: root             password: root             url: jdbc:mysql://localhost:3306/slave_test?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8 mybatis:   mapper-locations: classpath:mapper/*.xml

多数据源配置类

@Configuration @Component public class DynamicDataSourceConfig {
    @Bean     @ConfigurationProperties("spring.datasource.druid.xiaobin-master")     public DataSource xiaobinMasterDataSource(){
        return DruidDataSourceBuilder.create().build();     }     @Bean     @ConfigurationProperties("spring.datasource.druid.xiaobin-slave")     public DataSource xiaobinSlaveDataSource(){
        return DruidDataSourceBuilder.create().build();     }     @Bean     @Primary     public DynamicDataSource dataSource(DataSource xiaobinMasterDataSource, DataSource xiaobinSlaveDataSource) {
        Map targetDataSources = new HashMap<>();         targetDataSources.put("xiaobin-master",xiaobinMasterDataSource);         targetDataSources.put("xiaobin-slave", xiaobinSlaveDataSource);return new DynamicDataSource(xiaobinMasterDataSource, targetDataSources);     } }

动态数据源切换类

public class DynamicDataSource  extends AbstractRoutingDataSource {
    private static final ThreadLocal contextHolder = new ThreadLocal<>();public DynamicDataSource(DataSource defaultTargetDataSource, Map targetDataSources) {
super.setDefaultTargetDataSource(defaultTargetDataSource);super.setTargetDataSources(targetDataSources);super.afterPropertiesSet();     }@Overrideprotected Object determineCurrentLookupKey() {
return getDataSource();     }public static void setDataSource(String dataSource) {
        contextHolder.set(dataSource);     }public static String getDataSource() {
return contextHolder.get();     }public static void clearDataSource() {
        contextHolder.remove();     } }

自定义@DataSource注解

在需要切换数据的Dao添加此注解

package com.xiaobin.annotation; import java.lang.annotation.*; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface DataSource {
    String name() default ""; }

Aop切面类配置

@Aspect @Component public class DataSourceAspect {
    @Pointcut("@annotation(com.xiaobin.annotation.DataSource)")     public void dataSourcePointCut() {
    }     @Around("dataSourcePointCut()")     public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();         Method method = signature.getMethod();         DataSource dataSource = method.getAnnotation(DataSource.class);         if(dataSource == null){
            DynamicDataSource.setDataSource("xiaobin-master");         }else {
            DynamicDataSource.setDataSource(dataSource.name());         }         try {
            return point.proceed();         } finally {
            DynamicDataSource.clearDataSource();         }     } }

启动配置注解信息,重要(不然运行会报错)

@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class}) @MapperScan(basePackages = "com.xiaobin.mapper") @Import({DynamicDataSourceConfig.class}) public class StartApp {
    public static void main(String[] args) {
        SpringApplication.run(StartApp.class);     } }
 

测试controller

@RestController @RequestMapping public class UserController {
    @Autowired     private UserMapper userMapper;     @GetMapping("/{name}/list")     public List list(@PathVariable("name")String name){
if(name.equals("master")){
return userMapper.queryAllWithMaster();         }else{
return userMapper.queryAllWithSlave();         }     } }

效果图

更具路径传值,进行主从数据源切换

74f565d8bf5ce61888f3265f6641068a.png

b82d78914945cedb203467a39e183ee4.png

目录结构

3b4c66ccaae1998be836177f32d23f82.png

源码地址(数据库需要自己创建) https://gitee.com/MyXiaoXiaoBin/learning-to-share/tree/master/mysql_master_slave

-END-

b069fea83b69e46c58cc1f7f3aac752d.png

 学Java,请关注公众号:Java后端 

在看 
d9fe6df7c58b75bb49817813a23ec923.png

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

你可能感兴趣的文章
[ROS] Chinese MOOC || Chapter-4.4 Action
查看>>
简单的数据库操作
查看>>
iOS-解决iOS8及以上设置applicationIconBadgeNumber报错的问题
查看>>
亡灵序曲-The Dawn
查看>>
Redmine
查看>>
帧的最小长度 CSMA/CD
查看>>
xib文件加载后设置frame无效问题
查看>>
编程算法 - 左旋转字符串 代码(C)
查看>>
IOS解析XML
查看>>
Python3多线程爬取meizitu的图片
查看>>
树状数组及其他特别简单的扩展
查看>>
zookeeper适用场景:分布式锁实现
查看>>
110104_LC-Display(液晶显示屏)
查看>>
httpd_Vhosts文件的配置
查看>>
php学习笔记
查看>>
普通求素数和线性筛素数
查看>>
PHP截取中英文混合字符
查看>>
【洛谷P1816 忠诚】线段树
查看>>
电子眼抓拍大解密
查看>>
poj 1331 Multiply
查看>>