大概思路就是使用AbstractRoutingDataSource来动态切换数据源,当需要使用DISTINCT的时候,切换成功原生数据源,来进行查询。在这里还需要自己根据自定义的规则查询表名。
原生数据源
<bean name="nativeDataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="url" value="${db.master.url}" />
<property name="username" value="${db.master.user}" />
<property name="password" value="${db.master.password}" />
</bean>
复制代码
sharingjdbc数据源,内部还是引用了原生数据源的
<sharding:data-source id="shardingDataSource">
<sharding:sharding-rule data-source-names="nativeDataSource">
<sharding:table-rules>
<sharding:table-rule logic-table="apply_order" actual-data-nodes="nativeDataSource.apply_order_${[2017,2018]}${1..54}" table-strategy-ref="orderTableShardingStrategy" />
<sharding:table-rule logic-table="apply_device" actual-data-nodes="nativeDataSource.apply_device_${[2017,2018]}${1..54}" table-strategy-ref="applyDeviceTableShardingStrategy" />
<sharding:table-rule logic-table="awake_request_record" actual-data-nodes="nativeDataSource.awake_request_record_${[2017,2018]}${1..12}" table-strategy-ref="awakeRequestRecordTableShardingStrategy" />
</sharding:table-rules>
<sharding:binding-table-rules>
<sharding:binding-table-rule logic-tables="apply_order,apply_device,awake_request_record"/>
</sharding:binding-table-rules>
</sharding:sharding-rule>
<sharding:props>
<prop key="sql.show">true</prop>
</sharding:props>
</sharding:data-source>
复制代码
路由数据源
<bean id = "dataSource" class="com.dsp.common.datasource.DynamicDataSource" >
<!-- 已配置的数据源 -->
<property name="targetDataSources">
<map>
<entry key="shardingDataSource" value-ref="shardingDataSource"/>
<entry key="nativeDataSource" value-ref="nativeDataSource"/>
</map>
</property>
<!-- 默认的数据源 -->
<property name="defaultTargetDataSource" ref="shardingDataSource"/>
</bean>
复制代码
接着在mybatis引用数据源的地方使用这个路由数据源