91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

mybatis中怎么實現讀寫分離

發布時間:2021-08-04 13:48:17 來源:億速云 閱讀:144 作者:Leah 欄目:開發技術

本篇文章為大家展示了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();

}

2、mybatis-plus的實現方式

這個方式配置簡單,代碼少,很多事情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中怎么實現讀寫分離,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

奎屯市| 成安县| 罗田县| 清徐县| 宁南县| 济源市| 云和县| 多伦县| 灵寿县| 辰溪县| 乌拉特前旗| 周口市| 大兴区| 利辛县| 富顺县| 灵丘县| 岱山县| 沅江市| 南木林县| 安图县| 遂宁市| 杂多县| 磐石市| 双城市| 资溪县| 贵溪市| 孟州市| 大余县| 苏尼特左旗| 台州市| 朝阳市| 农安县| 当雄县| 翁源县| 奉贤区| 德昌县| 金湖县| 武功县| 莲花县| 马公市| 定远县|