golang 生成定單號(hào)的操作
年(2位)+一年中的第幾天(3位)+指定位數(shù)隨機(jī)數(shù)
//生成單號(hào) //06123xxxxx //sum 最少10位,sum 表示全部單號(hào)位數(shù) func MakeYearDaysRand(sum int) string { //年 strs := time.Now().Format("06") //一年中的第幾天 days := strconv.Itoa(GetDaysInYearByThisYear()) count := len(days) if count < 3 { //重復(fù)字符0 days = strings.Repeat("0", 3-count) + days } //組合 strs += days //剩余隨機(jī)數(shù) sum = sum - 5 if sum < 1 { sum = 5 } //0~9999999的隨機(jī)數(shù) 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 { //重復(fù)字符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, 30, 31, 31, 30, 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; }
補(bǔ)充:基于GO語言實(shí)現(xiàn)的支持高并發(fā)訂單號(hào)生成函數(shù)
1.固定24位長(zhǎng)度訂單號(hào),毫秒+進(jìn)程id+序號(hào)。
2.同一毫秒內(nèi)只要不超過一萬次并發(fā),則訂單號(hào)不會(huì)重復(fù)。
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位訂單號(hào) //前面17位代表時(shí)間精確到毫秒,中間3位代表進(jìn)程id,最后4位代表序號(hào) 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 } //對(duì)長(zhǎng)度不足n的數(shù)字前面補(bǔ)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 }
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
Go?基本數(shù)據(jù)類型與字符串相互轉(zhuǎn)換方法小結(jié)
這篇文章主要介紹了Go基本數(shù)據(jù)類型與字符串相互轉(zhuǎn)換,將string類型轉(zhuǎn)換成基本類型時(shí),必須確保string類型是有效的,文中補(bǔ)充介紹了Go基本數(shù)據(jù)類型和其字符串表示之間轉(zhuǎn)換,結(jié)合實(shí)例代碼給大家講解的非常詳細(xì),需要的朋友可以參考下2024-01-01golang使用aes庫實(shí)現(xiàn)加解密操作
這篇文章主要介紹了golang使用aes庫實(shí)現(xiàn)加解密操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-12-12Golang連接并操作PostgreSQL數(shù)據(jù)庫基本操作
PostgreSQL是常見的免費(fèi)的大型關(guān)系型數(shù)據(jù)庫,具有豐富的數(shù)據(jù)類型,也是軟件項(xiàng)目常用的數(shù)據(jù)庫之一,下面這篇文章主要給大家介紹了關(guān)于Golang連接并操作PostgreSQL數(shù)據(jù)庫基本操作的相關(guān)資料,需要的朋友可以參考下2022-09-09Go基礎(chǔ)教程系列之WaitGroup用法實(shí)例詳解
這篇文章主要介紹了Go基礎(chǔ)教程系列之WaitGroup用法實(shí)例詳解,需要的朋友可以參考下2022-04-04golang實(shí)現(xiàn)一個(gè)簡(jiǎn)單的websocket聊天室功能
這篇文章主要介紹了golang實(shí)現(xiàn)一個(gè)簡(jiǎn)單的websocket聊天室功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-10-10