Shardingsphere-jdbc 配置文件加载

Shardingsphere-jdbc 配置文件加载

在进行jdbc的功能演示时,有个疑问

不同的功能对应不同的配置文件,不同的配置文件是怎么被加载的,最后生成什么

分析配置文件加载流程

  1. 生成YamlRootConfiguration
  2. 解析config
    2.1 解析数据源连接信息
    2.2 解析规则信息,生成RuleConfiguration
  3. 通过ShardingSphereDataSourceFactory生成ShardingSphereDataSource

YamlRootConfiguration

public final class YamlRootConfiguration implements YamlConfiguration {
    
    private String schemaName;
    
    private Map<String, Map<String, Object>> dataSources = new HashMap<>();//多数据源
    
    private Collection<YamlRuleConfiguration> rules = new LinkedList<>();//有多少个配置文件就有多少个YamlRuleConfiguration
    
    private YamlModeConfiguration mode;//控制什么?
    
    private Properties props = new Properties();//配置文件中配置的props
}

对应配置文件中的配置

dataSources:
  ds_0:
    dataSourceClassName: com.zaxxer.hikari.HikariDataSource
    driverClassName: com.mysql.jdbc.Driver
    jdbcUrl: jdbc:mysql://localhost:3306/demo_ds_0?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8
    username: root
    password: root1234
  ds_1:
    dataSourceClassName: com.zaxxer.hikari.HikariDataSource
    driverClassName: com.mysql.jdbc.Driver
    jdbcUrl: jdbc:mysql://localhost:3306/demo_ds_1?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8
    username: root
    password: root1234

通过比较配置文件和YamlRootConfiguration可以发现,配置文件中的配置可以和YamlRootConfiguration映射起来的,也就是配置文件中的内容可以被解析出来存入YamlRootConfiguration中待下一步使用

解析数据源并启动

    public Map<String, DataSource> swapToDataSources(final Map<String, Map<String, Object>> yamlDataSources) {
        return DataSourceConverter.getDataSourceMap(yamlDataSources.entrySet().stream().collect(Collectors.toMap(Entry::getKey, entry -> swapToDataSourceConfiguration(entry.getValue()))));
    }
    public static Map<String, DataSource> getDataSourceMap(final Map<String, DataSourceConfiguration> dataSourceConfigMap) {
        return dataSourceConfigMap.entrySet().stream().collect(Collectors.toMap(Entry::getKey,
            entry -> entry.getValue().createDataSource(), (oldValue, currentValue) -> oldValue, LinkedHashMap::new));
    }
    @SneakyThrows(ReflectiveOperationException.class)
    public DataSource createDataSource() {
        DataSource result = (DataSource) Class.forName(dataSourceClassName).getConstructor().newInstance();
        Method[] methods = result.getClass().getMethods();
        Map<String, Object> allProps = new HashMap<>(props);
        allProps.putAll((Map) customPoolProps);
        for (Entry<String, Object> entry : allProps.entrySet()) {
            if (SKIPPED_PROPERTY_NAMES.contains(entry.getKey())) {
                continue;
            }
            try {
                Optional<Method> setterMethod = findSetterMethod(methods, entry.getKey());
                if (setterMethod.isPresent() && null != entry.getValue()) {
                    setDataSourceField(setterMethod.get(), result, entry.getValue());
                }
            } catch (final IllegalArgumentException ex) {
                throw new ShardingSphereConfigurationException("Incorrect configuration item: the property %s of the dataSource, because %s", entry.getKey(), ex.getMessage());
            }
        }
        return JDBCParameterDecoratorHelper.decorate(result);//连接池配置
    }
    public HikariDataSource decorate(final HikariDataSource dataSource) {
        Map<String, String> urlProps = new ConnectionUrlParser(dataSource.getJdbcUrl()).getQueryMap();
        addJDBCProperty(dataSource, urlProps, "useServerPrepStmts", Boolean.TRUE.toString());
        addJDBCProperty(dataSource, urlProps, "cachePrepStmts", Boolean.TRUE.toString());
        addJDBCProperty(dataSource, urlProps, "prepStmtCacheSize", "200000");
        addJDBCProperty(dataSource, urlProps, "prepStmtCacheSqlLimit", "2048");
        addJDBCProperty(dataSource, urlProps, "useLocalSessionState", Boolean.TRUE.toString());
        addJDBCProperty(dataSource, urlProps, "rewriteBatchedStatements", Boolean.TRUE.toString());
        addJDBCProperty(dataSource, urlProps, "cacheResultSetMetadata", Boolean.FALSE.toString());
        addJDBCProperty(dataSource, urlProps, "cacheServerConfiguration", Boolean.TRUE.toString());
        addJDBCProperty(dataSource, urlProps, "elideSetAutoCommits", Boolean.TRUE.toString());
        addJDBCProperty(dataSource, urlProps, "maintainTimeStats", Boolean.FALSE.toString());
        addJDBCProperty(dataSource, urlProps, "netTimeoutForStreamingResults", "0");
        addJDBCProperty(dataSource, urlProps, "tinyInt1isBit", Boolean.FALSE.toString());
        addJDBCProperty(dataSource, urlProps, "useSSL", Boolean.FALSE.toString());
        addJDBCProperty(dataSource, urlProps, "serverTimezone", "UTC");
        HikariDataSource result = new HikariDataSource(dataSource);
        dataSource.close();
        return result;
    }
  1. 从配置文件中单独抽出数据源的连接信息
  2. 一个数据源对应一个DataSourceConfiguration
  3. DataSourceConfiguration启动数据源
  4. 对启动的dataSource进行加工,放入一些全局配置(这里我认为可以优化成动态配置)

