iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >如何在Spring中使用MyBatis实现数据的读写分离
  • 217
分享到

如何在Spring中使用MyBatis实现数据的读写分离

springmybatis读写分离 2023-05-31 10:05:17 217人浏览 泡泡鱼
摘要

如何在spring中使用mybatis实现数据的读写分离?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。其实现原理如下:通过Spring aop对dao层接口进行

如何在spring中使用mybatis实现数据的读写分离?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

其实现原理如下:

  1. 通过Spring aop对dao层接口进行拦截,并对需要指定数据源的接口在ThradLocal中设置其数据源类型及名称

  2. 通过MyBatsi的插件,对根据更新或者查询操作在ThreadLocal中设置数据源(dao层没有指定的情况下)

  3. 继承AbstractRoutingDataSource类。

在此直接写死使用HikariCP作为数据源

其实现步骤如下:

  1. 定义其数据源配置文件并进行解析为数据源

  2. 定义AbstractRoutingDataSource类及其它注解

  3. 定义Aop拦截

  4. 定义MyBatis插件

  5. 整合在一起

1.配置及解析类

其配置参数直接使用HikariCP的配置,其具体参数可以参考HikariCP。

在此使用yaml格式,名称为datasource.yaml,内容如下:

dds: write:  jdbcUrl: jdbc:mysql://localhost:3306/order  passWord: liu123  username: root  maxPoolSize: 10  minIdle: 3  poolName: master read:  - jdbcUrl: jdbc:Mysql://localhost:3306/test   password: liu123   username: root   maxPoolSize: 10   minIdle: 3   poolName: slave1  - jdbcUrl: jdbc:mysql://localhost:3306/test2   password: liu123   username: root   maxPoolSize: 10   minIdle: 3   poolName: slave2

定义该配置所对应的Bean,名称为DBConfig,内容如下:

@Component@ConfigurationProperties(locations = "classpath:datasource.yaml", prefix = "dds")public class DBConfig {  private List<HikariConfig> read;  private HikariConfig write;  public List<HikariConfig> getRead() {    return read;  }  public void setRead(List<HikariConfig> read) {    this.read = read;  }  public HikariConfig getWrite() {    return write;  }  public void setWrite(HikariConfig write) {    this.write = write;  }}

把配置转换为DataSource的工具类,名称:DataSourceUtil,内容如下:

import com.zaxxer.hikari.HikariConfig;import com.zaxxer.hikari.HikariDataSource;import javax.sql.DataSource;import java.util.ArrayList;import java.util.List;public class DataSourceUtil {  public static DataSource getDataSource(HikariConfig config) {    return new HikariDataSource(config);  }  public static List<DataSource> getDataSource(List<HikariConfig> configs) {    List<DataSource> result = null;    if (configs != null && configs.size() > 0) {      result = new ArrayList<>(configs.size());      for (HikariConfig config : configs) {        result.add(getDataSource(config));      }    } else {      result = new ArrayList<>(0);    }    return result;  }}

2.注解及动态数据源

定义注解@DataSource,其用于需要对个别方法指定其要使用的数据源(如某个读操作需要在master上执行,但另一读方法b需要在读数据源的具体一台上面执行)

@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface DataSource {    DataSourceType type() default DataSourceType.WRITE;    String name() default "";}

定义数据源类型,分为两种:READ,WRITE,内容如下:

public enum DataSourceType {  READ, WRITE;}

定义保存这此共享信息的类DynamicDataSourceHolder,在其中定义了两个ThreadLocal和一个map,holder用于保存当前线程的数据源类型(读或者写),pool用于保存数据源名称(如果指定),其内容如下:

import java.util.Map;import java.util.concurrent.ConcurrentHashMap;public class DynamicDataSourceHolder {  private static final Map<String, DataSourceType> cache = new ConcurrentHashMap<>();  private static final ThreadLocal<DataSourceType> holder = new ThreadLocal<>();  private static final ThreadLocal<String> pool = new ThreadLocal<>();  public static void putToCache(String key, DataSourceType dataSourceType) {    cache.put(key,dataSourceType);  }  public static DataSourceType getFromCach(String key) {    return cache.get(key);  }  public static void putDataSource(DataSourceType dataSourceType) {    holder.set(dataSourceType);  }  public static DataSourceType getDataSource() {    return holder.get();  }  public static void putPoolName(String name) {    if (name != null && name.length() > 0) {      pool.set(name);    }  }  public static String getPoolName() {    return pool.get();  }  public static void clearDataSource() {    holder.remove();    pool.remove();  }}

