labix.org/v2/mgo/bson 包虽然是MongoDB的golang实现,其中产生唯一ID的算法是独立的,不依赖MongoDB, 提炼这部分的代码如下:

 

package main

import (
    "crypto/md5"
    "crypto/rand"
    "encoding/binary"
    "encoding/hex"
    "fmt"
    "io"
    "os"
    "sync/atomic"
    "time"
)

// objectIdCounter is atomically incremented when generating a new ObjectId
// using NewObjectId() function. It's used as a counter part of an id.
var objectIdCounter uint32 = 0

// machineId stores machine id generated once and used in subsequent calls
// to NewObjectId function.
var machineId = readMachineId()

// ObjectId is a unique ID identifying a BSON value. It must be exactly 12 bytes
// long. MongoDB objects by default have such a property set in their "_id"
// property.
//
// http://www.mongodb.org/display/DOCS/Object+IDs
type ObjectId string

func main() {
    objID := NewObjectId()
    fmt.Println(objID)
    fmt.Println(objID.Hex())
}

// readMachineId generates machine id and puts it into the machineId global
// variable. If this function fails to get the hostname, it will cause
// a runtime error.
func readMachineId() []byte {
    var sum [3]byte
    id := sum[:]
    hostname, err1 := os.Hostname()
    if err1 != nil {
        _, err2 := io.ReadFull(rand.Reader, id)
        if err2 != nil {
            panic(fmt.Errorf("cannot get hostname: %v; %v", err1, err2))
        }
        return id
    }
    hw := md5.New()
    hw.Write([]byte(hostname))
    copy(id, hw.Sum(nil))
    fmt.Println("readMachineId:" + string(id))
    return id
}

// NewObjectId returns a new unique ObjectId.
// 4byte 时间,
// 3byte 机器ID
// 2byte pid
// 3byte 自增ID
func NewObjectId() ObjectId {
    var b [12]byte
    // Timestamp, 4 bytes, big endian
    binary.BigEndian.PutUint32(b[:], uint32(time.Now().Unix()))
    // Machine, first 3 bytes of md5(hostname)
    b[4] = machineId[0]
    b[5] = machineId[1]
    b[6] = machineId[2]
    // Pid, 2 bytes, specs don't specify endianness, but we use big endian.
    pid := os.Getpid()
    b[7] = byte(pid >> 8)
    b[8] = byte(pid)
    // Increment, 3 bytes, big endian
    i := atomic.AddUint32(&objectIdCounter, 1)
    b[9] = byte(i >> 16)
    b[10] = byte(i >> 8)
    b[11] = byte(i)
    return ObjectId(b[:])
}

// Hex returns a hex representation of the ObjectId.
// 返回16进制对应的字符串
func (id ObjectId) Hex() string {
    return hex.EncodeToString([]byte(id))
}

执行结果截图:

参考资料:

mgo说明文档
http://godoc.org/labix.org/v2/mgo/bson

Golang binary包——byte数组如何转int?
http://blog.cyeam.com/hash/2014/07/29/go_bytearraytoint/

golang产生guid的更多相关文章

  1. GOLANG 加密,解密,GUID 小方法

    golang的 MD5加密.BASE64解密  guid 的代码: /** * 用于加密,解密,(包含MD5加密和base64加密/解密)以及GUID的生成 * 时间: * zhifieya */ p ...

  2. Dapr Pub/Sub 集成 RabbitMQ 、Golang、Java、DotNet Core

    前置条件: <Dapr运用> <Dapr 运用之 Java gRPC 调用篇> <Dapr 运用之集成 Asp.Net Core Grpc 调用篇> 搭建 Rabb ...

  3. golang xml解析

    第二章里还提到了xml的解析部分.之前有想整理下encoding包下常用的几个文件格式的处理.这次刚好整理下xml的部分.先上例子 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 ...

  4. golang语法笔记

    开始微服务,那就先温习下golang语法吧; golang变量类型 1. 整形 Go %b    表示为二进制 %c    该值对应的unicode码值 %d    表示为十进制 %o    表示为八 ...

  5. Golang中如何正确的使用sarama包操作Kafka?

    Golang中如何正确的使用sarama包操作Kafka? 一.背景 在一些业务系统中,模块之间通过引入Kafka解藕,拿IM举例(图来源): 用户A给B发送消息,msg_gateway收到消息后,投 ...

  6. Golang, 以17个简短代码片段,切底弄懂 channel 基础

    (原创出处为本博客:http://www.cnblogs.com/linguanh/) 前序: 因为打算自己搞个基于Golang的IM服务器,所以复习了下之前一直没怎么使用的协程.管道等高并发编程知识 ...

  7. 说说Golang的使用心得

    13年上半年接触了Golang,对Golang十分喜爱.现在是2015年,离春节还有几天,从开始学习到现在的一年半时间里,前前后后也用Golang写了些代码,其中包括业余时间的,也有产品项目中的.一直 ...

  8. TODO:Golang指针使用注意事项

    TODO:Golang指针使用注意事项 先来看简单的例子1: 输出: 1 1 例子2: 输出: 1 3 例子1是使用值传递,Add方法不会做任何改变:例子2是使用指针传递,会改变地址,从而改变地址. ...

  9. UniqueIdentifier 数据类型 和 GUID 生成函数

    UniqueIdentifier 数据类型用于存储GUID的值,占用16Byte. SQL Server将UniqueIdentifier存储为16字节的二进制数值,Binary(16),按照特定的格 ...

随机推荐

  1. 如何到python模块路径linux

    执行命令whereis python即可显示出python相关的所有的路径,包括可执行文件路径,安装路径等,该方法适用于大部分类似的场景抄自百度知道

  2. Groovy学习记录-------Groovy安装/配置

    1.Groovy SDK下载 Groovy SDK官网下载地址: http://www.groovy-lang.org/download.html  每个版本有五个选项可供下载,依次为: binary ...

  3. mxonline实战15,用户中心:我的课程, 我的收藏,我的消息,登出和点击数以及收藏数

     对应github地址:第15天     一.  我的课程   1. 继承usercenter-base页面 2. 编写url, view

  4. Class文件分析

    java源码和class文件 源码: package classloader; public class TestCase { private int value; public int test() ...

  5. Hadoop完全分布式搭建

    ---记于2015年11月6日星期五 准备工作 软硬件环境 主机操作系统:处理器:i5,主频:3.2G,内存:8G,Windows64 虚拟机软件:VMware Workstation 10 虚拟操作 ...

  6. canvas+js+面向对象的圆形封装

    效果: Circle.js /* 1. 封装属性: x, y r, fillStyle strokeStyle opacity 2.render */ function Circle(option) ...

  7. python bytes和str之间的转换

    1 # bytes object 2 b = b"example" 3 4 # str object 5 s = "example" 6 7 # str to ...

  8. Vue.js 动态挂载子组件

    直接来实例 父组件 <template> <div> <div :is="sub.content" :ref="sub.name" ...

  9. SQL高效分页(百万条数据)

    第一种方法:效率最高 SELECT TOP 页大小 * FROM ( SELECT ROW_NUMBER() OVER (ORDER BY id) AS RowNumber,* FROM table1 ...

  10. 【JSP】jsp报错:Syntax error, insert "}" to complete MethodBody

    使用MyEclipse编写JSP的时候有时会报错误如下 Syntax error, insert "}" to complete MethodBody 大体意思就是说方法体缺少缺少 ...