当前位置: 首页 > 编程日记 > 正文

生成24位字符串ID__IdGenerator.java

此工具类用于生成24位字符串ID,唯一不重复。

直接通过 IdGenerator.get() 获取。

 

源码如下:(点击下载源码 - IdGenerator.java )

  1 import java.net.NetworkInterface;
  2 import java.nio.ByteBuffer;
  3 import java.nio.ByteOrder;
  4 import java.util.Enumeration;
  5 
  6 /**
  7  * 生成24位字符串ID
  8  * 
  9  */
 10 public class IdGenerator implements Comparable<IdGenerator> {
 11 
 12     /**
 13      * 调用该方法获取24位字符串ID
 14      * @return
 15      */
 16     public static String get() {
 17         return new IdGenerator().toString();
 18     }
 19 
 20     public IdGenerator() {
 21         _time = _gentime;
 22         _machine = _genmachine;
 23         synchronized (_incLock) {
 24             _inc = _nextInc++;
 25         }
 26         _new = true;
 27     }
 28 
 29     public int hashCode() {
 30         return _inc;
 31     }
 32 
 33     public String toStringMongod() {
 34         byte b[] = toByteArray();
 35 
 36         StringBuilder buf = new StringBuilder(24);
 37 
 38         for (int i = 0; i < b.length; i++) {
 39             int x = b[i] & 0xFF;
 40             String s = Integer.toHexString(x);
 41             if (s.length() == 1)
 42                 buf.append("0");
 43             buf.append(s);
 44         }
 45 
 46         return buf.toString();
 47     }
 48 
 49     public byte[] toByteArray() {
 50         byte b[] = new byte[12];
 51         ByteBuffer bb = ByteBuffer.wrap(b);
 52         bb.putInt(_inc);
 53         bb.putInt(_machine);
 54         bb.putInt(_time);
 55         reverse(b);
 56         return b;
 57     }
 58 
 59     static void reverse(byte[] b) {
 60         for (int i = 0; i < b.length / 2; i++) {
 61             byte t = b[i];
 62             b[i] = b[b.length - (i + 1)];
 63             b[b.length - (i + 1)] = t;
 64         }
 65     }
 66 
 67     static String _pos(String s, int p) {
 68         return s.substring(p * 2, (p * 2) + 2);
 69     }
 70 
 71     public String toString() {
 72         return toStringMongod();
 73     }
 74 
 75     public int compareTo(IdGenerator id) {
 76         if (id == null)
 77             return -1;
 78 
 79         long xx = id.getTime() - getTime();
 80         if (xx > 0)
 81             return -1;
 82         else if (xx < 0)
 83             return 1;
 84 
 85         int x = id._machine - _machine;
 86         if (x != 0)
 87             return -x;
 88 
 89         x = id._inc - _inc;
 90         if (x != 0)
 91             return -x;
 92 
 93         return 0;
 94     }
 95 
 96     public int getMachine() {
 97         return _machine;
 98     }
 99 
100     public long getTime() {
101         long z = _flip(_time);
102         return z * 1000;
103     }
104 
105     public int getInc() {
106         return _inc;
107     }
108 
109     final int _time;
110     final int _machine;
111     final int _inc;
112 
113     boolean _new;
114 
115     static int _flip(int x) {
116         byte b[] = new byte[4];
117         ByteBuffer bb = ByteBuffer.wrap(b);
118         bb.order(ByteOrder.LITTLE_ENDIAN);
119         bb.putInt(x);
120         bb.flip();
121         bb.order(ByteOrder.BIG_ENDIAN);
122         return bb.getInt();
123     }
124 
125     private static int _nextInc = (new java.util.Random()).nextInt();
126     private static final String _incLock = new String("IdGenerator._incLock");
127 
128     private static int _gentime = _flip((int) (System.currentTimeMillis() / 1000));
129 
130     static final Thread _timeFixer;
131     private static final int _genmachine;
132     static {
133         try {
134             final int machinePiece;
135             {
136                 StringBuilder sb = new StringBuilder();
137                 Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
138                 while (e.hasMoreElements()) {
139                     NetworkInterface ni = e.nextElement();
140                     sb.append(ni.toString());
141                 }
142                 machinePiece = sb.toString().hashCode() << 16;
143             }
144 
145             final int processPiece = java.lang.management.ManagementFactory.getRuntimeMXBean().getName().hashCode() & 0xFFFF;
146             _genmachine = machinePiece | processPiece;
147         } catch (java.io.IOException ioe) {
148             throw new RuntimeException(ioe);
149         }
150 
151         _timeFixer = new Thread("IdGenerator-TimeFixer") {
152             public void run() {
153                 while (true) {
154                     try {
155                         Thread.sleep(499);
156                     } catch (InterruptedException e) {
157                     }
158                     _gentime = _flip((int) (System.currentTimeMillis() / 1000));
159                 }
160             }
161         };
162         _timeFixer.setDaemon(true);
163         _timeFixer.start();
164     }
165 
166 }