动态数据源类为DynamicDataSoruce,其继承自AbstractRoutingDataSource,可以根据返回的key切换到相应的数据源,其内容如下:

import com.zaxxer.hikari.HikariDataSource;import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;import javax.sql.DataSource;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ThreadLocalRandom;public class DynamicDataSource extends AbstractRoutingDataSource {  private DataSource writeDataSource;  private List<DataSource> readDataSource;  private int readDataSourceSize;  private Map<String, String> dataSourceMapping = new ConcurrentHashMap<>();  @Override  public void afterPropertiesSet() {    if (this.writeDataSource == null) {      throw new IllegalArgumentException("Property 'writeDataSource' is required");    }    setDefaultTargetDataSource(writeDataSource);    Map<Object, Object> targetDataSource = new HashMap<>();    targetDataSource.put(DataSourceType.WRITE.name(), writeDataSource);    String poolName = ((HikariDataSource)writeDataSource).getPoolName();    if (poolName != null && poolName.length() > 0) {      dataSourceMapping.put(poolName,DataSourceType.WRITE.name());    }    if (this.readDataSource == null) {      readDataSourceSize = 0;    } else {      for (int i = 0; i < readDataSource.size(); i++) {        targetDataSource.put(DataSourceType.READ.name() + i, readDataSource.get(i));        poolName = ((HikariDataSource)readDataSource.get(i)).getPoolName();        if (poolName != null && poolName.length() > 0) {          dataSourceMapping.put(poolName,DataSourceType.READ.name() + i);        }      }      readDataSourceSize = readDataSource.size();    }    setTargetDataSources(targetDataSource);    super.afterPropertiesSet();  }  @Override  protected Object determineCurrentLookupKey() {    DataSourceType dataSourceType = DynamicDataSourceHolder.getDataSource();    String dataSourceName = null;    if (dataSourceType == null ||dataSourceType == DataSourceType.WRITE || readDataSourceSize == 0) {      dataSourceName = DataSourceType.WRITE.name();    } else {      String poolName = DynamicDataSourceHolder.getPoolName();      if (poolName == null) {        int idx = ThreadLocalRandom.current().nextInt(0, readDataSourceSize);        dataSourceName = DataSourceType.READ.name() + idx;      } else {        dataSourceName = dataSourceMapping.get(poolName);      }    }    DynamicDataSourceHolder.clearDataSource();    return dataSourceName;  }  public void setWriteDataSource(DataSource writeDataSource) {    this.writeDataSource = writeDataSource;  }  public void setReadDataSource(List<DataSource> readDataSource) {    this.readDataSource = readDataSource;  }}

3.AOP拦截

如果在相应的dao层做了自定义配置(指定数据源),则在些处理。解析相应方法上的@DataSource注解,如果存在,并把相应的信息保存至上面的DynamicDataSourceHolder中。在此对com.hfjy.service.order.dao包进行做拦截。内容如下:

import com.hfjy.service.order.anno.DataSource;import com.hfjy.service.order.wr.DynamicDataSourceHolder;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;import org.aspectj.lang.reflect.MethodSignature;import org.springframework.stereotype.Component;import java.lang.reflect.Method;@Aspect@Componentpublic class DynamicDataSourceAspect {  @Pointcut("execution(public * com.hfjy.service.order.dao.*.*(*))")  public void dynamic(){}  @Before(value = "dynamic()")  public void beforeOpt(JoinPoint point) {    Object target = point.getTarget();    String methodName = point.getSignature().getName();    Class<?>[] clazz = target.getClass().getInterfaces();    Class<?>[] parameterType = ((MethodSignature)point.getSignature()).getMethod().getParameterTypes();    try {      Method method = clazz[0].getMethod(methodName,parameterType);      if (method != null && method.isAnnotationPresent(DataSource.class)) {        DataSource datasource = method.getAnnotation(DataSource.class);        DynamicDataSourceHolder.putDataSource(datasource.type());        String poolName = datasource.name();        DynamicDataSourceHolder.putPoolName(poolName);        DynamicDataSourceHolder.putToCache(clazz[0].getName() + "." + methodName, datasource.type());      }    } catch (Exception e) {      e.printStackTrace();    }  }  @After(value = "dynamic()")  public void afterOpt(JoinPoint point) {    DynamicDataSourceHolder.clearDataSource();  }}

