go 生成雪花id

package lib

import (
    "sync"
    "time"
)

type AlgorithmSnowFlake struct {
    sync.Mutex
    machineId     int64
    dataCenterId  int64
    lastTimeStamp int64
    sn            int64
}

var algorithmSnowFlake *AlgorithmSnowFlake = nil

func GetAlgorithmSnowFlake() *AlgorithmSnowFlake {
    return algorithmSnowFlake
}

func (sf *AlgorithmSnowFlake) GetID() uint64 {
    sf.Lock()
    defer sf.Unlock()
    
    curTimeStamp := time.Now().UnixNano() / 1000000   // 13位

    if curTimeStamp == sf.lastTimeStamp {
        if sf.sn > 4095 {
            time.Sleep(time.Millisecond)
            curTimeStamp = time.Now().UnixNano() / 1000000
            sf.sn = 0
        }
    } else {
        sf.sn = 0
    }
    sf.sn++
    sf.lastTimeStamp = curTimeStamp

    // 时间戳向左移动22位
    curTimeStamp = curTimeStamp << 22   // 35

    // 合并机器id
    machineId := sf.machineId << 17     // 18

    // 合并数据中心id
    dataCenterId := sf.dataCenterId << 12   // 13

    // 通过与运算把各个部位连接在一起
    id := curTimeStamp | machineId | dataCenterId | sf.sn
    //return id
    return uint64(id)
}

func NewAlgorithmSnowFlake(machineId int64, dataCenterId int64) {
    algorithmSnowFlake = &AlgorithmSnowFlake{
        machineId:    machineId,
        dataCenterId: dataCenterId,
    }
}

生成10个雪花id

package main

import (
    "test/lib"
    "fmt"
)

func main() {
    lib.NewAlgorithmSnowFlake(1, 1)
    m := map[uint64]int{}
    l := []uint64{}
    for i:=0;i<10;i++{
        newID := lib.GetAlgorithmSnowFlake().GetID()
        m[newID] = i
        l = append(l, newID)
    }

    for k, v := range m{
        fmt.Println(k,v)
    }
}

 

posted @ 2020-03-24 15:27  眼镜儿  阅读(528)  评论(0编辑  收藏  举报