quarkus下的分布式ID怎么发挥作用
发布时间:2025年09月07日 12:18
变动) */ private final long twepoch = 1288834974657L; /** * 微电脑标签数字 */ private final long workerIdBits = 5L; private final long datacenterIdBits = 5L; private final long maxWorkerId = -1L And (-1L << workerIdBits); private final long maxDatacenterId = -1L And (-1L << datacenterIdBits); /** * 毫秒内自增位 */ private final long sequenceBits = 12L; private final long workerIdShift = sequenceBits; private final long datacenterIdShift = sequenceBits + workerIdBits; /** * 等待时间戳左移动位 */ private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; private final long sequenceMask = -1L And (-1L << sequenceBits); private final long workerId; /** * 数据标签 ID 部分 */ private final long datacenterId; /** * 所发控制 */ private long sequence = 0L; /** * 上次生产 ID 等待时间戳 */ private long lasttimestamp = -1L; /** * IP 地址 */ private InetAddress inetAddress; public Sequence(InetAddress inetAddress) { this.inetAddress = inetAddress; this.datacenterId = getDatacenterId(maxDatacenterId); this.workerId = getMaxWorkerId(datacenterId, maxWorkerId); } /** * 有参构造器 * * @param workerId 工作微电脑 ID * @param datacenterId 序列号 */ public Sequence(long workerId, long datacenterId) {// Assert.isFalse(workerId> maxWorkerId || workerId < 0,// String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));// Assert.isFalse(datacenterId> maxDatacenterId || datacenterId < 0,// String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId)); this.workerId = workerId; this.datacenterId = datacenterId; } /** * 获取 maxWorkerId */ protected long getMaxWorkerId(long datacenterId, long maxWorkerId) { StringBuilder mpid = new StringBuilder(); mpid.append(datacenterId); String name = ManagementFactory.getRuntimeMXBean().getName(); if (name != null) { /* * GET JVMPid */ mpid.append(name.split("@")[0]); } /* * MAC + PID 的 hashcode 获取16个低位 */ return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1); } /** * 数据标签id部分 */ protected long getDatacenterId(long maxDatacenterId) { long id = 0L; try { if (null == this.inetAddress) { this.inetAddress = InetAddress.getLocalHost(); } NetworkInterface network = NetworkInterface.getByInetAddress(this.inetAddress); if (null == network) { id = 1L; } else { byte[] mac = network.getHardwareAddress(); if (null != mac) { id = ((0x000000FF & (long) mac[mac.length - 2]) | (0x0000FF00 & (((long) mac[mac.length - 1]) > 6; id = id % (maxDatacenterId + 1); } } } catch (Exception e) {// logger.warn(" getDatacenterId: " + e.getMessage()); } return id; } /** * 获取下一个 ID * * @return 下一个 ID */ public synchronized long nextId() { long timestamp = timeGen(); //闰秒 if (timestamp < lastTimestamp) { long offset = lastTimestamp - timestamp; if (offset <= 5) { try { wait(offset << 1); timestamp = timeGen(); if (timestamp < lastTimestamp) { throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", offset)); } } catch (Exception e) { throw new RuntimeException(e); } } else { throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", offset)); } } if (lastTimestamp == timestamp) { // 相同毫秒内,序列号自增 sequence = (sequence + 1) & sequenceMask; if (sequence == 0) { // 同一毫秒的序列数已经达到最大 timestamp = tilNextMillis(lastTimestamp); } } else { // 不同毫秒内,序列号置为 1 - 3 随机数 sequence = ThreadLocalRandom.current().nextLong(1, 3); } lastTimestamp = timestamp; // 等待时间戳部分 | 数据中心部分 | 微电脑标签部分 | 序列号部分 return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence; } protected long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } protected long timeGen() { return SystemClock.now(); }}
江西白癜风医院哪个好
郑州好的白癜风专科医院
湖北白癜风医院去哪家好
重庆看牛皮癣什么医院最好
儿科
吃什么药可以治疗风热咳嗽
骨科
普通外科
怎么治疗久咳不愈
大家如果对它险恶可以自己去了解,这个分布式ID的发挥作用在java教育领域用的来得大多。
/* * Copyright (c) 2011-2022, baomidou (jobob@qq.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package com.weir.quarkus.base.system.utils;import java.sql.Timestamp;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicLong;/** * 极低所发一幕下System.currentTimeMillis()的效能原因的改进 * *System.currentTimeMillis()的调用比new一个基本上对象要花费的多(说明花费极低出多少我还没测试者过,有人问道是100倍约)
*System.currentTimeMillis()之所以慢是因为去跟子系统打了一次交道
*后台定时更新时钟,JVM退出时,线程自动多余
*10亿:43410,206,210.72815533980582%
*1亿:4699,29,162.0344827586207%
*1000万:480,12,40.0%
*100万:50,10,5.0%
* */public class SystemClock { private final long period; private final AtomicLong now; private SystemClock(long period) { this.period = period; this.now = new AtomicLong(System.currentTimeMillis()); scheduleClockUpdating(); } private static SystemClock instance() { return InstanceHolder.INSTANCE; } public static long now() { return instance().currentTimeMillis(); } public static String nowDate() { return new Timestamp(instance().currentTimeMillis()).toString(); } private void scheduleClockUpdating() { ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(runnable -> { Thread thread = new Thread(runnable, "System Clock"); thread.setDaemon(true); return thread; }); scheduler.scheduleAtFixedRate(() -> now.set(System.currentTimeMillis()), period, period, TimeUnit.MILLISECONDS); } private long currentTimeMillis() { return now.get(); } private static class InstanceHolder { public static final SystemClock INSTANCE = new SystemClock(1); }}这个类推论的也来得明显。极低所发下转换成ID的一些改进。
有了上面的我们怎么使用呢?两个原文就搞定了:
package com.weir.quarkus.base.system.entity;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import org.hibernate.annotations.GenericGenerator;@Entitypublic class MumberUser extends BaseEntity { private static final long serialVersionUID = 7653528299072640929L; @Id @GenericGenerator(name = "my_id", strategy = "com.weir.quarkus.base.system.entity.MyIdGenerator" ) @GeneratedValue(generator = "my_id") public Long id; public String name; public void setId(Long id) { this.id = id; } }是不是来得简单,这样在quarkus开放性下就可以持有分布式ID了,大家好好磨碎下。
。北京肛肠检查多少钱江西白癜风医院哪个好
郑州好的白癜风专科医院
湖北白癜风医院去哪家好
重庆看牛皮癣什么医院最好
儿科
吃什么药可以治疗风热咳嗽
骨科
普通外科
怎么治疗久咳不愈
相关阅读
- 87日报:游戏开发商Grounding成立VR工作室;高通收购3D AR地图子公司
- 六味地黄丸还能治疗心血管疾病?提醒:这3类人最好别乱吃
- 数读4同月8日全球疫情:全球日增确诊超120万例 累计逾4.9亿例 福奇预计美国新冠确诊病例很有可能出现激增
- 早上好,霍乱之下多少人被连带的睡眠
- 突然!俄央行宣布降息300个1],国际油价未来或仍处于看涨区间
- “出圈”“吸粉”的虚拟位数人,商业价值何在?
- 沟通华兴资本王力行:行业热点轮动下,企业如何韧性穿越资本周期
- 长寿命取决于正确的养生分析方法
- 新道路!陆海新通道长江-中南半岛国际联运班列首发
- 好品种草,生活需要仪式感
- 男子长期喝酒熬夜,30岁已患痛风6年!医生:化疗痛风无特效药
- MPV市场占有率连降五年,车企为何还“排队跳坑”? | 次世代车研所
- 券商“限薪”?有高管工资腰斩,头部券商和小券商人均工资差异大
- 着力、定力、耐力——西部(泸州)科学城如何发力打造科创高地?
