SnowflakeShardingKeyGenerator may require a default workId implementation or an interface that can be easily set
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
}
}
Users should config worker.id in different nodes.