本文共 5737 字,大约阅读时间需要 19 分钟。
点击上方 Java后端,选择 设为星标
优质文章,及时送达作者 | hy_xiaobin
来源 | juejin.im/post/5d8705e65188253f4b629f47表名 t_user
表中分别添加两条不同数据,方便测试 主数据库记录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(); } }
在需要切换数据的Dao添加此注解
package com.xiaobin.annotation; import java.lang.annotation.*; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface DataSource { String name() default ""; }
@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); } }
@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(); } } }
更具路径传值,进行主从数据源切换
学Java,请关注公众号:Java后端
喜 欢 文 章 , 点 个 在看转载地址:http://jeeav.baihongyu.com/