package com.jt.boot.utils;

 import com.google.common.base.Objects;

 import java.net.NetworkInterface;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.Enumeration;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger; /**
* <p>A globally unique identifier for objects.</p>
* <p/>
* <p>Consists of 12 bytes, divided as follows:</p>
* <table border="1">
* <caption>ObjectID layout</caption>
* <tr>
* <td>0</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td><td>11</td>
* </tr>
* <tr>
* <td colspan="4">time</td><td colspan="3">machine</td> <td colspan="2">pid</td><td colspan="3">inc</td>
* </tr>
* </table>
* <p/>
* <p>Instances of this class are immutable.</p>
*/
public class ObjectId implements Comparable<ObjectId>, java.io.Serializable { private final int _time;
private final int _machine;
private final int _inc;
private boolean _new;
private static final int _genmachine; private static AtomicInteger _nextInc = new AtomicInteger((new Random()).nextInt()); private static final long serialVersionUID = -4415279469780082174L; private static final Logger LOGGER = Logger.getLogger("org.bson.ObjectId"); /**
* Create a new object id.
*/
public ObjectId() {
_time = (int) (System.currentTimeMillis() / 1000);
_machine = _genmachine;
_inc = _nextInc.getAndIncrement();
_new = true;
} public static String id() {
return get().toHexString();
} /**
* Gets a new object id.
*
* @return the new id
*/
public static ObjectId get() {
return new ObjectId();
} /**
* Checks if a string could be an {@code ObjectId}.
*
* @param s a potential ObjectId as a String.
* @return whether the string could be an object id
* @throws IllegalArgumentException if hexString is null
*/
public static boolean isValid(String s) {
if (s == null)
return false; final int len = s.length();
if (len != 24)
return false; for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9')
continue;
if (c >= 'a' && c <= 'f')
continue;
if (c >= 'A' && c <= 'F')
continue; return false;
} return true;
} /**
* Converts this instance into a 24-byte hexadecimal string representation.
*
* @return a string representation of the ObjectId in hexadecimal format
*/
public String toHexString() {
final StringBuilder buf = new StringBuilder(24);
for (final byte b : toByteArray()) {
buf.append(String.format("%02x", b & 0xff));
}
return buf.toString();
} /**
* Convert to a byte array. Note that the numbers are stored in big-endian order.
*
* @return the byte array
*/
public byte[] toByteArray() {
byte b[] = new byte[12];
ByteBuffer bb = ByteBuffer.wrap(b);
// by default BB is big endian like we need
bb.putInt(_time);
bb.putInt(_machine);
bb.putInt(_inc);
return b;
} private int _compareUnsigned(int i, int j) {
long li = 0xFFFFFFFFL;
li = i & li;
long lj = 0xFFFFFFFFL;
lj = j & lj;
long diff = li - lj;
if (diff < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
if (diff > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
return (int) diff;
} public int compareTo(ObjectId id) {
if (id == null)
return -1; int x = _compareUnsigned(_time, id._time);
if (x != 0)
return x; x = _compareUnsigned(_machine, id._machine);
if (x != 0)
return x; return _compareUnsigned(_inc, id._inc);
} /**
* Gets the timestamp (number of seconds since the Unix epoch).
*
* @return the timestamp
*/
public int getTimestamp() {
return _time;
} /**
* Gets the timestamp as a {@code Date} instance.
*
* @return the Date
*/
public Date getDate() {
return new Date(_time * 1000L);
} /**
* Gets the current value of the auto-incrementing counter.
*
* @return the current counter value.
*/
public static int getCurrentCounter() {
return _nextInc.get();
} static { try {
// build a 2-byte machine piece based on NICs info
int machinePiece;
{
try {
StringBuilder sb = new StringBuilder();
Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
while (e.hasMoreElements()) {
NetworkInterface ni = e.nextElement();
sb.append(ni.toString());
}
machinePiece = sb.toString().hashCode() << 16;
} catch (Throwable e) {
// exception sometimes happens with IBM JVM, use random
LOGGER.log(Level.WARNING, e.getMessage(), e);
machinePiece = (new Random().nextInt()) << 16;
}
LOGGER.fine("machine piece post: " + Integer.toHexString(machinePiece));
} // add a 2 byte process piece. It must represent not only the JVM but the class loader.
// Since static var belong to class loader there could be collisions otherwise
final int processPiece;
{
int processId = new Random().nextInt();
try {
processId = java.lang.management.ManagementFactory.getRuntimeMXBean().getName().hashCode();
} catch (Throwable t) {
} ClassLoader loader = ObjectId.class.getClassLoader();
int loaderId = loader != null ? System.identityHashCode(loader) : 0; StringBuilder sb = new StringBuilder();
sb.append(Integer.toHexString(processId));
sb.append(Integer.toHexString(loaderId));
processPiece = sb.toString().hashCode() & 0xFFFF;
LOGGER.fine("process piece: " + Integer.toHexString(processPiece));
} _genmachine = machinePiece | processPiece;
LOGGER.fine("machine : " + Integer.toHexString(_genmachine));
} catch (Exception e) {
throw new RuntimeException(e);
} } @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; ObjectId that = (ObjectId) o; return Objects.equal(this.serialVersionUID, that.serialVersionUID) &&
Objects.equal(this.LOGGER, that.LOGGER) &&
Objects.equal(this._time, that._time) &&
Objects.equal(this._machine, that._machine) &&
Objects.equal(this._inc, that._inc) &&
Objects.equal(this._new, that._new) &&
Objects.equal(this._nextInc, that._nextInc) &&
Objects.equal(this._genmachine, that._genmachine);
} @Override
public int hashCode() {
return Objects.hashCode(serialVersionUID, LOGGER, _time, _machine, _inc, _new,
_nextInc, _genmachine);
} public static void main(String[] args) {
System.out.println(new ObjectId().toHexString());
System.out.println(new ObjectId().toHexString());
System.out.println(new ObjectId().toHexString());
}
}

