package service import ( "apsClient/constvar" "apsClient/model" "apsClient/model/response" "fmt" "github.com/spf13/cast" "sync" "time" ) type CacheStore struct { cache map[string]interface{} mu sync.Mutex } var defaultCacheStore *CacheStore func init() { defaultCacheStore = newCacheManager() } func newCacheManager() *CacheStore { return &CacheStore{ cache: make(map[string]interface{}), } } func (cm *CacheStore) Get(key string) (interface{}, bool) { cm.mu.Lock() defer cm.mu.Unlock() conn, ok := cm.cache[key] return conn, ok } func (cm *CacheStore) Add(key string, value interface{}) { cm.mu.Lock() defer cm.mu.Unlock() cm.cache[key] = value } func (cm *CacheStore) Remove(key string) { cm.mu.Lock() defer cm.mu.Unlock() delete(cm.cache, key) } const ( PlcCacheKey = "plc:%v:%v" //plc:position:key CurrentTaskCacheKey = "current_task" CurrentProgressCacheKey = "current_progress:%v" //current_progress:position PlcCacheKeyUpdateTime = "finish_number_update_time:%v" //finish_number_update_time:position ) func PlcCacheGet(position int, key string) (interface{}, bool) { return defaultCacheStore.Get(fmt.Sprintf(PlcCacheKey, position, key)) } func PlcCacheSet(position int, key string, value interface{}) { if key == constvar.PlcCacheKeyFinishNumber { oldFinishNumber, exists := PlcCacheGet(position, key) if !exists || cast.ToInt(oldFinishNumber) != cast.ToInt(value) { //finishNumber有了变化,设置更新时间缓存 FinishUpdateTimeSet(position, time.Now().Unix()) } } defaultCacheStore.Add(fmt.Sprintf(PlcCacheKey, position, key), value) } func FinishUpdateTimeGet(position int) interface{} { val, ok := defaultCacheStore.Get(fmt.Sprintf(PlcCacheKeyUpdateTime, position)) if ok { return val } return 0 } func FinishUpdateTimeSet(position int, value interface{}) { defaultCacheStore.Add(fmt.Sprintf(PlcCacheKeyUpdateTime, position), value) } func TaskCacheSet(value *response.TaskData) { defaultCacheStore.Add(CurrentTaskCacheKey, value) } func TaskCacheUnset() { defaultCacheStore.Remove(CurrentTaskCacheKey) } func TaskCacheGet() (*response.TaskData, bool) { if v, ok := defaultCacheStore.Get(CurrentTaskCacheKey); ok { return v.(*response.TaskData), ok } return nil, false } func ProgressCacheGet(position int) (*model.ProductionProgress, bool) { if v, ok := defaultCacheStore.Get(fmt.Sprintf(CurrentProgressCacheKey, position)); ok { return v.(*model.ProductionProgress), ok } return nil, false } func ProgressCacheSet(position int, value *model.ProductionProgress) { defaultCacheStore.Add(fmt.Sprintf(CurrentProgressCacheKey, position), value) } func ProgressCacheUnset(position int) { defaultCacheStore.Remove(fmt.Sprintf(CurrentProgressCacheKey, position)) }