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. 论文笔记(4)-Deep Boltzmann Machines

    Deep Boltzmann Machines是hinton的学生写的,是在RBM基础上新提出的模型,首先看一下RBM与BM的区别 很明显可以看出BM是在隐含层各个节点以及输入层各个节点都是相互关联的 ...

  2. 如何获得 Microsoft Push Notification Service(MPNS)的最佳体验

    有很多同学抱怨MPNS的各种问题,其中包括服务超时.返回各种错误代码不知如何处理等等..今天我用一点时间来为大家介绍下如何处理和操作咱们的MPNS. 首先为大家明确一个问题,Microsoft Pus ...

  3. BCP 基本语法

    copy from:http://msdn.microsoft.com/zh-cn/library/ms162802.aspx bcp [database_name.] schema.{table_n ...

  4. C# 图片反色处理 图片夜间模式

    项目属性-->生成-->允许不安全代码勾上. 代码: /// <summary> /// 反色处理 /// </summary> private Bitmap In ...

  5. docker rpm 下载地址

    http://yum.dockerproject.org/repo/main/centos/7/Packages/

  6. django orm 以列表作为筛选条件进行查询

    在Django的orm中进行查询操作时,可以通过传入列表,列表内的元素为索引值,作为一个筛选条件来进行行查询 from .models import UserInfo user_obj = UserI ...

  7. 使用PhpSpreadsheet将Excel导入到MySQL数据库

    本文以导入学生成绩表为例,给大家讲解使用PhpSpreadsheet将Excel导入的MySQL数据库. 准备 首先我们需要准备一张MySQL表,表名t_student,表结构如下: CREATE T ...

  8. What are rules about using an underscore in a c identifier

    http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identi ...

  9. HTML 5 使用 FileReader、FormData实现文件上传

    一.FileReader FileReader 对象允许Web应用程序异步读取存储在用户计算机中的文件(或缓冲区的原始数据),使用File或Blob对象指定要读取的文件或数据. 1.1 实例化 var ...

  10. [转][SQL]如何实现存储过程中动态加入条件---没想到语句可以这么巧妙

    在存储过程过程中,如果要实现Select查询的where子句动态查询,可以用exec ( "select .... where" +@whereStr)这样的方式.但这样的话,感觉 ...