Files
go-utils/order_id/id.go
2023-10-26 19:51:23 +08:00

48 lines
1.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package order_id
import (
"fmt"
"math/rand"
"sync/atomic"
"time"
"github.com/tx7do/go-utils/trans"
)
type idCounter uint32
func (c *idCounter) Increase() uint32 {
cur := *c
atomic.AddUint32((*uint32)(c), 1)
atomic.CompareAndSwapUint32((*uint32)(c), 1000, 0)
return uint32(cur)
}
var orderIdIndex idCounter
// GenerateOrderIdWithRandom 生成20位订单号前缀+时间+随机数
func GenerateOrderIdWithRandom(prefix string, split string, tm *time.Time) string {
if tm == nil {
tm = trans.Time(time.Now())
}
index := rand.Intn(1000)
return fmt.Sprintf("%s%s%.4d%s%.2d%s%.2d%s%.2d%s%.2d%s%.2d%s%.4d", prefix, split,
tm.Year(), split, tm.Month(), split, tm.Day(), split,
tm.Hour(), split, tm.Minute(), split, tm.Second(), split, index)
}
// GenerateOrderIdWithIncreaseIndex 生成20位订单号前缀+时间+自增长索引
func GenerateOrderIdWithIncreaseIndex(prefix string, split string, tm *time.Time) string {
if tm == nil {
tm = trans.Time(time.Now())
}
index := orderIdIndex.Increase()
return fmt.Sprintf("%s%s%.4d%s%.2d%s%.2d%s%.2d%s%.2d%s%.2d%s%.4d", prefix, split,
tm.Year(), split, tm.Month(), split, tm.Day(), split,
tm.Hour(), split, tm.Minute(), split, tm.Second(), split, index)
}