全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

详解MyBatis多数据源配置(读写分离)

MyBatis多数据源配置(读写分离)

首先说明,本文的配置使用的最直接的方式,实际用起来可能会很麻烦。

实际应用中可能存在多种结合的情况,你可以理解本文的含义,不要死板的使用。

多数据源的可能情况

1.主从

通常是MySQL一主多从的情况,本文的例子就是主从的情况,但是只有两个数据源,所以采用直接配置不会太麻烦,但是不利于后续扩展,主要是作为一个例子来说明,实际操作请慎重考虑。

2.分库

当业务独立性强,数据量大的时候的,为了提高并发,可能会对表进行分库,分库后,每一个数据库都需要配置一个数据源。

这种情况可以参考本文,但是需要注意每一个数据库对应的Mapper要在不同的包下方便区分和配置。

另外分库的情况下也会存在主从的情况,如果你的数据库从库过多,就参考上面提供的方法,或者寻找其他方式解决。

Mapper分包

分库的情况下,不同的数据库的Mapper一定放在不同的包下。

主从的情况下,同一个Mapper会同时存在读写的情况,创建两个并不合适,使用同一个即可。但是这种情况下需要注意,Spring对Mapper自动生成的名字是相同的,而且类型也相同,这是就不能直接注入Mapper接口。需要通过SqlSession来解决。

Spring基础配置

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd 
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop.xsd">

  <context:component-scan base-package="com.isea533.mybatis.service"/>
  <context:property-placeholder location="classpath:config.properties"/>
  <aop:aspectj-autoproxy/>

  <import resource="spring-datasource-master.xml"/>
  <import resource="spring-datasource-slave.xml"/>
</beans>

这个文件,主要是引入了spring-datasource-master.xml和spring-datasource-slave.xml。