4.MyBatis插件

如果在dao层没有指定相应的要使用的数据源,则在此进行拦截,根据是更新还是查询设置数据源的类型,内容如下:

import org.apache.ibatis.executor.Executor;import org.apache.ibatis.mapping.MappedStatement;import org.apache.ibatis.mapping.SqlCommandType;import org.apache.ibatis.plugin.*;import org.apache.ibatis.session.ResultHandler;import org.apache.ibatis.session.RowBounds;import java.util.Properties;@Intercepts({    @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),    @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,        RowBounds.class, ResultHandler.class})})public class DynamicDataSourcePlugin implements Interceptor {  @Override  public Object intercept(Invocation invocation) throws Throwable {    MappedStatement ms = (MappedStatement)invocation.getArgs()[0];    DataSourceType dataSourceType = null;    if ((dataSourceType = DynamicDataSourceHolder.getFromCach(ms.getId())) == null) {      if (ms.getSqlCommandType().equals(SqlCommandType.SELECT)) {        dataSourceType = DataSourceType.READ;      } else {        dataSourceType = DataSourceType.WRITE;      }      DynamicDataSourceHolder.putToCache(ms.getId(), dataSourceType);    }    DynamicDataSourceHolder.putDataSource(dataSourceType);    return invocation.proceed();  }  @Override  public Object plugin(Object target) {    if (target instanceof Executor) {      return Plugin.wrap(target, this);    } else {      return target;    }  }  @Override  public void setProperties(Properties properties) {  }}

5.整合

在里面定义MyBatis要使用的内容及DataSource,内容如下:

import com.hfjy.service.order.wr.DBConfig;import com.hfjy.service.order.wr.DataSourceUtil;import com.hfjy.service.order.wr.DynamicDataSource;import org.apache.ibatis.session.SqlSessionFactory;import org.mybatis.spring.SqlSessionFactoryBean;import org.mybatis.spring.annotation.MapperScan;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.io.ClassPathResource;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import org.springframework.jdbc.datasource.DataSourceTransactionManager;import javax.annotation.Resource;import javax.sql.DataSource;@Configuration@MapperScan(value = "com.hfjy.service.order.dao", sqlSessionFactoryRef = "sqlSessionFactory")public class DataSourceConfig {  @Resource  private DBConfig dbConfig;  @Bean(name = "dataSource")  public DynamicDataSource dataSource() {    DynamicDataSource dataSource = new DynamicDataSource();    dataSource.setWriteDataSource(DataSourceUtil.getDataSource(dbConfig.getWrite()));    dataSource.setReadDataSource(DataSourceUtil.getDataSource(dbConfig.getRead()));    return dataSource;  }  @Bean(name = "transactionManager")  public DataSourceTransactionManager dataSourceTransactionManager(@Qualifier("dataSource") DataSource dataSource) {    return new DataSourceTransactionManager(dataSource);  }  @Bean(name = "sqlSessionFactory")  public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {    SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();    sessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));    sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()        .getResources("classpath*:mapper/*.xml"));    sessionFactoryBean.setDataSource(dataSource);    return sessionFactoryBean.getObject();  }}

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注编程网精选频道,感谢您对编程网的支持。

--结束END--

本文标题: 如何在Spring中使用MyBatis实现数据的读写分离

