golang 生成定單號的操作
阿新 • • 發佈:2020-12-19
年(2位)+一年中的第幾天(3位)+指定位數隨機數
//生成單號 //06123xxxxx //sum 最少10位,sum 表示全部單號位數 func MakeYearDaysRand(sum int) string { //年 strs := time.Now().Format("06") //一年中的第幾天 days := strconv.Itoa(GetDaysInYearByThisYear()) count := len(days) if count < 3 { //重複字元0 days = strings.Repeat("0",3-count) + days } //組合 strs += days //剩餘隨機數 sum = sum - 5 if sum < 1 { sum = 5 } //0~9999999的隨機數 ran := GetRand() pow := math.Pow(10,float64(sum)) - 1 //fmt.Println("sum=>",sum) //fmt.Println("pow=>",pow) result := strconv.Itoa(ran.Intn(int(pow))) count = len(result) //fmt.Println("result=>",result) if count < sum { //重複字元0 result = strings.Repeat("0",sum-count) + result } //組合 strs += result return strs } //年中的第幾天 func GetDaysInYearByThisYear() int { now := time.Now() total := 0 arr := []int{31,28,31,30,31} y,month,d := now.Date() m := int(month) for i := 0; i < m-1; i++ { total = total + arr[i] } if (y%400 == 0 || (y%4 == 0 && y%100 != 0)) && m > 2 { total = total + d + 1 } else { total = total + d } return total; }
補充:基於GO語言實現的支援高併發訂單號生成函式
1.固定24位長度訂單號,毫秒+程序id+序號。
2.同一毫秒內只要不超過一萬次併發,則訂單號不會重複。
github地址:https://github.com/w3liu/go-common/blob/master/number/ordernum/ordernum.go
package ordernum import ( "fmt" "github.com/w3liu/go-common/constant/timeformat" "os" "sync/atomic" "time" ) var num int64 //生成24位訂單號 //前面17位代表時間精確到毫秒,中間3位代表程序id,最後4位代表序號 func Generate(t time.Time) string { s := t.Format(timeformat.Continuity) m := t.UnixNano()/1e6 - t.UnixNano()/1e9*1e3 ms := sup(m,3) p := os.Getpid() % 1000 ps := sup(int64(p),3) i := atomic.AddInt64(&num,1) r := i % 10000 rs := sup(r,4) n := fmt.Sprintf("%s%s%s%s",s,ms,ps,rs) return n } //對長度不足n的數字前面補0 func sup(i int64,n int) string { m := fmt.Sprintf("%d",i) for len(m) < n { m = fmt.Sprintf("0%s",m) } return m }
以上為個人經驗,希望能給大家一個參考,也希望大家多多支援我們。如有錯誤或未考慮完全的地方,望不吝賜教。