spring-datasource-master.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd 
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop.xsd">

  <bean id="dataSourceMaster" class="com.alibaba.druid.pool.DruidDataSource" 
    init-method="init" destroy-method="close">
    <property name="driverClassName" value="${master.jdbc.driverClass}"/>
    <property name="url" value="${master.jdbc.url}"/>
    <property name="username" value="${master.jdbc.user}"/>
    <property name="password" value="${master.jdbc.password}"/>

    <property name="filters" value="stat"/>

    <property name="maxActive" value="20"/>
    <property name="initialSize" value="1"/>
    <property name="maxWait" value="60000"/>
    <property name="minIdle" value="1"/>

    <property name="timeBetweenEvictionRunsMillis" value="60000"/>
    <property name="minEvictableIdleTimeMillis" value="300000"/>

    <property name="validationQuery" value="SELECT 'x'"/>
    <property name="testWhileIdle" value="true"/>
    <property name="testOnBorrow" value="false"/>
    <property name="testOnReturn" value="false"/>
  </bean>

  <bean id="sqlSessionFactory1" 
    class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSourceMaster"/>
    <property name="mapperLocations">
      <array>
        <value>classpath:mapper/*.xml</value>
      </array>
    </property>
  </bean>

  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.isea533.mybatis.mapper"/>
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory1"/>
  </bean>

  <bean id="sqlSessionMaster" class="org.mybatis.spring.SqlSessionTemplate" scope="prototype">
    <constructor-arg index="0" ref="sqlSessionFactory1"/>
  </bean>

  <aop:config>
    <aop:pointcut id="appService" 
      expression="execution(* com.isea533.mybatis.service..*Service*.*(..))"/>
    <aop:advisor advice-ref="txAdvice1" pointcut-ref="appService"/>
  </aop:config>

  <tx:advice id="txAdvice1" transaction-manager="transactionManager1">
    <tx:attributes>
      <tx:method name="select*" read-only="true"/>
      <tx:method name="find*" read-only="true"/>
      <tx:method name="get*" read-only="true"/>
      <tx:method name="*"/>
    </tx:attributes>
  </tx:advice>

  <bean id="transactionManager1" 
   class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSourceMaster"/>
  </bean>
</beans>

spring-datasource-slave.xml

和master区别不大,主要是id名字和数据源配置有区别。

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd">

  <bean id="dataSourceSlave" class="com.alibaba.druid.pool.DruidDataSource" 
    init-method="init" destroy-method="close">
    <property name="driverClassName" value="${slave.jdbc.driverClass}"/>
    <property name="url" value="${slave.jdbc.url}"/>
    <property name="username" value="${slave.jdbc.user}"/>
    <property name="password" value="${slave.jdbc.password}"/>

    <property name="filters" value="stat"/>

    <property name="maxActive" value="20"/>
    <property name="initialSize" value="1"/>
    <property name="maxWait" value="60000"/>
    <property name="minIdle" value="1"/>

    <property name="timeBetweenEvictionRunsMillis" value="60000"/>
    <property name="minEvictableIdleTimeMillis" value="300000"/>

    <property name="validationQuery" value="SELECT 'x'"/>
    <property name="testWhileIdle" value="true"/>
    <property name="testOnBorrow" value="false"/>
    <property name="testOnReturn" value="false"/>
  </bean>

  <bean id="sqlSessionFactory2" 
    class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSourceSlave"/>
    <property name="mapperLocations">
      <array>
        <value>classpath:mapper/*.xml</value>
      </array>
    </property>
  </bean>

  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.isea533.mybatis.mapper"/>
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory2"/>
  </bean>

  <bean id="sqlSessionSlave" class="org.mybatis.spring.SqlSessionTemplate" scope="prototype">
    <constructor-arg index="0" ref="sqlSessionFactory2"/>
  </bean>


  <aop:config>
    <aop:pointcut id="appService" 
      expression="execution(* com.isea533.mybatis.service..*Service*.*(..))"/>
    <aop:advisor advice-ref="txAdvice2" pointcut-ref="appService"/>
  </aop:config>

  <tx:advice id="txAdvice2" transaction-manager="transactionManager2">
    <tx:attributes>
      <tx:method name="*" read-only="true"/>
    </tx:attributes>
  </tx:advice>

  <bean id="transactionManager2" 
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSourceSlave"/>
  </bean>
</beans>

这里需要注意<tx:method name="*" read-only="true"/>是只读的。如果不是从库,可以按主库进行配置。

在下面代码中:

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  <property name="basePackage" value="com.isea533.mybatis.mapper"/>
  <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory2"/>
</bean>

必须通过sqlSessionFactoryBeanName来指定不同的sqlSessionFactory。

config.properties

# 数据库配置 - Master
master.jdbc.driverClass = com.mysql.jdbc.Driver
master.jdbc.url = jdbc:mysql://192.168.1.11:3306/test
master.jdbc.user = root
master.jdbc.password = jj

# - Slave
slave.jdbc.driverClass = com.mysql.jdbc.Driver
slave.jdbc.url = jdbc:mysql://192.168.1.22:3306/test
slave.jdbc.user = root
slave.jdbc.password = jj

使用Mapper

这里是针对主从的情况进行设置的,两个配置扫描的Mapper是一样的,所以没法直接注入,需要通过下面的麻烦方式注入。

@Service
public class DemoService {
  private CountryMapper writeMapper;
  private CountryMapper readMapper;

  @Resource(name = "sqlSessionMaster")
  public void setWriteMapper(SqlSession sqlSession) {
    this.writeMapper = sqlSession.getMapper(CountryMapper.class);
  }
  @Resource(name = "sqlSessionSlave")
  public void setReadMapper(SqlSession sqlSession) {
    this.readMapper = sqlSession.getMapper(CountryMapper.class);
  }

  public int save(Country country){
    return writeMapper.insert(country);
  }

  public List<Country> selectPage(int pageNum, int pageSize) {
    PageHelper.startPage(pageNum, pageSize);
    return readMapper.select(null);
  }
}

因为sqlSession能通过name区分开,所以这里从sqlSession获取Mapper。

另外如果需要考虑在同一个事务中写读的时候,需要使用相同的writeMapper,这样在读的时候,才能获取事务中的最新数据。

以上是主从的情况。

在分库的情况时,由于不同Mapper在不同的包下,所以可以直接使用@Resource或者@Autowired注入Mapper,不需要通过sqlSession获取。

本篇文章,只是一个多数据源的参考,实际应用时,请根据自己的情况进行考虑。

后续,我会利用业余时间,在本文和上面两个相关链接的基础上,针对MySql多数据源,尝试开发可以自动切换数据源的插件,因为我对这方面的实际应用不是很熟,所以欢迎大家留言分享自己的解决方案,对这些了解的越多,就越有可能开发出通用的数据源切换插件。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


# mybatis  # 读写分离  # mybatis实现读写分离  # 配置读写分离  # Spring Boot 集成Mybatis实现主从(多数据源)分离方案示例  # 详解Spring Boot整合Mybatis实现 Druid多数据源配置  # springboot + mybatis配置多数据源示例  # Spring Boot + Mybatis多数据源和动态数据源配置方法  # Spring3 整合MyBatis3 配置多数据源动态选择SqlSessionFactory详细教程  # 详解SpringBoot和Mybatis配置多数据源  # Spring+MyBatis多数据源配置实现示例  # Spring Boot+Mybatis+Druid+PageHelper实现多数据源并分页的方法  # Spring Boot 整合mybatis 使用多数据源的实现方法  # Mybatis注解实现多数据源读写分离详解  # 自己的  # 情况下  # 需要注意  # 主要是  # 实际应用  # 这是  # 放在  # 我会  # 也会  # 你可以  # 有可能  # 不需要  # 基础上  # 我对  # 要在  # 会对  # 可以直接  # 这种情况  # 就不能  # 欢迎大家 


相关文章: 网站制作哪家好,cc、.co、.cm哪个域名更适合做网站?  宿州网站制作公司兴策,安徽省低保查询网站?  美食网站链接制作教程视频,哪个教做美食的网站比较专业点?  番禺网站制作公司哪家值得合作,番禺图书馆新馆开放了吗?  招商网站制作流程,网站招商广告语?  SAX解析器是什么,它与DOM在处理大型XML文件时有何不同?  c++怎么编写动态链接库dll_c++ __declspec(dllexport)导出与调用【方法】  如何快速搭建高效WAP手机网站吸引移动用户?  网站插件制作软件免费下载,网页视频怎么下到本地插件?  网站视频怎么制作,哪个网站可以免费收看好莱坞经典大片?  建站之星官网登录失败?如何快速解决?  如何通过西部建站助手安装IIS服务器?  北京网站制作的公司有哪些,北京白云观官方网站?  网站代码制作软件有哪些,如何生成自己网站的代码?  如何快速搭建支持数据库操作的智能建站平台?  制作销售网站教学视频,销售网站有哪些?  如何在腾讯云服务器快速搭建个人网站?  如何快速辨别茅台真假?关键步骤解析  如何破解联通资金短缺导致的基站建设难题?  寿县云建站:智能SEO优化与多行业模板快速上线指南  湖州网站制作公司有哪些,浙江中蓝新能源公司官网?  ,交易猫的商品怎么发布到网站上去?  建站主机是否等同于虚拟主机?  常州企业网站制作公司,全国继续教育网怎么登录?  如何在西部数码注册域名并快速搭建网站?  网站制作模板下载什么软件,ppt模板免费下载网站?  专业商城网站制作公司有哪些,pi商城官网是哪个?  如何彻底删除建站之星生成的Banner?  建站主机服务器选购指南:轻量应用与VPS配置解析  如何制作网站标识牌,动态网站如何制作(教程)?  名字制作网站免费,所有小说网站的名字?  ,网站推广常用方法?  建站之星如何快速更换网站模板?  宁波自助建站系统如何快速打造专业企业网站?  如何用AWS免费套餐快速搭建高效网站?  关于BootStrap modal 在IOS9中不能弹出的解决方法(IOS 9 bootstrap modal ios 9 noticework)  如何在Golang中指定模块版本_使用go.mod控制版本号  历史网站制作软件,华为如何找回被删除的网站?  如何构建满足综合性能需求的优质建站方案?  青岛网站建设如何选择本地服务器?  如何快速生成专业多端适配建站电话?  专业网站制作企业网站,如何制作一个企业网站,建设网站的基本步骤有哪些?  建站之星体验版:智能建站系统+响应式设计,多端适配快速建站  北京网站制作网页,网站升级改版需要多久?  IOS倒计时设置UIButton标题title的抖动问题  广平建站公司哪家专业可靠?如何选择?  如何选择可靠的免备案建站服务器?  网站制作外包价格怎么算,招聘网站上写的“外包”是什么意思?  免费网站制作模板下载,除了易企秀之外还有什么H5平台可以制作H5长页面,最好是免费的?  如何在云主机上快速搭建多站点网站? 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。