作者 tangxvhui

bug 修复

@@ -9,6 +9,7 @@ import ( @@ -9,6 +9,7 @@ import (
9 "oppmg/protocol" 9 "oppmg/protocol"
10 "oppmg/services/ucenter" 10 "oppmg/services/ucenter"
11 "oppmg/utils" 11 "oppmg/utils"
  12 + "oppmg/utils/idworker"
12 "time" 13 "time"
13 14
14 "github.com/astaxie/beego/orm" 15 "github.com/astaxie/beego/orm"
@@ -392,7 +393,7 @@ func AddFirstDepartment(newCompany *models.Company, newusercompany *models.UserC @@ -392,7 +393,7 @@ func AddFirstDepartment(newCompany *models.Company, newusercompany *models.UserC
392 IsTop: 1, 393 IsTop: 1,
393 ParentId: 0, 394 ParentId: 0,
394 Relation: fmt.Sprint(utils.GenerateIDBySonyflake()), 395 Relation: fmt.Sprint(utils.GenerateIDBySonyflake()),
395 - Id: utils.GenerateID14(), 396 + Id: idworker.NextId(),
396 } 397 }
397 _, err = models.AddDepartment(newDepartment, o) 398 _, err = models.AddDepartment(newDepartment, o)
398 if err != nil { 399 if err != nil {
  1 +package idworker
  2 +
  3 +import (
  4 + "sync"
  5 + "time"
  6 +)
  7 +
  8 +const (
  9 + twepoch int64 = 1483200000000 // 默认起始的毫秒时间戳 1483200000000 。计算时,减去这个值
  10 + sequenceBits uint = 12 //自增ID 所占用位置
  11 + sequenceMax int64 = -1 ^ (-1 << sequenceBits)
  12 + timeShift uint = sequenceBits
  13 +)
  14 +
  15 +/*
  16 +* 1 符号位 | 39 时间戳 | 12 (毫秒内)自增ID
  17 +* 0 | 0000000 00000000 00000000 00000000 00000000 | 000000 000000
  18 +*
  19 + */
  20 +
  21 +type IdWorker struct {
  22 + sequence int64 //序号
  23 + lastTimestamp int64 //最后的时间戳
  24 + mutex sync.Mutex
  25 + twepoch int64 //默认起始的毫秒时间戳
  26 +}
  27 +
  28 +func NewIdWorker() *IdWorker {
  29 + idworker := &IdWorker{
  30 + lastTimestamp: -1,
  31 + sequence: 0,
  32 + twepoch: twepoch,
  33 + mutex: sync.Mutex{},
  34 + }
  35 + return idworker
  36 +}
  37 +
  38 +func (n *IdWorker) Generate() int64 {
  39 + n.mutex.Lock()
  40 + defer n.mutex.Unlock()
  41 + now := time.Now().UnixNano() / 1e6
  42 + if n.lastTimestamp == now {
  43 + n.sequence++
  44 + if n.sequence > sequenceMax {
  45 + for now <= n.lastTimestamp {
  46 + now = time.Now().UnixNano() / 1e6
  47 + }
  48 + }
  49 + } else {
  50 + n.sequence = 0
  51 + }
  52 + n.lastTimestamp = now
  53 + result := (now-twepoch)<<timeShift | n.sequence
  54 + return result
  55 +}
  56 +
  57 +var newIdworker = NewIdWorker()
  58 +
  59 +//NextId 新的id, 15 个数字的 id
  60 +func NextId() int64 {
  61 + return newIdworker.Generate()
  62 +}