您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關Mybatis中怎么利用注解實現多數據源讀寫分離,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
首先需要建立兩個庫進行測試,我這里使用的是master_test和slave_test兩個庫,兩張庫都有一張同樣的表(偷懶,喜喜),表結構
表名 t_user
| 字段名 | 類型 | 備注 || :------: | :------: | :------: || id | int | 主鍵自增ID || name | varchar | 名稱 |
表中分別添加兩條不同數據,方便測試
主數據庫記錄name為xiaobin,從庫為xiaoliu
開始使用Springboot 整合mybatis,首先引入pom文件
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.4.RELEASE</version> </parent> <groupId>com.xiaobin</groupId> <artifactId>mysql_master_slave</artifactId> <version>1.0-SNAPSHOT</version> <properties> <java.version>1.8</java.version> <lombok.version>1.18.6</lombok.version> <mybatis.version>1.3.2</mybatis.version> <lombox.version>1.18.6</lombox.version> </properties> <dependencies> <!-- 添加web啟動坐標 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 添加lombok工具坐標 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> </dependency> <!-- 添加springboot 測試坐標 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <!-- 添加lombox 測試坐標 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombox.version}</version> </dependency> <!-- 添加mybatis依賴坐標 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis.version}</version> </dependency> <!-- 添加mysql驅動器坐標 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- 添加druid數據源坐標 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> <!-- 添加AOP坐標 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </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=utf8mybatis: mapper-locations: classpath:mapper/*.xml
多數據源配置類
package com.xiaobin.config;import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Primary;import org.springframework.stereotype.Component;import javax.sql.DataSource;import java.util.HashMap;import java.util.Map;/** * 創建時間: 2019/9/22 11:42 * 備注:多數據源配置信息 * 碼農自學交流小群:260532022,歡迎大家的加入,分享學習是一件開心事 **/@Configuration@Componentpublic 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<Object, Object> targetDataSources = new HashMap<>(); targetDataSources.put("xiaobin-master",xiaobinMasterDataSource); targetDataSources.put("xiaobin-slave", xiaobinSlaveDataSource); return new DynamicDataSource(xiaobinMasterDataSource, targetDataSources); }}
動態數據源切換類
package com.xiaobin.config;import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;import org.springframework.lang.Nullable;import javax.sql.DataSource;import java.util.Map;/** * 創建時間: 2019/9/22 11:51 * 備注:動態數據源 * 碼農自學交流小群:260532022,歡迎大家的加入,分享學習是一件開心事 **/public class DynamicDataSource extends AbstractRoutingDataSource { private static final ThreadLocal<String> contextHolder = new ThreadLocal<>(); public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) { super.setDefaultTargetDataSource(defaultTargetDataSource); super.setTargetDataSources(targetDataSources); super.afterPropertiesSet(); } @Override protected 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.*;/** * 創建時間: 2019/9/22 11:53 * 備注:自定義數據源選擇注解 * 碼農自學交流小群:260532022,歡迎大家的加入,分享學習是一件開心事 **/@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface DataSource { String name() default "";}
Aop切面類配置
package com.xiaobin.aspect;import com.xiaobin.annotation.DataSource;import com.xiaobin.config.DynamicDataSource;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Pointcut;import org.aspectj.lang.reflect.MethodSignature;import org.springframework.stereotype.Component;import java.lang.reflect.Method;/** * 創建時間: 2019/9/22 11:54 * 備注: * 碼農自學交流小群:260532022,歡迎大家的加入,分享學習是一件開心事 **/@Aspect@Componentpublic 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(); } }}
啟動配置注解信息,重要(不然運行會報錯)
package com.xiaobin;import com.xiaobin.config.DynamicDataSourceConfig;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;import org.springframework.context.annotation.Import;/** * 創建時間: 2019/9/22 11:17 * 備注: * 碼農自學交流小群:260532022,歡迎大家的加入,分享學習是一件開心事 **/@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
package com.xiaobin.api;import com.xiaobin.Entity.TUser;import com.xiaobin.mapper.UserMapper;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.List; @RestController@RequestMappingpublic class UserController { @Autowired private UserMapper userMapper; @GetMapping("/{name}/list") public List<TUser> list(@PathVariable("name")String name){ if(name.equals("master")){ return userMapper.queryAllWithMaster(); }else{ return userMapper.queryAllWithSlave(); } }}
看完上述內容,你們對Mybatis中怎么利用注解實現多數據源讀寫分離有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。