The uniqueness of the snowflake algorithm can be guaranteed in a single node, corresponding to the application in kubernetes. If it is expanded horizontally and multiple copies are performed, duplicate IDs may appear. This requires us to generate a workId according to pod_name. I still recommend that you use it.No third-party components are introduced
This problem is solved under the premise of network request, so I modified the yaml file of kubernetes.
- yaml configuration of k8s
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: # Get the current one Pod Name of
- String (0~1024) numeric method, through masking
public static int stringToNumber(String input) { // Use CRC32 to calculate the hash value of a string CRC32 crc = new CRC32(); byte[] bytes = (StandardCharsets.UTF_8); (bytes); // Get the hash value and limit it to 0 to 1023 long hashValue = (); return (int) (hashValue % 1024); }
- Get server machine code
/** * Get the machine code. * @return */ public static String getUniqueMachineId() { StringBuilder uniqueId = new StringBuilder(); try { // Get the IP address of the machine InetAddress localHost = (); (()).append("_"); // Get the network interface and get the MAC address Enumeration<NetworkInterface> networkInterfaces = (); while (()) { NetworkInterface networkInterface = (); byte[] mac = (); if (mac != null) { for (int i = 0; i < ; i++) { (("%02X", mac[i])); if (i < - 1) { ("-"); } } ("_"); } } // Add system information as a supplement String osName = (""); String osVersion = (""); String userName = (""); (osName).append("_").append(osVersion).append("_").append(userName); } catch (Exception e) { (); } return (); }
- Implementation of ID generator
@Slf4j public class IdUtils { static SnowFlakeGenerator snowFlakeGenerator; public static String generateId() { if (snowFlakeGenerator == null) { long podNameCode = stringToNumber((("POD_NAME")).orElse(stringToNumber(getUniqueMachineId()))); ("podNameCode:{}", podNameCode); snowFlakeGenerator = new SnowFlakeGenerator(podNameCode); } return (); }
This is the article about the uniqueness of snowflake algorithms in springboot~Multi-node applications. For more relevant content on the uniqueness of snowflake algorithms, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!