解析规则

    public Collection<RuleConfiguration> swapToRuleConfigurations(final Collection<YamlRuleConfiguration> yamlRuleConfigs) {
        Collection<RuleConfiguration> result = new LinkedList<>();
        Collection<Class<?>> ruleConfigTypes = yamlRuleConfigs.stream().map(YamlRuleConfiguration::getRuleConfigurationType).collect(Collectors.toList());
        for (Entry<Class<?>, YamlRuleConfigurationSwapper> entry : OrderedSPIRegistry.getRegisteredServicesByClass(YamlRuleConfigurationSwapper.class, ruleConfigTypes).entrySet()) {
            result.addAll(swapToRuleConfigurations(yamlRuleConfigs, entry.getKey(), entry.getValue()));
        }
        return result;
    }
    private Collection<RuleConfiguration> swapToRuleConfigurations(final Collection<YamlRuleConfiguration> yamlRuleConfigs, 
                                                                   final Class<?> ruleConfigType, final YamlRuleConfigurationSwapper swapper) {
        return yamlRuleConfigs.stream().filter(
            each -> each.getRuleConfigurationType().equals(ruleConfigType)).map(each -> (RuleConfiguration) swapper.swapToObject(each)).collect(Collectors.toList());
    }
    public static <T extends OrderedSPI<?>> Map<Class<?>, T> getRegisteredServicesByClass(final Class<T> orderedSPIClass, final Collection<Class<?>> types) {
        Collection<T> registeredServices = getRegisteredServices(orderedSPIClass);
        Map<Class<?>, T> result = new LinkedHashMap<>(registeredServices.size(), 1);//为啥设成1?
        for (T each : registeredServices) {
            types.stream().filter(type -> each.getTypeClass() == type).forEach(type -> result.put(type, each));
        }
        return result;
    }
    public static <T extends OrderedSPI<?>> Map<Class<?>, T> getRegisteredServicesByClass(final Class<T> orderedSPIClass, final Collection<Class<?>> types) {
        Collection<T> registeredServices = getRegisteredServices(orderedSPIClass);
        Map<Class<?>, T> result = new LinkedHashMap<>(registeredServices.size(), 1);
        for (T each : registeredServices) {
            types.stream().filter(type -> each.getTypeClass() == type).forEach(type -> result.put(type, each));
        }
        return result;
    }
    public static <T extends OrderedSPI<?>> Collection<T> getRegisteredServices(final Class<T> orderedSPIClass) {
        return getRegisteredServices(orderedSPIClass, Comparator.naturalOrder());//使用常数大小来排序
    }
    public static <T extends OrderedSPI<?>> Collection<T> getRegisteredServices(final Class<T> orderedSPIClass, final Comparator<Integer> comparator) {
        Map<Integer, T> result = new TreeMap<>(comparator);//使用treemap来达到排序目的
        for (T each : ShardingSphereServiceLoader.getSingletonServiceInstances(orderedSPIClass)) {
            Preconditions.checkArgument(!result.containsKey(each.getOrder()), "Found same order `%s` with `%s` and `%s`", each.getOrder(), result.get(each.getOrder()), each);
            result.put(each.getOrder(), each);
        }
        return result.values();
    }

