shardingsphere icon indicating copy to clipboard operation
shardingsphere copied to clipboard

version 4.0.0-RC2: key generated by SnowflakeShardingKeyGenerator mod 4 always is 0/1, expected 0/1/2/3

Open AL-Liang opened this issue 7 years ago • 9 comments

Hi. I found a fact about the sharding key generated by built-in snowflake algorithm. The result of the key mod 4 always is 0/1, to me, it is wierd. What I expected is, the result should be 0/1/2/3, and the key should evenly distributed to all the sharded tables. I am new to ShardingSphere and the snowflake algorithm. Hope I can get some help here.

I found out there is no this problem when keys are generated in a same millisecond.

Thanks.

`public final class PreciseModuloShardingTableAlgorithm implements PreciseShardingAlgorithm {

@Override
public String doSharding(final Collection<String> tableNames, final PreciseShardingValue<Long> shardingValue) {

    String tableName = (String) tableNames.toArray()[0];

    if(tableName.startsWith("table_a")) {
        for (String each : tableNames) {
            if (each.endsWith(shardingValue.getValue() % 4 + "")) {
                return each;
            }
        }
    }

    if (tableName.startsWith("table_b")) {
        for (String each : tableNames) {
            if (each.endsWith(shardingValue.getValue() % 2 + "")) {
                return each;
            }
        }
    }

    throw new UnsupportedOperationException();
}

}`

In database config class: ` DataSource getShardingDataSource() throws SQLException { ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();

    shardingRuleConfig.getTableRuleConfigs().add(new TableRuleConfiguration("table_a", "ds.table_a_$->{0..3}"));
    shardingRuleConfig.getBindingTableGroups().add("table_a");

    shardingRuleConfig.getTableRuleConfigs().add(new TableRuleConfiguration("table_b", "ds.admin_behaviour_track_$->{0..2}"));
    shardingRuleConfig.getBindingTableGroups().add("table_b");

    shardingRuleConfig.setDefaultKeyGeneratorConfig(new KeyGeneratorConfiguration("SNOWFLAKE", "id"));

    shardingRuleConfig.setDefaultTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("id", new PreciseModuloShardingTableAlgorithm()));

    Properties properties = new Properties();
    properties.setProperty(ShardingPropertiesConstant.SQL_SHOW.getKey(), "true");

    return ShardingDataSourceFactory.createDataSource(createDataSourceMap(), shardingRuleConfig, properties);
}`

AL-Liang avatar Oct 31 '19 08:10 AL-Liang

Can you change title for search friendly?

terrymanu avatar Oct 31 '19 14:10 terrymanu

Can you change title for search friendly?

Thanks for your reply. I am not sure how. Any advice?

AL-Liang avatar Oct 31 '19 15:10 AL-Liang

What is your version?

terrymanu avatar Nov 01 '19 09:11 terrymanu

What is your version?

	<dependency>
		<groupId>org.apache.shardingsphere</groupId>
		<artifactId>sharding-jdbc-core</artifactId>
		<version>4.0.0-RC2</version>
	</dependency>

AL-Liang avatar Nov 01 '19 10:11 AL-Liang

Since the SnowflakeShardingKeyGenerator has a left shift operation when generating a number at different timestamps, the remainder is always 0 or 1 when this number is used to modulate a number of 2^n(your number is 4).

haetao avatar Nov 05 '19 09:11 haetao

I'll fix it.

haetao avatar Nov 05 '19 09:11 haetao

Me too, and hope you'll get involved

geomonlin avatar Nov 05 '19 09:11 geomonlin

DISCUSS:

Writing the description and constraint of configuring the max vibration offset in the official document.

  1. explanation Using the snowflake algorithm as the partition key strategy, the max vibration offset needs to be configured.

  2. Constraints The max vibration offset is not recommended to take the number not 2 ^ n but less than 2 ^ 12 When the number of physical tables is 2 ^ n, the max vibration offset needs to be configured as 2 ^ n-1

Any Suggestions?

haetao avatar Nov 07 '19 11:11 haetao

When I use snowflake algorithm to mod 4, it seems still has this problem. This is my graddle info:

    implementation 'org.apache.shardingsphere:shardingsphere-jdbc-core:5.2.1'
   // org.springframework.boot version '2.5.14'
    implementation 'org.yaml:snakeyaml:1.33'

This is my config for shardingsphere:

mode:
  type: Standalone

dataSources:
  ds:
    dataSourceClassName: com.zaxxer.hikari.HikariDataSource
    driverClassName: com.mysql.cj.jdbc.Driver
    jdbcUrl:xxxx
    username: xxxx
    password: xxxx

rules:
  - !SHARDING
    tables:
      tb_user:
        actualDataNodes: ds.tb_user_${0..1}
        tableStrategy:
          standard:
            shardingColumn: id
            shardingAlgorithmName: tb_user_inline
        keyGenerateStrategy:
          column: id
          keyGeneratorName: snowflake
      tb_role:
        actualDataNodes: ds.tb_role_${0..1}
        tableStrategy:
          standard:
            shardingColumn: id
            shardingAlgorithmName: tb_role_inline
        keyGenerateStrategy:
          column: id
          keyGeneratorName: snowflake
      tb_user_role:
        actualDataNodes: ds.tb_user_role_${0..1}
        tableStrategy:
          standard:
            shardingColumn: id
            shardingAlgorithmName: tb_user_role_inline
        keyGenerateStrategy:
          column: id
          keyGeneratorName: snowflake
      tb_order:
        actualDataNodes: ds.tb_order_${0..3}
        tableStrategy:
          standard:
            shardingColumn: id
            shardingAlgorithmName: tb_order_inline
        keyGenerateStrategy:
          column: id
          keyGeneratorName: snowflake
    bindingTables:
      - tb_user,tb_role,tb_user_role
    shardingAlgorithms:
      tb_user_inline:
        type: INLINE
        props:
          algorithm-expression: tb_user_${id.toLong() % 2}
      tb_role_inline:
        type: INLINE
        props:
          algorithm-expression: tb_role_${id.toLong() % 2}
      tb_user_role_inline:
        type: INLINE
        props:
          algorithm-expression: tb_user_role_${id.toLong() % 2}
      tb_order_inline:
        type: INLINE
        props:
          algorithm-expression: tb_order_${id.toLong() % 4}
    keyGenerators:
      snowflake:
        type: SNOWFLAKE

props:
  sql-show: true

And when insert record to ds.tb_order_${0..3}, I find it will just insert into ds.tb_order_0 or ds.tb_order_1.

charlotte-xiao avatar Jun 05 '23 09:06 charlotte-xiao