Skip to content

Commit

Permalink
SnowflakeId配置优化
Browse files Browse the repository at this point in the history
  • Loading branch information
binking338 committed Aug 12, 2024
1 parent 92ac3eb commit 62c7dd3
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,9 @@ public void release() {
public boolean pong() {
return true;
}

@Override
public void remind(){

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,28 @@
*/
public interface SnowflakeWorkerIdDispatcher {
/**
* 获取
* 获取WorkerId占用
* @param workerId 指定workerId
* @param datacenterId 指定datacenterId
* @return
*/
long acquire(Long workerId, Long datacenterId);

/**
* 释放占用
* 释放WorkerId占用
* @return
*/
void release();

/**
* 心跳上报
* 如果长期失联,需通知运维介入
* @return
*/
boolean pong();

/**
* 心跳失败累计到一定次数,提醒运维或相关人员,以便介入处理
*/
void remind();
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@
@RequiredArgsConstructor
@Slf4j
public class SnowflakeAutoConfiguration {
private final SnowflakeProperties properties;

int pongContinuousErrorCount = 0;
SnowflakeWorkerIdDispatcher snowflakeWorkerIdDispatcher;

@Bean
Expand All @@ -34,6 +37,7 @@ public SnowflakeIdGenerator snowflakeIdGenerator(SnowflakeWorkerIdDispatcher sno
@Bean
@ConditionalOnMissingBean(SnowflakeWorkerIdDispatcher.class)
public DefaultSnowflakeWorkerIdDispatcher defaultSnowflakeWorkerIdDispatcher(SnowflakeProperties properties) {
log.warn("默认调度器需通过手工配置完成WorkerId、DatacenterId分发,有重复分配风险!!!请根据项目实际情况自行实现SnowflakeWorkerIdDispatcher。");
DefaultSnowflakeWorkerIdDispatcher dispatcher = new DefaultSnowflakeWorkerIdDispatcher(
properties.getWorkerId() == null ? 0 : properties.getWorkerId().longValue(),
properties.getDatacenterId() == null ? 0 : properties.getDatacenterId().longValue()
Expand All @@ -44,8 +48,15 @@ public DefaultSnowflakeWorkerIdDispatcher defaultSnowflakeWorkerIdDispatcher(Sno

@Scheduled(cron = "0 */1 * * * ?")
public void pong() {
if (!snowflakeWorkerIdDispatcher.pong()) {
if (snowflakeWorkerIdDispatcher.pong()) {
log.info("SnowflakeWorkerIdDispatcher 心跳上报成功");
pongContinuousErrorCount = 0;
} else {
log.error("SnowflakeWorkerIdDispatcher 心跳上报失败");
pongContinuousErrorCount ++;
if(pongContinuousErrorCount > properties.getMaxPongContinuousErrorCount()){
snowflakeWorkerIdDispatcher.remind();
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@
public class SnowflakeProperties {
Long workerId = null;
Long datacenterId = null;
int maxPongContinuousErrorCount = 10;
}

0 comments on commit 62c7dd3

Please sign in to comment.