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

 更新时间:2017年01月03日 09:23:04   作者:isea533  
这篇文章主要介绍了详解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多数据源,尝试开发可以自动切换数据源的插件,因为我对这方面的实际应用不是很熟,所以欢迎大家留言分享自己的解决方案,对这些了解的越多,就越有可能开发出通用的数据源切换插件。

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

相关文章

  • 在spring中使用自定义注解注册监听器的方法

    在spring中使用自定义注解注册监听器的方法

    本篇文章主要介绍了在spring中使用自定义注解注册监听器的方法,本文就是在分析监听器回调原理的基础上,在spring环境中使用自定义的注解实现一个监听器。小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-01-01
  • SpringMVC bean加载控制的实现分析

    SpringMVC bean加载控制的实现分析

    SpringMVC是一种基于Java,实现了Web MVC设计模式,请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将Web层进行职责解耦。基于请求驱动指的就是使用请求-响应模型,框架的目的就是帮助我们简化开发,SpringMVC也是要简化我们日常Web开发
    2023-02-02
  • 基于Cookie与Session的Servlet API会话管理操作

    基于Cookie与Session的Servlet API会话管理操作

    这篇文章主要为大家介绍了基于Cookie与Session的Servlet API会话管理操作详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-08-08
  • Elasticsearch配置文件示例示范

    Elasticsearch配置文件示例示范

    这篇文章主要为大家介绍了Elasticsearch配置文件的示例示范,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-04-04
  • Java实现文件上传下载以及查看功能

    Java实现文件上传下载以及查看功能

    这篇文章主要为大家详细介绍了java如何实现文件上传和下载以及查看功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-03-03
  • Intellij Idea中批量导入第三方jar包的全过程

    Intellij Idea中批量导入第三方jar包的全过程

    引入jar包一般都是针对小的java项目,这篇文章主要给大家介绍了关于Intellij Idea中批量导入第三方jar包的相关资料,文中通过图文介绍的非常详细,需要的朋友可以参考下
    2021-10-10
  • Mybatis-Plus进阶分页与乐观锁插件及通用枚举和多数据源详解

    Mybatis-Plus进阶分页与乐观锁插件及通用枚举和多数据源详解

    这篇文章主要介绍了Mybatis-Plus的分页插件与乐观锁插件还有通用枚举和多数据源的相关介绍,文中代码附有详细的注释,感兴趣的朋友来看看吧
    2022-03-03
  • Java深入讲解SPI的使用

    Java深入讲解SPI的使用

    SPI英文全称为Service Provider Interface,顾名思义,服务提供者接口,它是jdk提供给“服务提供厂商”或者“插件开发者”使用的接口
    2022-06-06
  • SpringBoot集成Druid实现监控功能的示例代码

    SpringBoot集成Druid实现监控功能的示例代码

    这篇文章主要介绍了SpringBoot集成Druid实现监控功能,Druid是阿里巴巴开发的号称为监控而生的数据库连接池,可以很好的监控DB池连接和SQL的执行情况,天生就是针对监控而生的DB连接池,文中通过代码示例讲解非常详细,需要的朋友可以参考下
    2024-02-02
  • Java中的System.getProperty()详解

    Java中的System.getProperty()详解

    System.getProperty("XXX")方法用来读取JVM中的系统属性,那么java 虚拟机中的系统属性使用在运行java程序的时候java -D配置,有两种方式,一种是在命令行配置另一种是在IDE中配置,本文给大家介绍的非常详细,感兴趣的朋友一起看看吧
    2023-09-09

最新评论