Sharding-Jdbc源码学习(一):配置shardingDatasource

一,分片-JDBC分库分表概述

拆分-JDBC是实现了JDBC协议的罐子文件。基于JDBC协议实现,与基于MySQL的协议实现的分库策略(mycat)在实现上有很大差异。

无论使用哪种架构,核心逻辑均极为相似,除了协议实现层不同(JDBC或数据库协议),都会分为分片规则配置,SQL解析,SQL改写,SQL路由,SQL执行以及结果归并等模块。

故整体架构如下:

å¾çæè¿°

本文主要从分片规则配置及JDB​​C规范重写入手解读源码。

二,从JDBC规范重写学习拆分-JDBC实现原理。

1,定义ShardingDataSource,sharding-Datasource支持配置多数据源,以实现分库的目的。

例如:配置shardingDataSource 

@Configuration
public class SpringConfig {
    @Bean("shardingDataSource")
    public ShardingDataSource createProductBean(DruidDataSource x_ds_0, DruidDataSource x_ds_1, DruidDataSource x_ds_2,DruidDataSource x_ds_3, DruidDataSource x_ds_4, DruidDataSource x_ds_5,
DruidDataSource x_ds_6, DruidDataSource x_ds_7, DruidDataSource x_ds_8) throws SQLException {

        Map dataSourceMap = new HashMap<>();
        dataSourceMap.put("x_ds_0", x_ds_0);
        dataSourceMap.put("x_ds_1", x_ds_1);
        dataSourceMap.put("x_ds_2", x_ds_2);
        dataSourceMap.put("x_ds_3", x_ds_3);
        dataSourceMap.put("x_ds_4", x_ds_4);
        dataSourceMap.put("x_ds_5", x_ds_5);
        dataSourceMap.put("x_ds_6", x_ds_6);
        dataSourceMap.put("x_ds_7", x_ds_7);
        dataSourceMap.put("x_ds_8", x_ds_8);

        YamlShardingConfiguration yamlShardingConfiguration = getYamlShardingConfiguration();
        ShardingRule shardingRule = yamlShardingConfiguration.getShardingRule().getShardingRuleConfiguration().build(dataSourceMap);
        return new ShardingDataSource(shardingRule);

    }

    public static YamlShardingConfiguration getYamlShardingConfiguration() {
        YamlShardingConfiguration yamlShardingConfiguration = null;
        try (
                InputStream fileInputStream = SpringConfig.class.getResource("/yarmdb.yaml").openStream();
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8")
        ) {
            yamlShardingConfiguration = new Yaml(new Constructor(YamlShardingConfiguration.class)).loadAs(inputStreamReader, YamlShardingConfiguration.class);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return yamlShardingConfiguration;
    }
}

你可能感兴趣的:(Sharding-Jdbc源码学习(一):配置shardingDatasource)