mh_goadmin_server/app/admin/models/tools/productCounter.go

35 lines
609 B
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 tools
import (
"sync"
)
type ProductCounter struct {
mu sync.Mutex
counters map[string]int
}
func NewProductCounter() *ProductCounter {
return &ProductCounter{
counters: make(map[string]int),
}
}
func (pc *ProductCounter) GetNextProductNumber(categoryID string) int {
pc.mu.Lock()
defer pc.mu.Unlock()
// 如果之前没有这个分类的计数器初始化为1
if _, ok := pc.counters[categoryID]; !ok {
pc.counters[categoryID] = 1
}
// 生成商品编号
productNumber := pc.counters[categoryID]
// 增加计数器
pc.counters[categoryID]++
return productNumber
}