解析流程

  1. 提取YamlRuleConfiguration中的RuleConfigurationType
  2. 根据RuleConfigurationType将已实现的YamlRuleConfigurationSwapper按顺序转化为标准配置
  3. 最后生成ShardingRuleConfiguration集合

YamlRuleConfigurationSwapper

SPI 名称 详细说明
YamlRuleConfigurationSwapper 用于将 YAML 配置转化为标准用户配置
已知实现类 详细说明
ReadwriteSplittingRuleAlgorithmProviderConfigurationYamlSwapper 用于将基于算法的读写分离配置转化为读写分离标准配置
DatabaseDiscoveryRuleAlgorithmProviderConfigurationYamlSwapper 用于将基于算法的数据库发现配置转化为数据库发现标准配置
ShardingRuleAlgorithmProviderConfigurationYamlSwapper 用于将基于算法的分片配置转化为分片标准配置
EncryptRuleAlgorithmProviderConfigurationYamlSwapper 用于将基于算法的加密配置转化为加密标准配置
ReadwriteSplittingRuleConfigurationYamlSwapper 用于将读写分离的 YAML 配置转化为读写分离标准配置
DatabaseDiscoveryRuleConfigurationYamlSwapper 用于将数据库发现的 YAML 配置转化为数据库发现标准配置
AuthorityRuleConfigurationYamlSwapper 用于将权限规则的 YAML 配置转化为权限规则标准配置
ShardingRuleConfigurationYamlSwapper 用于将分片的 YAML 配置转化为分片标准配置
EncryptRuleConfigurationYamlSwapper 用于将加密的 YAML 配置转化为加密标准配置
ShadowRuleConfigurationYamlSwapper 用于将影子库的 YAML 配置转化为影子库标准配置

可以在configuration.cn.md看到每个swapper的作用

问题: 为什么要按顺序来注册swapper?

ShardingRuleConfiguration

public final class ShardingRuleConfiguration implements SchemaRuleConfiguration, DistributedRuleConfiguration {
    
    private Collection<ShardingTableRuleConfiguration> tables = new LinkedList<>();
    
    private Collection<ShardingAutoTableRuleConfiguration> autoTables = new LinkedList<>();
    
    private Collection<String> bindingTableGroups = new LinkedList<>();
    
    private Collection<String> broadcastTables = new LinkedList<>();
    
    private ShardingStrategyConfiguration defaultDatabaseShardingStrategy;
    
    private ShardingStrategyConfiguration defaultTableShardingStrategy;
    
    private KeyGenerateStrategyConfiguration defaultKeyGenerateStrategy;

    private String defaultShardingColumn;
    
    private Map<String, ShardingSphereAlgorithmConfiguration> shardingAlgorithms = new LinkedHashMap<>();
    
    private Map<String, ShardingSphereAlgorithmConfiguration> keyGenerators = new LinkedHashMap<>();
}

对应的配置内容

