设为首页 加入收藏

TOP

分布式主键解决方案之--Snowflake雪花算法(二)
2019-10-09 19:58:52 】 浏览:106
Tags:分布式 解决方案 --Snowflake 雪花 算法
lNextMillis(final long lastTimestamp) { 89 long timestamp = this.timeGen(); 90 while (timestamp <= lastTimestamp) { 91 timestamp = this.timeGen(); 92 } 93 return timestamp; 94 } 95 96 private long timeGen() { 97 return System.currentTimeMillis(); 98 } 99 100 /** 101 * <p> 102 * 获取 maxWorkerId 103 * </p> 104 */ 105 protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) { 106 StringBuffer mpid = new StringBuffer(); 107 mpid.append(datacenterId); 108 String name = ManagementFactory.getRuntimeMXBean().getName(); 109 if (!name.isEmpty()) { 110 /* 111 * GET jvmPid 112 */ 113 mpid.append(name.split("@")[0]); 114 } 115 /* 116 * MAC + PID 的 hashcode 获取16个低位 117 */ 118 return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1); 119 } 120 121 /** 122 * <p> 123 * 数据标识id部分 124 * </p> 125 */ 126 protected static long getDatacenterId(long maxDatacenterId) { 127 long id = 0L; 128 try { 129 InetAddress ip = InetAddress.getLocalHost(); 130 NetworkInterface network = NetworkInterface.getByInetAddress(ip); 131 if (network == null) { 132 id = 1L; 133 } else { 134 byte[] mac = network.getHardwareAddress(); 135 id = ((0x000000FF & (long) mac[mac.length - 1]) 136 | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6; 137 id = id % (maxDatacenterId + 1); 138 } 139 } catch (Exception e) { 140 System.out.println(" getDatacenterId: " + e.getMessage()); 141 } 142 return id; 143 } 144 }

 

3--测试

package com.anson;

/**
 * @description: TODO
 * @author: anson
 * @Date: 2019/10/7 22:16
 * @version: 1.0
 */
public class snow
{
    public static  void main(String[] args) throws Exception
    {
        try
        {


        IdWorker idw = new IdWorker(1,1);
        long ids = idw.nextId();


        for(int i=0;i<10000;i++)
        {
            ids = idw.nextId();
            System.out.println(ids);
        }

        }
        catch (Exception ex)
        {

        }

    }
}

结果如下图:

 

 程序生成了19位的有序数字,这个既解决了分布式ID生成唯一性问题,也解决了性能问题,建议系统ID设计都采用该算法生成。

 

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Elasticsearch实战-磁盘IO被打满 下一篇springcloud vue.js 微服务分布式..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目