首页 > 编程知识 正文

号码生成器,随机昵称生成器

时间:2023-05-06 20:25:22 阅读:146040 作者:4403

package com.wangwangyouxuan.utils; 导入Java.lang.management.management factory; import Java.net.inet地址; import Java.net.network接口; /** * p名称: IdWorker.java/p * p说明:分布式自生长ID/p * pre * Twitter的Snowflake JAVA实现方案* /pre *核心代码是该IdWorker类的实现分别用0表示1位-分割的部分的作用: *1||| 0---00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000下一个41位等于毫秒级别的时间,*然后是5位数据中心识别位、5位计算机ID (实际上是线程识别,而不是标识符),以及12位该毫秒内当前毫秒内的计数*这一好处是总体上根据时间的推移进行排序,在整个分布式系统中不会发生ID冲突(由数据中心和计算机ID区分),而且效率很高。 测试结果显示,snowflake每秒产生26万ID左右,完全能够满足需求。 * p * 64位ID(42 (毫秒)5)设备id (5)业务代码(12 )重复累积) )/publicclassidworker(/时间开始标志点作为基准,一般判断为系统最近时间(不可变更) //数据中心识别位数privatefinalstaticlongdatacenteridbits=5l; //机器ID的最大值privatefinalstaticlongmaxworkerid=-1l ^ (-1 lworkeridbits; //数据中心ID最大值privatefinalstaticlongmaxdatacenterid=-1l ^ (-1 ldatacenteridbits; //毫秒内隐私保护措施克隆服务质量=12l; //将机器ID向左偏移12位,使privatefinalstaticlongworkeridshift=sequence bits; //数据中心ID向左17位私有身份证明数据中心id=sequencebitsworkeridbits; //小时毫秒22位私有身份证明连接时间timestampleftshift=sequencebitsworkeridbitsdatacenteridbits; 私密性统计信息克隆sequencemask=-1l ^ (-1 lsequencebits; /*上次生产id时间戳*/privatestaticlonglasttimestamp=-1l; //0,私有长序列=0l; 私有金融长工作器id; //数据标识id部分私有金融长数据中心id; publicidworker ((this.data centerid=get data centerid ) Maxdatacenterid ); this.worker id=getmaxWorkerId (数据中心,maxworkerid ); } /** * @param workerId *机床id * @ param数据中心*序列号*/publicidworker(longworkerid, longdatacenterid(if )工作器iii (iii ) thrownewillegalargumentexception ) string.format (datacenterId > maxDatacenterId || datacenterId < 0) { throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId)); } this.workerId = workerId; this.datacenterId = datacenterId; } /** * 获取下一个ID * * @return */ public synchronized long nextId() { long timestamp = timeGen(); if (timestamp < lastTimestamp) { throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } if (lastTimestamp == timestamp) { // 当前毫秒内,则+1 sequence = (sequence + 1) & sequenceMask; if (sequence == 0) { // 当前毫秒内计数满了,则等待下一秒 timestamp = tilNextMillis(lastTimestamp); } } else { sequence = 0L; } lastTimestamp = timestamp; // ID偏移组合生成最终的ID,并返回ID long nextId = ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence; return nextId; } private long tilNextMillis(final long lastTimestamp) { long timestamp = this.timeGen(); while (timestamp <= lastTimestamp) { timestamp = this.timeGen(); } return timestamp; } private long timeGen() { return System.currentTimeMillis(); } /** * <p> * 获取 maxWorkerId * </p> */ protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) { StringBuffer mpid = new StringBuffer(); mpid.append(datacenterId); String name = ManagementFactory.getRuntimeMXBean().getName(); if (!name.isEmpty()) { /* * GET jvmPid */ mpid.append(name.split("@")[0]); } /* * MAC + PID 的 hashcode 获取16个低位 */ return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1); } /** * <p> * 数据标识id部分 * </p> */ protected static long getDatacenterId(long maxDatacenterId) { long id = 0L; try { InetAddress ip = InetAddress.getLocalHost(); NetworkInterface network = NetworkInterface.getByInetAddress(ip); if (network == null) { id = 1L; } else { byte[] mac = network.getHardwareAddress(); id = ((0x000000FF & (long) mac[mac.length - 1]) | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6; id = id % (maxDatacenterId + 1); } } catch (Exception e) { System.out.println(" getDatacenterId: " + e.getMessage()); } return id; } public static void main(String[] args) { IdWorker idWorker = new IdWorker(0,0);//一秒生成26万个ID for (int i = 0; i <10000; i++) { long nextId=idWorker.nextId();System.out.println(nextId); } }}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。