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了,大家好好磨碎下。
。北京肛肠检查多少钱江西白癜风医院哪个好
郑州好的白癜风专科医院
湖北白癜风医院去哪家好
重庆看牛皮癣什么医院最好
儿科
吃什么药可以治疗风热咳嗽
骨科
普通外科
怎么治疗久咳不愈
相关阅读
- 71分钟,5-5!法网破发战,纳达尔艰难保发,金锁崩盘,0-2落后?
- 华为50大厂商之一——深南电路
- 中超首球先生是谁?转会费仅25万 曾征战西甲法甲 单防C罗
- 2022赛季中超联赛开赛 18支球队三总决赛比拼
- 泰山队揭幕战球员打分,贾德松防空出色获最佳,克雷桑打分最低
- 弗维列夫意外受伤,纳达尔主动上前关怀!祝福他!法网半决赛中断
- 国乒端午节亲手包馒头,马龙孙颖莎陈梦齐上阵,樊振东包得最像样
- 高即战力潜在落顺位完成试训,湖人还在为南湾湖人继续找人?
- 如今足球:意大利vs德国 匈牙利vs英格兰
- 达格利什:孙子外孙也是利物浦球迷,这家俱乐部非常特别
- 麦克马纳曼:安菲尔德的场面令人惊叹,确实能让对手感到害怕
- 湖人试训圣母大学内线大将,他也是一个潜在的落选中?
- 帕洛尔:穆托夫并不需要争取丹朱马,迪马利亚符合塔帅的体系
- 今日足球:横滨樱花vs湘南海洋 名古屋鲸八vs京都不死鸟