rules:
- !SHARDING
  tables:
    t_order: 
      actualDataNodes: ds_${0..1}.t_order_${0..1}
      tableStrategy: 
        standard:
          shardingColumn: order_id
          shardingAlgorithmName: t_order_inline
      keyGenerateStrategy:
        column: order_id
        keyGeneratorName: snowflake
    t_order_item:
      actualDataNodes: ds_${0..1}.t_order_item_${0..1}
      tableStrategy:
        standard:
          shardingColumn: order_id
          shardingAlgorithmName: t_order_item_inline
      keyGenerateStrategy:
        column: order_item_id
        keyGeneratorName: snowflake
  bindingTables:
    - t_order,t_order_item
  broadcastTables:
    - t_address
  defaultDatabaseStrategy:
    standard:
      shardingColumn: user_id
      shardingAlgorithmName: database_inline
  defaultTableStrategy:
    none:
  
  shardingAlgorithms:
    database_inline:
      type: INLINE
      props:
        algorithm-expression: ds_${user_id % 2}
    t_order_inline:
      type: INLINE
      props:
        algorithm-expression: t_order_${order_id % 2}
    t_order_item_inline:
      type: INLINE
      props:
        algorithm-expression: t_order_item_${order_id % 2}
  
  keyGenerators:
    snowflake:
      type: SNOWFLAKE
      props:
          worker-id: 123

通过比较配置文件和ShardingRuleConfiguration可以发现,配置文件中的配置可以和ShardingRuleConfiguration映射起来的

生成ShardingSphereDataSource

    public static DataSource createDataSource(final String schemaName, final ModeConfiguration modeConfig, 
                                              final Map<String, DataSource> dataSourceMap, final Collection<RuleConfiguration> configs, final Properties props) throws SQLException {
        return new ShardingSphereDataSource(Strings.isNullOrEmpty(schemaName) ? DefaultSchema.LOGIC_NAME : schemaName, modeConfig, dataSourceMap, configs, props);
    }

将解析出来的dataSourceRuleConfiguration通过调用ShardingSphereDataSource的构造方法来生成

    public ShardingSphereDataSource(final String schemaName, final ModeConfiguration modeConfig, final Map<String, DataSource> dataSourceMap,
                                    final Collection<RuleConfiguration> ruleConfigs, final Properties props) throws SQLException {
        this.schemaName = schemaName;
        contextManager = createContextManager(schemaName, modeConfig, dataSourceMap, ruleConfigs, props);
    }

ShardingSphereDataSource中的成员变量contextManager

    private ContextManager createContextManager(final String schemaName, final ModeConfiguration modeConfig, final Map<String, DataSource> dataSourceMap,
                                                final Collection<RuleConfiguration> ruleConfigs, final Properties props) throws SQLException {
        Map<String, Map<String, DataSource>> dataSourcesMap = Collections.singletonMap(schemaName, dataSourceMap);
        Map<String, Collection<RuleConfiguration>> schemaRuleConfigs = Collections.singletonMap(
                schemaName, ruleConfigs.stream().filter(each -> each instanceof SchemaRuleConfiguration).collect(Collectors.toList()));
        Collection<RuleConfiguration> globalRuleConfigs = ruleConfigs.stream().filter(each -> each instanceof GlobalRuleConfiguration).collect(Collectors.toList());
        ContextManagerBuilder builder = TypedSPIRegistry.getRegisteredService(ContextManagerBuilder.class, null == modeConfig ? "Memory" : modeConfig.getType(), new Properties());//工厂模式生成对应的ContextManagerBuilder
        return builder.build(modeConfig, dataSourcesMap, schemaRuleConfigs, globalRuleConfigs, props, null == modeConfig || modeConfig.isOverwrite());
    }
    @Override
    public ContextManager build(final ModeConfiguration modeConfig, final Map<String, Map<String, DataSource>> dataSourcesMap,
                                final Map<String, Collection<RuleConfiguration>> schemaRuleConfigs, final Collection<RuleConfiguration> globalRuleConfigs,
                                final Properties props, final boolean isOverwrite) throws SQLException {
        MetaDataContexts metaDataContexts = new MetaDataContextsBuilder(dataSourcesMap, schemaRuleConfigs, globalRuleConfigs, props).build(null);
        TransactionContexts transactionContexts = createTransactionContexts(metaDataContexts);
        ContextManager result = new MemoryContextManager();
        result.init(metaDataContexts, transactionContexts);
        return result;
    }
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,509评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,806评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,875评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,441评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,488评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,365评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,190评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,062评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,500评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,706评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,834评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,559评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,167评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,779评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,912评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,958评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,779评论 2 354

推荐阅读更多精彩内容