转载于:https://www.cnblogs.com/zhoubang521/p/5200309.html

相关文章:

IDEA构建一个mybatis项目

目录结构如下&#xff1a; 在pom.xml中配置需要的jar包 <dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.3.0</version></dependency><dependency><gro…

小程序在canvas上层做图片滚动

实现该功能踩过的坑 1.swiper的swiper-item中image图片无法在canvas的上层显示&#xff0c;会被canvas 覆盖 2.swiper的swiper-item 里面放 cover-image 会样式错乱 3.scroll-view里面放 cover-image 会样式错乱 解决方案&#xff1a;使用CSS样式实现&#xff0c;超出部分隐…

React是如何在后台运行的

React is a very popular JavaScript library. With over 5.5 million weekly downloads, React is enjoying great popularity. But not a lot of React developers know how React works under the hood. React是一个非常流行JavaScript库。 每周的下载量超过550万&#xff0…

H5播放视频流

代码 <html> <head> <title>视频直播</title> <meta charset"utf-8"> <link href"http://vjs.zencdn.net/5.5.3/video-js.css" rel"stylesheet"> <!-- If youd like to support IE8 --> <!-…

获取Java系统相关信息

1 package com.test;2 3 import java.util.Properties;4 import java.util.Map.Entry;5 6 import org.junit.Test;7 8 public class SystemTest {9 10 /** 11 * 获取Java系统相关信息 12 * throws Exception 13 */ 14 Test 15 public void testSys…

如何使用FaunaDB + GraphQL

I have one or two projects I maintain on Netlify, in addition to hosting my blog there. It’s an easy platform to deploy to, and has features for content management (CMS) and lambda functions (by way of AWS).除了在其中托管我的博客外&#xff0c;我在Netlify上…

POJ 1414 Life Line(搜索)

题意&#xff1a; 给定一块正三角形棋盘&#xff0c;然后给定一些棋子和空位&#xff0c;棋子序号为a&#xff08;1<a<9)&#xff0c;group的定义是相邻序号一样的棋子。 然后到C&#xff08;1<N<9&#xff09;棋手在空位放上自己序号C的棋子&#xff0c; 放完后&a…

MySQL_数据库操作语句

ZC&#xff1a;数据库名/表名/字段名 都使用小写字母 1、 创建 数据库 和 表 的时候&#xff0c;都要指定 编码方式为 utf-8 ! ! ! 因为 执行命令“show variables like char%;”后可以看到 character_set_database 的值为 latin1&#xff0c;即 默认创建数据库是使用的 字符编…

H5打开预览PDF,PPT等文件

实现代码&#xff1a; pdfUrl 写你的文件路径 <iframe :src"//www.xdocin.com/xdoc?_functo&_formathtml&_cache1&_xdocpdfUrl"width"100%"height"100%"frameborder"0"> </iframe> 可以直接打开看

广播代码_代码广播:专为编码而设计的24/7音乐

广播代码阅读本文时&#xff0c;您可以继续阅读Code Radio。 (You can go ahead and start listening to Code Radio while you read this) Most developers I know listen to music while they code. When the meetings are over, the headphones come out.我认识的大多数开发…

从 Android 静音看正确的查bug的姿势?

0、写在前面 没抢到小马哥的红包&#xff0c;无心回家了&#xff0c;回公司写篇文章安慰下自己TT。。话说年关难过&#xff0c;bug多多&#xff0c;时间久了难免头昏脑热&#xff0c;不辨朝暮&#xff0c;难识乾坤。。。艾玛&#xff0c;扯远了&#xff0c;话说谁没踩过坑&…

SecureCRT中sqlplus,使用Backspace删除时 ^H^H

在“Session Options” - "Terminal" - "Mapped Keys" - "Other mappings"&#xff0c;选择“Backspace sends delete”。转载于:https://www.cnblogs.com/Clark-cloud-database/p/7813867.html

在vue中使用vuex,修改state的值示例

1、 安装 vuex npm install vuex -S 2、在目录下创建store文件 3、 在store.js编辑一个修改state的方法 然后在mian.js中全局引入 最后在组件中使用 这个的功能是运用mutations 修改state中的值

软件开发 自由职业_自由职业? 这里有7个可以出售软件开发服务的地方

软件开发 自由职业Web developers need clients. This is true whether you are a full-time freelancer or you freelance on the side.Web开发人员需要客户。 无论您是全职自由职业者&#xff0c;还是身旁的自由职业者&#xff0c;都是如此。 So if youve ever asked: "…

生成SSH key

1、打开终端&#xff0c;输入下面的代码 &#xff0c;注意&#xff1a;$your_email为占位符&#xff0c;此处输入你自己的email ssh-keygen -t rsa -C "$your_email" 2、查看生成的公钥&#xff0c;输入下面的代码 cat ~/.ssh/id_rsa.pub 3、复制公钥&#xff08;公钥…

[转载]二叉树(BST,AVT,RBT)

二叉查找树(Binary Search Tree)是满足如下性质的二叉树&#xff1a;①若它的左子树非空&#xff0c;则左子树上所有结点的值均小于根结点的值&#xff1b;②若它的右子树非空&#xff0c;则右子树上所有结点的值均大于根结点的值&#xff1b;③左、右子树本身又各是一棵二叉查…

Invalid Host header 问题解决

出现该问的原因&#xff1a; 因为新版的 webpack-dev-server 出于安全考虑&#xff0c;默认检查 hostname&#xff0c;如果hostname不是配置内的就不能访问。 解决办法&#xff1a;设置跳过host检查 打开你的项目全局搜索 devServer &#xff0c;在 devServer 里面添加 &quo…

react hooks使用_为什么要使用React Hooks?

react hooks使用The first thing you should do whenever youre about to learn something new is ask yourself two questions -每当您要学习新东西时&#xff0c;应该做的第一件事就是问自己两个问题- Why does this thing exist? 为什么这东西存在&#xff1f; What probl…

算法 - 字符串匹配

http://blog.csdn.net/linhuanmars/article/details/20276833 转载于:https://www.cnblogs.com/qlky/p/7817471.html

工作流入门链接

百度百科-工作流 http://baike.baidu.com/link?urlZjElBNByyZz_ItLtd_Uqt3Sadcwv0-4CDO806vKQWJDuUOFybbkzpg8GOB1EU71w8bT4x64RoRXBrFXa7o_dK 企业应用工作流的好处http://jingyan.baidu.com/article/90895e0fe9c56164ec6b0b24.html工作流管理的好处http://blog.sina.com.cn/…

uniapph5配置index.html模板路径不生效解决办法

很简单&#xff0c;关闭应用再重新启动试试&#xff0c;还不行的话&#xff0c;重启IDE

终端软件升级功能开发_5个很棒的终端技巧可帮助您升级为开发人员

终端软件升级功能开发There are plenty of beginner tutorials around that help you learn command line basics, such as cd, ls, pwd and so on...but what about that fancy magic youve seen more experienced developers use?周围有很多初学者教程可以帮助您学习命令行基…

自定义左右侧滑菜单

实现效果&#xff1a; 左右侧滑菜单&#xff0c;侧滑栏占主屏比为60%监听触控&#xff0c;自定义滑动动画&#xff0c;当侧边栏滑动超过50%松开触控将自动滑动到60%&#xff0c;未超过50%松开触控回归侧边栏隐藏为主屏设置蒙版效果&#xff0c;根据侧滑菜单的占屏比设置主屏蒙版…

uniapp设置模板路径页面样式混乱解决办法

乱了就在html里面加上下面这行代码试试 <link rel"stylesheet" href"<% BASE_URL %>static/index.css" /> <meta name"viewport" content"widthdevice-width, initial-scale1.0, user-scalableno, minimum-scale1.0, maxim…

JavaScript获取当前日期,昨天,今天日期以及任意天数间隔日期

<script language"JavaScript" type"text/javascript"> function GetDateStr(AddDayCount) { var dd new Date(); dd.setDate(dd.getDate()AddDayCount);//获取AddDayCount天后的日期 var y dd.getYear(); var m dd.getMonth()1;//获取当前月份…

snapd_snapd使管理Nextcloud变得轻而易举

snapdAs I’ve described in both my Linux in Action book and Linux in Motion course, Nextcloud is a powerful way to build a file sharing and collaboration service using only open source software running on your own secure infrastructure. It’s DropBox, Skyp…

atitit.跨架构 bs cs解决方案. 自定义web服务器的实现方案 java .net jetty  HttpListener...

atitit.跨架构 bs cs解决方案. 自定义web服务器的实现方案 java .net jetty HttpListener 1. 自定义web服务器的实现方案&#xff0c;基于原始socket vs 基于tcpListener vs 基于HttpListener1 2. download1 3. Lib3 4. Code3 5. HttpListener类4 6. Reef5 1. 自定义web服务器…

Python高级函数--map/reduce

名字开头大写 后面小写&#xff1b;练习&#xff1a; 1 def normalize(name): 2 return name[0].upper() name[1:].lower() 3 L1 [adam, LISA, barT] 4 L2 list(map(normalize, L1)) 5 print(L2) reduce求积&#xff1a; 1 from functools import reduce 2 3 def prod(…

样式集(9) - 切换Tab菜单

先上效果图 下面是以vue实现的示例代码&#xff1a; 代码解析&#xff1a; 很简单的代码&#xff0c;直接复制粘贴使用吧~ 别忘记一键三连哦&#xff0c;点赞&#xff0c;收藏&#xff0c;关注&#xff0c;谢谢~ 后续持续更新更多干货哦&#xff01;&#xff01; <temp…

python字典{:4}_Python字典101:详细的视觉介绍

python字典{&#xff1a;>4}欢迎 (Welcome) In this article, you will learn how to work with Python dictionaries, an incredibly helpful built-in data type that you will definitely use in your projects.在本文中&#xff0c;您将学习如何使用Python字典&#xff…