C/C++教程

用Nacos分配Snowflake的Worker ID

本文主要是介绍用Nacos分配Snowflake的Worker ID,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

背景

Snowflake唯一ID算法大家都很熟悉,他是Twitter公司提出来的算法。但是对于workerId和 datacenterId的维护往往需要各项目自行设计。
基本都是基于zookeeper or 数据库 or Redis的。
本例就是用Nacos分配 worker id。

源码

https://gitee.com/JiaXiaohei/snowflake-nacos

原理

核心类:SnowflakeIdGenerator.class
基本原理:基于Nacos的监听服务 namingService.subscribe,监听服务下的实例列表变化。
注册一个服务到Nacos,如果服务列表发生变化,获取服务所有实例的Ip地址和端口,用本机Ip地址和端口判断本机在实例列表的index。

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.AbstractEventListener;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.DecimalFormat;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * SnowflakeId + Nacos
 */
@Component
public class SnowflakeIdGenerator {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private NacosServiceManager nacosServiceManager;

    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    private static SnowflakeIdWorker snowflakeIdWorker;

    private static int nodeId;

    @PostConstruct
    public void run() throws Exception {
        init();
    }

    /**
     * 获取雪花Id
     *
     * @return
     */
    public static long nextId() {
        return snowflakeIdWorker.nextId();
    }

    /**
     * 获取当前节点Id
     *
     * @return
     */
    public static int nodeId() {
        return nodeId;
    }

    /**
     * 获取当前服务所有节点 + 增加服务监听
     *
     * @throws NacosException
     */
    private void init() throws NacosException {
        NamingService namingService = nacosServiceManager.getNamingService(nacosDiscoveryProperties.getNacosProperties());
        namingService.subscribe(nacosDiscoveryProperties.getService(), new AbstractEventListener() {
            @Override
            public void onEvent(Event event) {
                if (-1 == nacosDiscoveryProperties.getPort()) {
                    return;
                }
                nodeId = calcNodeId(((NamingEvent) event).getInstances());
                if (nodeId > 1024) {
                    throw new IllegalArgumentException("Worker & Datacenter Id calc results exceed 1024");
                }
                long workerId = nodeId % 31;
                long datacenterId = (long) Math.floor((float) nodeId / 31);
                logger.info("nodeId:" + nodeId + " workerId:" + workerId + " datacenterId:" + datacenterId);
                snowflakeIdWorker = new SnowflakeIdWorker(workerId, datacenterId);
            }
        });
    }

    /**
     * 用ip+port计算服务列表的索引
     *
     * @param instanceList
     * @return
     */
    private int calcNodeId(List<Instance> instanceList) {
        List<Long> ipPosrList = instanceList.stream()
                .map(x -> dealIpPort(x.getIp(), x.getPort()))
                .sorted(Comparator.naturalOrder())
                .collect(Collectors.toList());
        return ipPosrList.indexOf(dealIpPort(nacosDiscoveryProperties.getIp(), nacosDiscoveryProperties.getPort()));
    }

    /**
     * ip补0 + 端口号
     *
     * @param ip
     * @param port
     * @return
     */
    private static Long dealIpPort(String ip, int port) {
        String[] ips = ip.split("\\.");
        StringBuilder sbr = new StringBuilder();
        for (int i = 0; i < ips.length; i++) {
            sbr.append(new DecimalFormat("000").format(Integer.parseInt(ips[i])));
        }
        return Long.parseLong(sbr.toString() + port);
    }

}

参考

雪花生成类:SnowflakeIdWorker.class 参考
https://blog.csdn.net/lq18050010830/article/details/89845790

这篇关于用Nacos分配Snowflake的Worker ID的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!