45 lines
1.1 KiB
Java
45 lines
1.1 KiB
Java
|
package com.isu.gaswellwatch.config;
|
||
|
|
||
|
import cn.hutool.core.lang.Snowflake;
|
||
|
import cn.hutool.core.net.NetUtil;
|
||
|
import cn.hutool.core.util.IdUtil;
|
||
|
import jakarta.annotation.PostConstruct;
|
||
|
import lombok.extern.slf4j.Slf4j;
|
||
|
import org.springframework.beans.factory.annotation.Value;
|
||
|
import org.springframework.stereotype.Component;
|
||
|
|
||
|
|
||
|
@Slf4j
|
||
|
@Component
|
||
|
public class SnowflakeConfig {
|
||
|
|
||
|
/**
|
||
|
* 为终端ID
|
||
|
*/
|
||
|
@Value("${snowflake.worker}")
|
||
|
private long workerId;
|
||
|
/**
|
||
|
* 数据中心ID
|
||
|
*/
|
||
|
@Value("${snowflake.data-center}")
|
||
|
private long dataCenterId;
|
||
|
|
||
|
private final Snowflake snowFlake = IdUtil.createSnowflake(workerId, dataCenterId);
|
||
|
|
||
|
@PostConstruct
|
||
|
public void init() {
|
||
|
workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
|
||
|
log.info("当前机器的workId:{}", workerId);
|
||
|
}
|
||
|
|
||
|
public synchronized long snowflakeId() {
|
||
|
return snowFlake.nextId();
|
||
|
}
|
||
|
|
||
|
public synchronized long snowflakeId(long workerId, long dataCenterId) {
|
||
|
Snowflake snowflake = IdUtil.createSnowflake(workerId, dataCenterId);
|
||
|
return snowflake.nextId();
|
||
|
}
|
||
|
}
|
||
|
|