生成类似于MongoDB产生的ObjectId
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的更多相关文章
- MongoDB中_id(ObjectId)生成
MongoDB 中我们经常会接触到一个自动生成的字段:"_id",类型为ObjectId. 之前我们使用MySQL等关系型数据库时,主键都是设置成自增的.但在分布式环境下,这种方法 ...
- ThinkPhp5 mongodb 使用自定义objectID出错解决
在Tp5中使用mongodb 使用自定义ObjectId时报错:Cannot use object of type MongoDB\\BSON\\ObjectID as array 查询源码发现在to ...
- MongoDB学习笔记~ObjectId主键的设计
回到目录 说一些关于ObjectId的事 MongoDB确实是最像关系型数据库的NoSQL,这在它主键设计上可以体现的出来,它并没有采用自动增长主键,因为在分布式服务器之间做数据同步很麻烦,而是采用了 ...
- java 查询 mongodb 中的objectid
网上找了很久查询objectid的方法都是错的,用mongovue能查询出来,但就是用java不知道怎么查询 1.mongovue里的查询方式: {"_id" : ObjectId ...
- 从MongoDB的ObjectId中获取时间信息
MongoDB默认使用_id字段作为主键,类型为ObjectId.ObjectId的生成有一定的规则,详情可以查看这篇文章 - MongoDB深究之ObjectId.如果你在写入数据库的时候忘记写入创 ...
- mongoose手动生成ObjectId
用mongoose驱动保存数据,如果_id没有定义,那么在save的时候,mongoose驱动会自己生成一个_id.那么如果需要手动生成可以用mongoose.Types.ObjectId()方法. ...
- mongoose和mongodb的几篇文章 (ObjectId,ref)
http://mongoosejs.com/docs/populate.html http://stackoverflow.com/questions/6578178/node-js-mongoose ...
- 【翻译】MongoDB指南/引言
[原文地址]https://docs.mongodb.com/manual/ 引言 MongoDB是一种开源文档型数据库,它具有高性能,高可用性,自动扩展性 1.文档数据库 MongoDB用一个文档来 ...
- Python操作MongoDB和Redis
1. python对mongo的常见CURD的操作 1.1 mongo简介 mongodb是一个nosql数据库,无结构化.和去中心化. 那为什么要用mongo来存呢? 1. 首先.数据关系复杂,没有 ...
随机推荐
- hdu 5045 N个人做M道题的正确率
http://acm.hdu.edu.cn/showproblem.php?pid=5045 给出N个人做M道题的正确率,每道题只能由一个人做出,并且当所有人都做出来且仅做出一道题时,做过题的人才可以 ...
- Windows 7下通过Excel2007连接Oracle数据库并对表查询
http://blog.csdn.net/pan_tian/article/details/8133668 1. 环境变量的设置 1.1 ORACLE_HOME环境变量的设置,我这里指向了我的Ora ...
- Win10系统下编译OSG3.4
环境说明 1.Win10专业版.64位: 2.VS2012旗舰版:QT5.2.0: 3.cmake-3.9.0.64位: 资源准备 1.OSG3.4源码包 http://trac.opensceneg ...
- Spring Boot 2 实践记录之 条件装配
实验项目是想要使用多种数据库访问方式,比如 JPA 和 MyBatis. 项目的 Service 层业务逻辑相同,只是具体实现代码不同,自然是一组接口,两组实现类的架构比较合理. 不过这种模式却有一个 ...
- JS代码指导原则
一.什么是平稳退化? 如果含有JS代码的网页在用户浏览器不支持JS(或者禁用JS)时,用户仍然能够顺利浏览(网站功能正常,只是视觉效果可能差一些),那么这个网页就能够平稳退化 网页能够平稳退化是很必要 ...
- ASP.NET Core真实管道详解[1]
ASP.NET Core管道虽然在结构组成上显得非常简单,但是在具体实现上却涉及到太多的对象,所以我们在 <ASP.NET Core管道深度剖析[共4篇]> 中围绕着一个经过极度简化的模拟 ...
- vux组件简单使用请大佬指点
一.打开vux项目 我用的是vsCode工具自己找看个人选择,第一次使用请去找vc方便开发使用的插件 二.项目目录及文件,有遮挡部分自行查看文件 三.根据官方文档实现引入插件 通过vux-loader ...
- wpf简单进度条
UserControl x:Class="WpfApplication1.UserControl2" xmlns="http://schemas.microsoft.co ...
- log4j学习(一)最简单的例子
前言: 之前笔者一直是在System.out中打日志的,由于笔者大部分时候是编写在tomcat容器里运行的一些个小web应用,所以这么做似乎没什么问题:打印出来的日志都可以在tomcat自己的log目 ...
- Android的基础知识
一.adb 的简单命令 1. adb devices : 连接当前手机的设备 2.adb kill-server : 杀死当前的adbmingling 3.adb start-server : ...