关系型DB(MySQL,MyBatis )

基于spring 切面(AOP)实现动态多数据源切换,基于 My

2020-01-05  本文已影响0人  AndyChen

基于spring 切面(AOP)实现动态多数据源切换;基于 MyBatis 插件方式实现动态分表查询。 来源于多个已上线项目实践,本项目有完整的测试示例。

mybatis-plugin-shard

以后会出详细的文档,敬请期待。

todo

项目地址

配套 MBG 增强插件

查看 MBG 增强插件请移步:mybatis-generator

功能概述

动态切换数据源的三种方式

如果以上三种方式都没有找到数据源,则使用默认的数据源。

分库分表思路

分表分库场景

运行

cd dependencies
mvn clean
mvn compile
mvn install
<mirror> 
    <id>alimaven</id> 
    <name>aliyun maven</name> 
    <url>https://maven.aliyun.com/repository/jcenter</url> 
    <mirrorOf>central</mirrorOf> 
</mirror>

数据源配置(部分)

<bean id="dataSource" class="common.aspect.ChooseDataSource" primary="true">
    <property name="defaultTargetDataSource" ref="dataSourceSystem"/>
    <!-- 下面的各个 0key 需要配置到 shardTableConfigView 的 schemaKeyList -->
    <property name="targetDataSources">
        <map key-type="java.lang.String">
            <entry key="system" value-ref="dataSourceSystem"/>
            <entry key="student" value-ref="dataSourceStudent"/>
            <entry key="finance" value-ref="dataSourceFinance"/>
            <entry key="biz" value-ref="dataSourceBiz"/>
        </map>
    </property>
</bean>

配置分表分库配置类

<!-- 以下配置,部分表名只是用于配置示例,仅为了更好的展示如何配置。
    本项目没有用到的表名有:edu_class、biz_trade_order、biz_item、biz_item_sku
-->
<bean id="shardConfig" class="common.shard.ShardConfig" >
    <!-- 列表值为 dataSource.targetDataSources 的 keys  -->
    <property name="schemaKeyList">
        <list>
            <value>system</value>
            <value>student</value>
            <value>finance</value>
            <value>biz</value>
        </list>
    </property>
    <!-- 基于服务接口分库策略,
        把针对某个 schema 的接口配置在该数据源 key 对应的 list 下,没有就不配置
    -->
    <property name="shardSchemaInterfaceClassNameList">
        <map>
            <entry key="student">
                <list>
                    <value>biz.service.facade.IEduStudentService</value>
                </list>
            </entry>
        </map>
    </property>
    <!-- 分表策略
        直接将 ShardRequest.shardKeyTable(优先级高于后者) 或 ShardRequest.shardKeyTableNumber 作为分表后缀的表。
         ShardRequest 参见:https://github.com/uncleAndyChen/mybatis-plugin-shard/blob/master/common/common-shard/src/main/java/common/shard/ShardRequest.java
     -->
    <property name="shardTableDirectlyList">
        <list>
            <value>edu_student</value>
            <value>edu_class</value>
        </list>
    </property>
    <!-- 分表策略
        通过两个数相除取余作为后缀的表,配合 ShardRequest.shardKeyTableNumber 使用
        ShardRequest 参见:https://github.com/uncleAndyChen/mybatis-plugin-shard/blob/master/common/common-shard/src/main/java/common/shard/ShardRequest.java
    -->
    <!-- key 将作为 shardKeyTableNumber 的除数(取余), 余数作为分表后缀-->
    <!-- shardKeyTableNumber 通过 ShardRequest 传递,在请求 api 时传递 -->
    <property name="shardTableDivideList">
        <map>
            <entry key="10">
                <list>
                    <value>biz_trade</value>
                    <value>biz_trade_order</value>
                </list>
            </entry>
            <entry key="5">
                <list>
                    <value>biz_item</value>
                    <value>biz_item_sku</value>
                </list>
            </entry>
        </map>
    </property>
    <!-- 打印分表的 sql 语句,默认为 false 即不打印。-->
    <property name="printShardSqlInfo" value="true" />
    <!-- 不需要分表的 sql 语句列表,以下这句为 MyBatis 操作数据库新增记录时,查询新增的主键值的语句 -->
    <property name="notNeedShardSqlList">
        <list>
            <value>SELECT LAST_INSERT_ID()</value>
        </list>
    </property>
