读写分离

背景信息

Java API 形式配置的读写分离可以方便的适用于各种场景,不依赖额外的 jar 包,用户只需要通过 java 代码构造读写分离数据源便可以使用读写分离功能。

参数解释

配置入口

类名称:org.apache.shardingsphere.readwritesplitting.api.ReadwriteSplittingRuleConfiguration

可配置属性:

名称数据类型说明
dataSources (+)Collection<ReadwriteSplittingDataSourceRuleConfiguration>读写数据源配置
loadBalancers (*)Map<String, AlgorithmConfiguration>从库负载均衡算法配置

主从数据源配置

类名称:org.apache.shardingsphere.readwritesplitting.api.rule.ReadwriteSplittingDataSourceRuleConfiguration

可配置属性:

名称数据类型说明默认值
nameString读写分离数据源名称-
staticStrategyStaticReadwriteSplittingStrategyConfiguration静态读写分离配置-
dynamicStrategyDynamicReadwriteSplittingStrategyConfiguration动态读写分离配置-
loadBalancerName (?)String读库负载均衡算法名称轮询负载均衡算法

类名称:org.apache.shardingsphere.readwritesplitting.api.strategy.StaticReadwriteSplittingStrategyConfiguration

可配置属性:

名称数据类型说明
writeDataSourceNameString写库数据源名称
readDataSourceNamesList<String>读库数据源列表

类名称:org.apache.shardingsphere.readwritesplitting.api.strategy.DynamicReadwriteSplittingStrategyConfiguration

可配置属性:

名称数据类型说明默认值
autoAwareDataSourceNameString数据库发现的逻辑数据源名称-
writeDataSourceQueryEnabled (?)String读库全部下线,主库是否承担读流量true

算法类型的详情,请参见内置负载均衡算法列表。 查询一致性路由的详情,请参见核心特性:读写分离

操作步骤

  1. 添加读写分离数据源
  2. 设置负载均衡算法
  3. 使用读写分离数据源

配置示例

  1. public DataSource getDataSource() throws SQLException {
  2. ReadwriteSplittingDataSourceRuleConfiguration dataSourceConfig = new ReadwriteSplittingDataSourceRuleConfiguration(
  3. "demo_read_query_ds", new StaticReadwriteSplittingStrategyConfiguration("demo_write_ds",
  4. Arrays.asList("demo_read_ds_0", "demo_read_ds_1")), null,"demo_weight_lb");
  5. Properties algorithmProps = new Properties();
  6. algorithmProps.setProperty("demo_read_ds_0", "2");
  7. algorithmProps.setProperty("demo_read_ds_1", "1");
  8. Map<String, AlgorithmConfiguration> algorithmConfigMap = new HashMap<>(1);
  9. algorithmConfigMap.put("demo_weight_lb", new AlgorithmConfiguration("WEIGHT", algorithmProps));
  10. ReadwriteSplittingRuleConfiguration ruleConfig = new ReadwriteSplittingRuleConfiguration(Collections.singleton(dataSourceConfig), algorithmConfigMap);
  11. Properties props = new Properties();
  12. props.setProperty("sql-show", Boolean.TRUE.toString());
  13. return ShardingSphereDataSourceFactory.createDataSource(createDataSourceMap(), Collections.singleton(ruleConfig), props);
  14. }
  15. private Map<String, DataSource> createDataSourceMap() {
  16. Map<String, DataSource> result = new HashMap<>(3, 1);
  17. result.put("demo_write_ds", DataSourceUtil.createDataSource("demo_write_ds"));
  18. result.put("demo_read_ds_0", DataSourceUtil.createDataSource("demo_read_ds_0"));
  19. result.put("demo_read_ds_1", DataSourceUtil.createDataSource("demo_read_ds_1"));
  20. return result;
  21. }

相关参考