本文链接: https://www.lsjlt.com/news/224892.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 如何在Spring中使用MyBatis实现数据的读写分离
    如何在Spring中使用MyBatis实现数据的读写分离?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。其实现原理如下:通过Spring AOP对dao层接口进行...
    99+
    2023-05-31
    spring mybatis 读写分离
  • 在spring中使用mybatis实现对mysql数据库进行读写分离
    这期内容当中小编将会给大家带来有关在spring中使用mybatis实现对mysql数据库进行读写分离,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。前言    &n...
    99+
    2023-05-31
    spring mybatis mysql
  • Spring如何实现多数据源读写分离
    这篇文章主要介绍“Spring如何实现多数据源读写分离”,在日常操作中,相信很多人在Spring如何实现多数据源读写分离问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Spri...
    99+
    2024-04-02
  • mybatis中怎么实现读写分离
    本篇文章为大家展示了mybatis中怎么实现读写分离,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。1、spring aop实现首先application-test.yml增加如下数据源的配置spri...
    99+
    2023-06-20
  • 怎么在java中利用spring实现读写分离
    怎么在java中利用spring实现读写分离?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。1.  背景我们一般应用对数据库而言都是“读多写少”,也就说对数据库读取数据...
    99+
    2023-05-30
    spring java
  • Linux下如何使用MaxScale实现数据库读写分离
    这篇文章主要介绍Linux下如何使用MaxScale实现数据库读写分离,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!MaxScale是maridb开发的一个mysql数据中间件,其配置简单,能够实现读写分离,并且可以...
    99+
    2023-06-27
  • 带你了解mybatis如何实现读写分离
    目录1、spring aop实现2、mybatis-plus的实现方式总结1、spring aop实现 首先application-test.yml增加如下数据源的配置 spri...
    99+
    2024-04-02
  • Spring+Mybatis 实现aop数据库读写分离与多数据库源配置操作
    在数据库层面大都采用读写分离技术,就是一个Master数据库,多个Slave数据库。Master库负责数据更新和实时数据查询,Slave库当然负责非实时数据查询。因为在实际的应用中,数据库都是读多写少(读取数据的频率高,更新数据的频率相对较...
    99+
    2023-05-31
    spring mybatis 读写分离
  • 分析型数据仓库中如何实现读写分离
    这篇文章主要为大家展示了“分析型数据仓库中如何实现读写分离”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“分析型数据仓库中如何实现读写分离”这篇文章吧。和以 My...
    99+
    2024-04-02
  • SpringBoot使用JPA如何实现读写分离
    今天就跟大家聊聊有关SpringBoot使用JPA如何实现读写分离,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。JPA是什么JPA(Java Persistence API)是Sun...
    99+
    2023-05-31
    springboot jpa 读写分离
  • MySQL中如何实现读写分离
    MySQL中如何实现读写分离,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。一,创建Master数据库的配置文件vi master...
    99+
    2024-04-02
  • 如何利用mycat实现mysql数据库读写分离
    这篇文章主要介绍了如何利用mycat实现mysql数据库读写分离,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。什么是MyCAT一个彻底开源的...
    99+
    2024-04-02
  • Redis如何实现数据库读写分离详解
    前言 Redis是一种NoSQL的文档数据库,通过key-value的结构存储在内存中,Redis读的速度是110000次/s,写的速度是81000次/s,性能很高,使用范围也很广。Redis是一个key-...
    99+
    2024-04-02
  • mysql中Oneproxy如何实现读写分离
    这篇文章将为大家详细讲解有关mysql中Oneproxy如何实现读写分离,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。基本架构: 写请求全部定向到主库,数据通过日志异步复...
    99+
    2024-04-02
  • 如何将Spring的动态数据源进行读写分离
    这篇文章给大家介绍如何将Spring的动态数据源进行读写分离,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。一、创建基于ThreadLocal的动态数据源容器,保证数据源的线程安全性package com.bo...
    99+
    2023-05-31
    spring 数据源 读写分离
  • Java程序员干货学习笔记—Spring结合MyBatis实现数据库读写分离
    随着系统用户访问量的不断增加,数据库的频繁访问将成为我们系统的一大瓶颈之一。由于项目前期用户量不大,我们实现单一的数据库就能完成。但是后期单一的数据库根本无法支撑庞大的项目去访问数据库,那么如何解决这个问题呢?实际的应用中,数据库都是读多写...
    99+
    2023-06-02
  • php+mysql如何实现读写分离
    这篇“php+mysql如何实现读写分离”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“php+mysql如何实现读写分离”文...
    99+
    2023-07-05
  • maxscale + mariadb5.5如何实现读写分离
    本篇文章给大家分享的是有关maxscale + mariadb5.5如何实现读写分离,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。1、安装[r...
    99+
    2024-04-02
  • SpringBoot使用Sharding-JDBC实现数据分片和读写分离的方法
    目录一、Sharding-JDBC简介二、具体的实现方式 1、maven引用2、数据库准备3、Spring配置4、精准分片算法和范围分片算法的Java代码5、测试一、Sha...
    99+
    2024-04-02
  • SpringBoot+MyBatis+AOP实现读写分离的示例代码
    目录一、 MySQL 读写分离1.1、如何实现 MySQL 的读写分离? 1.2、MySQL 主从复制原理?1.3、MySQL 主从同步延时问题(精华)二、SpringBo...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作