雪花算法工具类

@Component
@Slf4j
public class SnowflakeUtil {
    private Snowflake snowflake = IdUtil.createSnowflake(getWorkId(), getDataCenterId());

    public synchronized long snowflakeId() {
        return snowflake.nextId();
    }

    public synchronized long snowflakeId(long workerId, long dataCenterId) {
        Snowflake snowflake = IdUtil.createSnowflake(workerId, dataCenterId);
        return snowflake.nextId();
    }

    /**
     * @Author gj
     * @Description 获取机器id
     * @Params
     * @Return
     * @Date 2021/5/26 13:52
     */
    private static Long getWorkId() {
        try {
            String hostAddress = Inet4Address.getLocalHost().getHostAddress();
            int[] ints = StringUtils.toCodePoints(hostAddress);
            int sums = 0;
            for (int b : ints) {
                sums += b;
            }
            return (long) (sums % 32);
        } catch (UnknownHostException e) {            // 如果获取失败,则使用随机数备用
            return RandomUtils.nextLong(0, 31);
        }
    }

    /**
     * @Author gj
     * @Description获取数据id
     * @Params
     * @Return
     * @Date 2021/5/26 13:52
     */
    protected static long getDataCenterId() {
        long id = 0L;
        try {
            //获取本机(或者服务器ip地址)
            //DESKTOP-123SDAD/192.168.1.87
            InetAddress ip = InetAddress.getLocalHost();
            NetworkInterface network = NetworkInterface.getByInetAddress(ip);
            //一般不是null会进入else
            if (network == null) {
                id = 1L;
            } else {
                //获取物理网卡地址
                byte[] mac = network.getHardwareAddress();
                if (null != mac) {
                    id = ((0x000000FF & (long) mac[mac.length - 2]) |
                            (0x0000FF00 & (((long) mac[mac.length - 1]) << 8))) >> 6;
                    id = id % (31 + 1);
                }
            }
        } catch (Exception e) {
            return RandomUtils.nextLong(0, 31);
        }
        return id;
    }
}

pom

<dependency>
   <groupId>cn.hutool</groupId>
   <artifactId>hutool-core</artifactId>
   <version>${hutool.version}</version>
</dependency>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值