您好,登錄后才能下訂單哦!
本篇文章為大家展示了mybatis中怎么實現讀寫分離,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
1、spring aop實現
首先application-test.yml增加如下數據源的配置
spring: datasource: master: jdbc-url: jdbc:mysql://master域名:3306/test username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver slave1: jdbc-url: jdbc:mysql://slave域名:3306/test username: root # 只讀賬戶 password: 123456 driver-class-name: com.mysql.jdbc.Driver slave2: jdbc-url: jdbc:mysql://slave域名:3306/test username: root # 只讀賬戶 password: 123456 driver-class-name: com.mysql.jdbc.Driver
package com.cjs.example.enums; public enum DBTypeEnum { MASTER, SLAVE1, SLAVE2; }
定義ThreadLocal上下文,將當前線程的數據源進行動態修改
public class DBContextHolder { private static volatile ThreadLocal<DBTypeEnum> contextHolder = new ThreadLocal<>(); public static synchronized void set(DBTypeEnum dbType) { contextHolder.set(dbType); } public static synchronized DBTypeEnum get() { return contextHolder.get(); } public static void master() { set(DBTypeEnum.MASTER); } public static void slave() { set(DBTypeEnum.SLAVE1); } public static void slave2(){ set(DBTypeEnum.SLAVE2); } // 清除數據源名 public static void clearDB() { contextHolder.remove(); } }
重寫mybatis數據源路由接口,在此修改數據源為我們上一塊代碼設置的上下文的數據源
public class MyRoutingDataSource extends AbstractRoutingDataSource { @Nullable @Override protected Object determineCurrentLookupKey() { DBTypeEnum dbTypeEnum=DBContextHolder.get(); return dbTypeEnum; } }
將yml配置的多數據源手動指定注入
@Configuration public class DataSourceConfig { @Bean @ConfigurationProperties("spring.datasource.master") public DataSource masterDataSource() { return DataSourceBuilder.create().build(); } @Bean @ConfigurationProperties("spring.datasource.slave1") public DataSource slave1DataSource() { return DataSourceBuilder.create().build(); } @Bean public DataSource myRoutingDataSource(@Qualifier("masterDataSource") DataSource masterDataSource, @Qualifier("slave1DataSource") DataSource slave1DataSource) { Map<Object, Object> targetDataSources = new HashMap<>(); targetDataSources.put(DBTypeEnum.MASTER, masterDataSource); targetDataSources.put(DBTypeEnum.SLAVE1, slave1DataSource); MyRoutingDataSource myRoutingDataSource = new MyRoutingDataSource(); myRoutingDataSource.setDefaultTargetDataSource(masterDataSource); myRoutingDataSource.setTargetDataSources(targetDataSources); return myRoutingDataSource; } }
sqlsession注入以上我們配置的datasource路由
@EnableTransactionManagement @Configuration @Import({TableSegInterceptor.class}) public class MyBatisConfig { @Resource(name = "myRoutingDataSource") private DataSource myRoutingDataSource; @Autowired private MybatisConfigProperty mybatisConfigProperty; @Autowired private TableSegInterceptor tableSegInterceptor; @Bean public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(myRoutingDataSource); // SpringBoot項目集成mybatis打包為jar運行時setTypeAliasesPackage無效解決 VFS.addImplClass(SpringBootVFS.class); sqlSessionFactoryBean.setMapperLocations( new PathMatchingResourcePatternResolver().getResources(mybatisConfigProperty.getMapperLocations())); sqlSessionFactoryBean.setTypeAliasesPackage(mybatisConfigProperty.getTypeAliasesPackage()); sqlSessionFactoryBean.setConfigLocation( new PathMatchingResourcePatternResolver().getResource(mybatisConfigProperty.getConfigLocation())); sqlSessionFactoryBean.setPlugins(new Interceptor[]{tableSegInterceptor}); return sqlSessionFactoryBean.getObject(); } @Bean public PlatformTransactionManager platformTransactionManager() { return new DataSourceTransactionManager(myRoutingDataSource); } }
spring aop攔截指定前綴的service方法,并設置對應所屬的上下文
@Aspect @Component public class DataSourceAop { @Pointcut("!@annotation(com.ask.student.interceptor.annotation.Master) " + "&& (execution(* com.ask.student.service..*.select*(..)) " + "|| execution(* com.ask.student.service..*.get*(..))" + "|| execution(* com.ask.student.service..*.find*(..))" + ")") public void readPointcut() { } @Pointcut("@annotation(com.ask.student.interceptor.annotation.Master) " + "|| execution(* com.ask.student.service..*.insert*(..)) " + "|| execution(* com.ask.student.service..*.clean*(..)) " + "|| execution(* com.ask.student.service..*.reset*(..)) " + "|| execution(* com.ask.student.service..*.add*(..)) " + "|| execution(* com.ask.student.service..*.update*(..)) " + "|| execution(* com.ask.student.service..*.edit*(..)) " + "|| execution(* com.ask.student.service..*.delete*(..)) " + "|| execution(* com.ask.student.service..*.remove*(..))") public void writePointcut() { } @Before("readPointcut()") public void read() { DBContextHolder.slave(); } @Before("writePointcut()") public void write() { DBContextHolder.master(); } @After("readPointcut()||writePointcut()") public void afterSwitchDS(){ DBContextHolder.clearDB(); } }
以上最后一個方法的作用,在攔截器中獲取后及時清除避免導致來回切換當前線程變量延遲問題導致某些操作的數據源錯誤
DBContextHolder.clearDB();
@After("readPointcut()||writePointcut()")
public void afterSwitchDS(){
DBContextHolder.clearDB();
}
這個方式配置簡單,代碼少,很多事情mybatis-plus都已經做好了,推薦使用
yml配置如下
datasource: dynamic: primary: master #設置默認的數據源或者數據源組,默認值即為master strict: false #設置嚴格模式,默認false不啟動. 啟動后在未匹配到指定數據源時候會拋出異常,不啟動則使用默認數據源. datasource: master: url: jdbc:mysql://xxx:3306/db0?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai username: admin password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver type: com.zaxxer.hikari.HikariDataSource hikari: minimum-idle: 5 maximum-pool-size: 15 auto-commit: true idle-timeout: 30000 pool-name: springHikariCP max-lifetime: 1800000 connection-timeout: 30000 connection-test-query: SELECT 1 slave1: url: jdbc:mysql://xxx:3306/db2?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai username: admin password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver type: com.zaxxer.hikari.HikariDataSource hikari: minimum-idle: 5 maximum-pool-size: 15 auto-commit: true idle-timeout: 30000 pool-name: springHikariCP max-lifetime: 1800000 connection-timeout: 30000 connection-test-query: SELECT 1 slave2: url: jdbc:mysql://xxx:3306/db3?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai username: admin password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver type: com.zaxxer.hikari.HikariDataSource hikari: minimum-idle: 5 maximum-pool-size: 15 auto-commit: true idle-timeout: 30000 pool-name: springHikariCP max-lifetime: 1800000 connection-timeout: 30000 connection-test-query: SELECT 1
使用起來非常簡單,只需要加上這個master的注解即可
@Override @DS("master") public DestMedia getOneByCodeFromEpg(String code) { QueryWrapper queryWrapper = new QueryWrapper(); queryWrapper.eq("code", code); return super.getOne(queryWrapper); }
上述內容就是mybatis中怎么實現讀寫分離,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。