数据分片路由缓存

背景信息

该项功能为实验性功能,需要与数据分片功能同时使用。 数据分片路由缓存会将逻辑 SQL、分片键实际参数值、路由结果放入缓存中,以空间换时间,减少路由逻辑对 CPU 的使用。

建议仅在满足以下条件的情况下启用:

  • 纯 OLTP 场景
  • ShardingSphere 进程所在机器 CPU 已达到瓶颈
  • CPU 开销主要在于 ShardingSphere 路由逻辑
  • 所有 SQL 已经最优且每次 SQL 执行都能命中单一分片

在不满足以上条件的情况下使用,可能对 SQL 的执行延时不会有明显改善,同时会增加内存的压力。

参数解释

类名称:org.apache.shardingsphere.sharding.api.config.cache.ShardingCacheConfiguration

可配置属性:

名称数据类型说明默认值
allowedMaxSqlLengthint允许缓存的 SQL 长度限制-
routeCacheorg.apache.shardingsphere.sharding.api.config.cache.ShardingCacheOptionsConfiguration路由缓存-

类名称:org.apache.shardingsphere.sharding.api.config.cache.ShardingCacheOptionsConfiguration

可配置属性:

名称数据类型说明默认值
softValuesboolean是否软引用缓存值-
initialCapacityint缓存初始容量-
maximumSizeint缓存最大容量-

配置示例

  1. public final class ShardingDatabasesAndTablesConfigurationPrecise {
  2. @Override
  3. public DataSource getDataSource() throws SQLException {
  4. return ShardingSphereDataSourceFactory.createDataSource(createDataSourceMap(), Arrays.asList(createShardingRuleConfiguration(), createBroadcastRuleConfiguration())), new Properties());
  5. }
  6. private ShardingRuleConfiguration createShardingRuleConfiguration() {
  7. ShardingRuleConfiguration result = new ShardingRuleConfiguration();
  8. result.getTables().add(getOrderTableRuleConfiguration());
  9. result.getTables().add(getOrderItemTableRuleConfiguration());
  10. // ...
  11. result.setShardingCache(new ShardingCacheConfiguration(512, new ShardingCacheConfiguration.RouteCacheConfiguration(65536, 262144, true)));
  12. return result;
  13. }
  14. private ShardingTableRuleConfiguration getOrderTableRuleConfiguration() {
  15. ShardingTableRuleConfiguration result = new ShardingTableRuleConfiguration("t_order", "demo_ds_${0..1}.t_order_${[0, 1]}");
  16. result.setKeyGenerateStrategy(new KeyGenerateStrategyConfiguration("order_id", "snowflake"));
  17. result.setAuditStrategy(new ShardingAuditStrategyConfiguration(Collections.singleton("sharding_key_required_auditor"), true));
  18. return result;
  19. }
  20. private ShardingTableRuleConfiguration getOrderItemTableRuleConfiguration() {
  21. ShardingTableRuleConfiguration result = new ShardingTableRuleConfiguration("t_order_item", "demo_ds_${0..1}.t_order_item_${[0, 1]}");
  22. result.setKeyGenerateStrategy(new KeyGenerateStrategyConfiguration("order_item_id", "snowflake"));
  23. return result;
  24. }
  25. private Map<String, DataSource> createDataSourceMap() {
  26. Map<String, DataSource> result = new HashMap<>();
  27. result.put("demo_ds_0", DataSourceUtil.createDataSource("demo_ds_0"));
  28. result.put("demo_ds_1", DataSourceUtil.createDataSource("demo_ds_1"));
  29. return result;
  30. }
  31. private BroadcastRuleConfiguration createBroadcastRuleConfiguration() {
  32. return new BroadcastRuleConfiguration(Collections.singletonList("t_address"));
  33. }
  34. }

相关参考