springboot~多節點應用里的雪花算法唯一性
雪花算法的唯一性,在單個節點中是可以保證的,對應kubernetes中的應用,如果是橫向擴展后,進行多副本的情況下,可能出現重復的ID,這需要我們按著pod_name進行一個workId的生成,我還是建議通過不引入第三方組件和網絡請求的前提下解決(jue)這個(ge)問題,所(suo)以我(wo)修改了kubernetes的yaml文件。
- k8s的yaml配置
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 3
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: my-container
image: my-image:latest
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name # 獲取當前 Pod 的名稱
- 字符串(0~1024)數字方法,通過掩碼的方式
public static int stringToNumber(String input) {
// 使用CRC32計算字符串的哈希值
CRC32 crc = new CRC32();
byte[] bytes = input.getBytes(StandardCharsets.UTF_8);
crc.update(bytes);
// 獲取哈希值并限制在0到1023之間
long hashValue = crc.getValue();
return (int) (hashValue % 1024);
}
- 獲取服務器機器碼
/**
* 獲取機器碼.
* @return
*/
public static String getUniqueMachineId() {
StringBuilder uniqueId = new StringBuilder();
try {
// 獲取本機的IP地址
InetAddress localHost = InetAddress.getLocalHost();
uniqueId.append(localHost.getHostAddress()).append("_");
// 獲取網絡接口并獲取MAC地址
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
byte[] mac = networkInterface.getHardwareAddress();
if (mac != null) {
for (int i = 0; i < mac.length; i++) {
uniqueId.append(String.format("%02X", mac[i]));
if (i < mac.length - 1) {
uniqueId.append("-");
}
}
uniqueId.append("_");
}
}
// 添加系統信息作為補充
String osName = System.getProperty("os.name");
String osVersion = System.getProperty("os.version");
String userName = System.getProperty("user.name");
uniqueId.append(osName).append("_").append(osVersion).append("_").append(userName);
}
catch (Exception e) {
e.printStackTrace();
}
return uniqueId.toString();
}
- ID生成器的改進
@Slf4j
public class IdUtils {
static SnowFlakeGenerator snowFlakeGenerator;
public static String generateId() {
if (snowFlakeGenerator == null) {
long podNameCode = stringToNumber(Optional.ofNullable(System.getenv("POD_NAME")).orElse(stringToNumber(getUniqueMachineId())));
log.debug("podNameCode:{}", podNameCode);
snowFlakeGenerator = new SnowFlakeGenerator(podNameCode);
}
return snowFlakeGenerator.hexNextId();
}