springboot~多节点应用里的雪花算法唯一性

雪花算法的唯一性,在单个节点中是可以保证的,对应kubernetes中的应用,如果是横向扩展后,进行多副本的情况下,可能出现重复的ID,这需要我们按着pod_name进行一个workId的生成,我还是建议通过不引入第三方组件和网络请求的前提下解决这个问题,所以我修改了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 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();
    }
    

    ```

文章整理自互联网,只做测试使用。发布者:Lomu,转转请注明出处:https://www.it1024doc.com/5012.html

(0)
LomuLomu
上一篇 2024 年 12 月 31 日 上午4:16
下一篇 2024 年 12 月 31 日

相关推荐

  • 【GreatSQL优化器-10】find_best_ref

    【GreatSQL优化器-10】find_best_ref 一、find_best_ref介绍 GreatSQL的优化器对于join的表需要根据行数和cost来确定最后哪张表先执行哪张表后执行,这里面就涉及到预估满足条件的表数据,在keyuse_array数组有值的情况下,会用find_best_ref函数来通过索引进行cost和rows的估计,并且会找出最…

    2025 年 1 月 15 日
    59400
  • 【GreatSQL优化器-09】make_join_query_block

    【GreatSQL优化器-09】make_join_query_block 一、make_join_query_block介绍 GreatSQL优化器对于多张表join的连接顺序在前面的章节介绍过的best_access_path函数已经执行了,接着就是把where条件进行切割然后推给合适的表。这个过程就是由函数make_join_query_block来执…

    2025 年 1 月 12 日
    38900
  • 实战指南:理解 ThreadLocal 原理并用于Java 多线程上下文管理

    目录 一、ThreadLocal基本知识回顾分析 (一)ThreadLocal原理 (二)既然ThreadLocalMap的key是弱引用,GC之后key是否为null? (三)ThreadLocal中的内存泄漏问题及JDK处理方法 (四)部分核心源码回顾 ThreadLocal.set()方法源码详解 ThreadLocalMap.get()方法详解 Th…

    2025 年 1 月 22 日
    77600
  • IntelliJ IDEA激活破解补丁下载(IDEA永久激活破解)

    IDEA最新永久激活破解教程:https://www.it1024doc.com/4100.html 破解补丁下载 因为提取的人数比较多,导致分享的百度网盘链接容易被封: 所以需要下载破解补丁的,扫描下方公众号,关注后,发送关键字:0622 即可免费无套路的获取破解补丁!

    2024 年 6 月 22 日
    9.6K00
  • 一问一答学习PyQT6,对比WxPython和PyQt6的差异

    在我的基于WxPython的跨平台框架完成后,对WxPython的灵活性以及强大功能有了很深的了解,在跨平台的桌面应用上我突然对PyQt6的开发也感兴趣,于是准备了开发环境学习PyQt 6,并对比下WxPython的差异来进行深入的了解,发现它们很多理念和做法是如此的类似。 1、pyqt6都有那些布局控件? PyQt6 提供了多种布局控件,帮助开发者轻松地将…

    2025 年 1 月 15 日
    53400

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信