Golang杂谈-gorm集成雪花id

go get github.com/bwmarrin/snowflake
package main

import (
	"fmt"

	"github.com/bwmarrin/snowflake"
)

func main() {

	// Create a new Node with a Node number of 1
	node, err := snowflake.NewNode(1)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Generate a snowflake ID.
	id := node.Generate()

	// Print out the ID in a few different ways.
	fmt.Printf("Int64  ID: %d\n", id)
	fmt.Printf("String ID: %s\n", id)
	fmt.Printf("Base2  ID: %s\n", id.Base2())
	fmt.Printf("Base64 ID: %s\n", id.Base64())

	// Print out the ID's timestamp
	fmt.Printf("ID Time  : %d\n", id.Time())

	// Print out the ID's node number
	fmt.Printf("ID Node  : %d\n", id.Node())

	// Print out the ID's sequence number
	fmt.Printf("ID Step  : %d\n", id.Step())

  // Generate and print, all in one.
  fmt.Printf("ID       : %d\n", node.Generate().Int64())
}

 

雪花id工具方法

package snowflakeutil

import (
    "coolnews.com/coolnews-service/global"
    "github.com/bwmarrin/snowflake"
)

func GenSnowflakeId() int64 {
    node, err := snowflake.NewNode(1)
    if err != nil {
        global.Logger.Error("生成雪花id失败")
        return 0
    }
    // Generate a snowflake ID.
    id := node.Generate()
    return id.Int64()
}

 

 

 模型中使用 

type CnsAppUser struct {
    models.BaseModel
    Username string `json:"username" gorm:"size:20;unique;not null;comment:用户名"`
    Password string `json:"-" gorm:"size:100;not null;comment:密码"`
    Phone    string `json:"phone" gorm:"size:11;unique;not null;comment:手机号"`
    Avatar   string `json:"avatar" gorm:"size:255;comment:头像" json:"avatar"`
    Desc     string `json:"desc" gorm:"size:50;comment:用户简介"`
}

func (c *CnsAppUser) BeforeCreate(scope *gorm.DB) error {
    c.Id = snowflakeutil.GenSnowflakeId()
    return nil
}

 会遇到一个int64的字符串问题

 

json后加,string即可

posted @ 2024-08-19 11:03  Lastly  阅读(669)  评论(0)    收藏  举报