</bean>

切面配置

<!-- 用于切面,实现拦截数据库操作,实现分库分表的类 -->
<bean id="dataSourceAspect" class="common.aspect.DataSourceAspect">
    <property name="shardTableConfigView" ref="shardConfig" />
</bean>

<!-- 定义切面,用于拦截数据库操作,实现分库分表 -->
<aop:config proxy-target-class="true">
    <aop:aspect id="dataSourceAspect" ref="dataSourceAspect" order="1">
        <aop:pointcut id="point" expression="(execution(* biz.service.impl.*.*(..)))"/>
        <aop:before pointcut-ref="point" method="before"/>
        <aop:after pointcut-ref="point" method="afterHandler"/>
    </aop:aspect>
</aop:config>

请求参数 ShardRequest.java 类

public class ShardRequest {
    /**
     * 分库标志 key,是定义数据源时指定的 key,在执行数据库操作之前,通过该 key 动态切换数据源。
     * 如果只是分库,除了用到个属性,还可利用 ShardTableConfig.shardSchemaInterfaceNameList 实现。
     *      有关这两项配置的详细信息,请参见:https://github.com/uncleAndyChen/mybatis-plugin-shard/blob/master/biz/biz-config/src/main/resources/db-source.xml
     */
    private String shardKeySchema;

    /**
     * 分表标志 key,直接用作分表后缀的 key 值,针对直接添加后缀的表
     *      举例:应用该规则的原始表名为 table_name,则对应的分表为:table_name_key
     * 需要配合 ShardTableConfig 使用,与该类位于同一个目录,在 db-source.xml 中配置各属性值
     *     应用该规则的原始表名:ShardTableConfig.shardTableDirectlyList
     *          详细描述,请参见:https://github.com/uncleAndyChen/mybatis-plugin-shard/blob/master/biz/biz-config/src/main/resources/db-source.xml
     */
    private String shardKeyTable;

    /**
     * 动态分表参数编号,整形,一般与用户绑定,针对需要除一个数得到后缀的表
     * 需要配合 ShardTableConfig 使用,与该类位于同一个目录,在 db-source.xml 中配置各属性值
     *     应用该规则的原始表名:ShardTableConfig.shardTableDivideList
     *          详细描述,请参见:https://github.com/uncleAndyChen/mybatis-plugin-shard/blob/master/biz/biz-config/src/main/resources/db-source.xml
     *
     * 场景:SaaS 平台,每个用户分配一个编码值,可以按一定规则平均分配,比如现有有10万个用户,我们打算分10张表,那么,平均分配的话,就意味着每一万个用户有一个分表编号。
     * 极端地,对于 SasS 的超级 VIP 用户,可以分配一个唯一的分表编号,这就意味着这个 VIP 用户独享一套表。
     * 多个用户的数据可能存在于同一个数据库实例,也可能存在于多个数据库实例,可根据业务灵活分配。
     */
    private int shardKeyTableNumber;

    // getter and setter
    // ...
}

重新生成 mapper 和 entity

请参考 生成 Mapper 操作

有关 {xxx}Mapper.xml 文件

我是直接把 MBG 生成的 {xxx}Mapper.xml 文件放到了 biz-service-dal 模块下与 {xxx}Mapper.java 平级的目录下了,包名为:biz.mapper.xml.originalbiz.mapper.xml.extend

默认情况下,xml 文件不会被打包,所以,运行的时候会出现类似这样的错误:

Invalid bound statement (not found): biz.service.dal.mapper.original.EduStudentMapper.selectByExample

解决:需要在 pom.xml 里设置为需要将 xml 一起打包,如下:

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>

directory 配置到 xml 的父目录 src/main/java/biz/mapper/xml 不会生效,配置成 src/main/java 就好。

技术清单

支持

如果有疑问或建议,欢迎请提 Issue
可能不会立即回复,尤其上班时间,不过我会尽量抽业余时间回复的。

如果帮到了你

请 Star 一下,让我有动力继续完善和优化。

关于作者

上一篇 下一篇

猜你喜欢

热点阅读