shardingsphere icon indicating copy to clipboard operation
shardingsphere copied to clipboard

SnowflakeShardingKeyGenerator may require a default workId implementation or an interface that can be easily set

Open azraelee opened this issue 6 years ago • 1 comments

The default workId of the current SnowflakeShardingKeyGenerator is 0, which will cause key conflicts during distributed deployment. Forgot to say, my version is 4.0.0 The official documentation also did not make it clear how to modify the workId. I looked at the source code and finally found it, using the NewInstanceServiceLoader#newServiceInstances method, to get the actual SnowflakeShardingKeyGenerator object Then call getProperties ().setProperty("worker.id", "myWorkIdNumber") to resolve the generated key conflict I hope the next version can easily set worker.id, max.vibration.offse, max.tolerate.time.difference.milliseconds

@Component
@Slf4j
public class ShardingSphereWorkerIdConfig {

    @PostConstruct
    public void init() {
        Collection<ShardingKeyGenerator> shardingKeyGenerators = NewInstanceServiceLoader.newServiceInstances(ShardingKeyGenerator.class);
        for (ShardingKeyGenerator shardingKeyGenerator : shardingKeyGenerators) {
            if (shardingKeyGenerator instanceof SnowflakeShardingKeyGenerator) {
                Long workId = generateWorkId();
                shardingKeyGenerator.getProperties().setProperty("worker.id", workId.toString());
            }
        }
    }

    private long generateWorkId() {
       //xxx
    }
}

azraelee avatar May 28 '20 08:05 azraelee

Users should config worker.id in different nodes.

kimmking avatar May 28 '20 11:05 kimmking