生成类似于MongoDB产生的ObjectId的更多相关文章

  1. MongoDB中_id(ObjectId)生成

    MongoDB 中我们经常会接触到一个自动生成的字段:"_id",类型为ObjectId. 之前我们使用MySQL等关系型数据库时,主键都是设置成自增的.但在分布式环境下,这种方法 ...

  2. ThinkPhp5 mongodb 使用自定义objectID出错解决

    在Tp5中使用mongodb 使用自定义ObjectId时报错:Cannot use object of type MongoDB\\BSON\\ObjectID as array 查询源码发现在to ...

  3. MongoDB学习笔记~ObjectId主键的设计

    回到目录 说一些关于ObjectId的事 MongoDB确实是最像关系型数据库的NoSQL,这在它主键设计上可以体现的出来,它并没有采用自动增长主键,因为在分布式服务器之间做数据同步很麻烦,而是采用了 ...

  4. java 查询 mongodb 中的objectid

    网上找了很久查询objectid的方法都是错的,用mongovue能查询出来,但就是用java不知道怎么查询 1.mongovue里的查询方式: {"_id" : ObjectId ...

  5. 从MongoDB的ObjectId中获取时间信息

    MongoDB默认使用_id字段作为主键,类型为ObjectId.ObjectId的生成有一定的规则,详情可以查看这篇文章 - MongoDB深究之ObjectId.如果你在写入数据库的时候忘记写入创 ...

  6. mongoose手动生成ObjectId

    用mongoose驱动保存数据,如果_id没有定义,那么在save的时候,mongoose驱动会自己生成一个_id.那么如果需要手动生成可以用mongoose.Types.ObjectId()方法. ...

  7. mongoose和mongodb的几篇文章 (ObjectId,ref)

    http://mongoosejs.com/docs/populate.html http://stackoverflow.com/questions/6578178/node-js-mongoose ...

  8. 【翻译】MongoDB指南/引言

    [原文地址]https://docs.mongodb.com/manual/ 引言 MongoDB是一种开源文档型数据库,它具有高性能,高可用性,自动扩展性 1.文档数据库 MongoDB用一个文档来 ...

  9. Python操作MongoDB和Redis

    1. python对mongo的常见CURD的操作 1.1 mongo简介 mongodb是一个nosql数据库,无结构化.和去中心化. 那为什么要用mongo来存呢? 1. 首先.数据关系复杂,没有 ...

随机推荐

  1. Android-Xml,PullParser,解析

    在上一篇博客,Android-XML格式描述,介绍来XML在Android中的格式: 解析persons.xml文件内容: <?xml version="1.0" encod ...

  2. flume 整合kafka

    背景:系统的数据量越来越大,日志不能再简单的文件的保存,如此日志将会越来越大,也不方便查找与分析,综合考虑下使用了flume来收集日志,收集日志后向kafka传递消息,下面给出具体的配置 # The ...

  3. .NET Core 类库中读取appsettings.json

    { "Logging": { "IncludeScopes": false, "LogLevel": { "Default&quo ...

  4. Angular6 学习笔记——内容投影, ViewChild和ContentChild

    angular6.x系列的学习笔记记录,仍在不断完善中,学习地址: https://www.angular.cn/guide/template-syntax http://www.ngfans.net ...

  5. PowerDesigner 生成C#实体模版代码

    操作步骤见:  https://blog.csdn.net/da454122373/article/details/54346217 最后的template 模版代码如下: .if (%isValid ...

  6. 世界各国货币,C#数字货币计算

    货币 CCY(Currency)本质上是一种所有者与市场关于交换权的契约,根本上是所有者相互之间的约定.吾以吾之所有予市场,换吾之所需,货币就是这一过程的约定,它反映的是个体与社会的经济协作关系.货币 ...

  7. ASP.NET webform多次提交表单问题

    最近几天遇到一个头疼的问题,项目采用的是webform开发,每个界面都有个提交按钮,点击多次提交按钮导致提交按钮的OnClick事件执行了多次, 每次OnClick里面都有一些逻辑处理,执行了多次导致 ...

  8. 程序媛计划——python初级课时1~2

    在命令行中运行py文件:python 文件路径/文件名 python变量必须赋值后才能使用,因为py变量只有赋值后才会被创建. py可以同时给多个变量赋值:a,b,c = 10,20,'dfjkdj' ...

  9. C++单继承的构造函数和析构函数调用的顺序

    1.继承构造函数调用顺序以及销毁的过程 先调用父类的构造函数,在调用子类的构造函数,析构函数调用相反.

  10. TCP BBR - 一键安装最新内核并开启 TCP BBR

    原文地址: https://teddysun.com/489.html 最近,Google 开源了其 TCP BBR 拥塞控制算法,并提交到了 Linux 内核,从 4.9 开始,Linux 内核已经 ...