| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130 |
- /**
- * @Author: zou.yingbin
- * @Create : 2021/1/13 9:15
- * @Modify : 2021/1/13 9:15
- */
- package mtpcache
- import (
- "mtp2_if/db"
- "mtp2_if/logger"
- "mtp2_if/utils"
- "sync"
- "time"
- )
- var (
- vDicCurrency = enumdicitem{data: map[int32]string{}, nType: 2}
- vDic = enumdicitem{data: map[int32]string{}, nType: 1}
- vDicCardName = enumdicitem{data: map[int32]string{}, nType: 3}
- )
- // IGetEnumdicName 获取字典名称接口
- type IGetEnumdicName interface {
- get(int32) string
- load()
- }
- // 商品单位名称缓存
- type enumdicitem struct {
- mtx sync.RWMutex //锁
- data map[int32]string //数据[enumitemname]enumdicname
- last time.Time
- nType int32 // 1-单位名称 2-币种名称
- }
- type enumData struct {
- ENUMITEMNAME int32 `json:"enumitemname" xorm:"'enumitemname'"` //ID
- ENUMDICNAME string `json:"enumdicname" xorm:"'enumdicname'"` //名称
- }
- func (r *enumdicitem) buildSql() string {
- var sqlId utils.SQLVal = "select t.enumitemname, t.enumdicname" +
- " from enumdicitem t" +
- " where t.enumitemstatus = 1"
- sqlId.AndEx("t.enumdiccode", "goodsunit", r.nType == 1)
- sqlId.AndEx("t.enumdiccode", "currency", r.nType == 2)
- sqlId.AndEx("t.enumdiccode", "certificatetype", r.nType == 3)
- return sqlId.String()
- }
- func init() {
- go func() {
- time.Sleep(time.Second * 6)
- vDicCurrency.load()
- vDic.load()
- vDicCardName.load()
- }()
- }
- // 加载数据
- func (r *enumdicitem) load() {
- now := time.Now()
- // 间隔3秒以上才重新加载
- if d := now.Sub(r.last); d.Seconds() < 3 {
- return
- }
- r.mtx.Lock()
- defer r.mtx.Unlock()
- e := db.GetEngine()
- if e == nil {
- return
- }
- sData := make([]enumData, 0)
- s := e.SQL(r.buildSql())
- if err := s.Find(&sData); err != nil {
- logger.GetLogger().Errorf("cache load enumdicitem, %v", err)
- } else {
- r.data = make(map[int32]string)
- for i := range sData {
- r.data[sData[i].ENUMITEMNAME] = sData[i].ENUMDICNAME
- }
- r.last = time.Now()
- }
- }
- func (r *enumdicitem) get(id int32) string {
- r.mtx.RLock()
- defer r.mtx.RUnlock()
- if r.data == nil {
- return ""
- }
- if v, ok := r.data[id]; ok {
- return v
- }
- return ""
- }
- // getDicEnumName 获取字典名称
- func getDicEnumName(obj IGetEnumdicName, id int32) string {
- if id <= 0 {
- return ""
- }
- if v := obj.get(id); v != "" {
- return v
- } else {
- obj.load()
- }
- return obj.get(id)
- }
- // GetEnumDicitemName 获取商品单位枚举名称
- func GetEnumDicitemName(id int32) string {
- return getDicEnumName(&vDic, id)
- }
- // GetCurrencyName 获取币种名称
- func GetCurrencyName(id int32) string {
- return getDicEnumName(&vDicCurrency, id)
- }
- // GetCardName 获取卡类型名称
- func GetCardName(cardId int32) string {
- return getDicEnumName(&vDicCardName, cardId)
- }
|