读写分离

背景信息

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读写分离数据源名称-
writeDataSourceNameString写库数据源名称-
readDataSourceNamesList<String>读库数据源名称-
transactionalReadQueryStrategy (?)TransactionalReadQueryStrategy事务内读请求的路由策略,可选值:PRIMARY(路由至主库)、FIXED(同一事务内路由至固定数据源)、DYNAMIC(同一事务内路由至非固定数据源)DYNAMIC
loadBalancerName (?)String读库负载均衡算法名称轮询负载均衡算法

算法类型的详情,请参见内置负载均衡算法列表

操作步骤

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

配置示例

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

相关参考