ShardingSphere Hint模式 SpringBoot + Mybatis

ShardingSphere Hint模式不需要对sql进行解析,就可以进行数据库或者表的路由。下面贴一下代码,关于SpringBoot + Mybatis + ShardingSphere怎样结合。

配置文件,注意是DataSources 多了个s

 ShardingSphere Hint模式  SpringBoot + Mybatis

 

启动类,排除了DataSourceAutoConfiguration

 ShardingSphere Hint模式  SpringBoot + Mybatis

 

然后ShardingSphere 的配置类

 ShardingSphere Hint模式  SpringBoot + Mybatis

ShardingSphere Hint模式  SpringBoot + Mybatis

 

 

 

@Primary很关键。

现在就相当于你配置的数据源已经受ShardingSphere管理、拦截。你项目中所执行的sql相关的东西都会有ShardingSphere代理执行。

接下来是doSharding方法。

 ShardingSphere Hint模式  SpringBoot + Mybatis

ShardingSphere Hint模式  SpringBoot + Mybatis

 

 

 

根据HintManager设置的业务相关的标识,判定数据库,业务标识与数据库之间的映射关系*发挥。

availableTargetNames 是ShardingDataSourceFactory.createDataSource中所有的数据库。

shardingValue 是 HintManager设置的数据库,通过比较设置数据源,HintManager中使用ThreadLocal只对当前线程生效,所以,如果某线程没有设置数据源 可采取shardingValue 默认值的情况,设置默认数据源。

setDataSource是静态方法,可在代码中手动设置切换,同时也可封装切面,在Dao层自动切换数据源,随各位看官心情吧,有时间将会整理后上传github。

 

 

还有Spring 动态设置数据源切换,后续补充吧,Spring 动态数据源切换相对较多,ShardingSphere Hint 模式还比较少吧。

原创,有需要转载请标明出处。

上一篇:shardingsphere


下一篇:分库分表(5) ---SpringBoot + ShardingSphere 实现分库分表