From 21e8334773a573d6760a4d132678fd4837a463a4 Mon Sep 17 00:00:00 2001 From: u Date: Thu, 8 Jun 2023 14:04:20 +0800 Subject: [PATCH] 'fix' --- core.go | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/core.go b/core.go index 4d7a24c..6809f6a 100644 --- a/core.go +++ b/core.go @@ -1,6 +1,8 @@ package time_arrow import ( + "crypto/md5" + "encoding/hex" "encoding/json" "fmt" "log" @@ -398,7 +400,8 @@ func GetHolidaysDataWithCache() ([]HolidaysItem, error) { } type TimeArrowHelper struct { - GetData func(group string) (TimeArrows, error) + GetData func(group string) (TimeArrows, error) + cacheMap map[string]*TimeArrow } func (th *TimeArrowHelper) CallHitTimeArrow(t time.Time, group string, call func(*TimeArrow), expandTags ...string) error { @@ -464,11 +467,36 @@ func (th *TimeArrowHelper) CallHitTimeArrow(t time.Time, group string, call func return nil } +func md52Str(text string) string { + h := md5.New() + h.Write([]byte(text)) + return hex.EncodeToString(h.Sum(nil)) +} + +var hitTimeArrowCache = map[string]*TimeArrow{} +var hitTimeArrowCacheLock sync.Mutex + func (th *TimeArrowHelper) GetHitTimeArrow(t time.Time, group string, expandTags ...string) (*TimeArrow, error) { ta, err := th.GetData(group) if err != nil { return nil, err } + + keyA := md52Str(jsonEncode(ta)) + keyB := md52Str(jsonEncode(t)) + keyD := md52Str(group) + keyC := md52Str(strings.Join(expandTags, "-")) + + key := fmt.Sprint(keyA, "_", keyB, "_", keyC, "_", keyD) + hitTimeArrowCacheLock.Lock() + defer hitTimeArrowCacheLock.Unlock() + if hitTimeArrowCache[key] != nil { + if hitTimeArrowCache[key].Group == "___nil" { + return nil, nil + } + return hitTimeArrowCache[key], nil + } + sort.Slice(ta, func(i, j int) bool { return ta[i].Weights > ta[j].Weights }) @@ -487,36 +515,42 @@ func (th *TimeArrowHelper) GetHitTimeArrow(t time.Time, group string, expandTags case TimeArrowTypeDayOfWeek: //一周中某一天是否判定 if isInWeekOfDay(t, ta[e]) { + hitTimeArrowCache[key] = &ta[e] return &ta[e], nil } break case TimeArrowTypeDayOfMonth: //一月中某一天是否判定 if isInDayOfMonth(t, ta[e]) { + hitTimeArrowCache[key] = &ta[e] return &ta[e], nil } break case TimeArrowTypeDateSlice: //一月中某一天是否判定 if isInDateSlice(t, ta[e]) { + hitTimeArrowCache[key] = &ta[e] return &ta[e], nil } break case TimeArrowTypeAtLastDayHolidays: //节假日最后一天 if isInAtLastDayHolidays(t) { + hitTimeArrowCache[key] = &ta[e] return &ta[e], nil } break case TimeArrowTypePriorToDayHolidays: //节假日前一天 if isInPriorToDayHolidays(t) { + hitTimeArrowCache[key] = &ta[e] return &ta[e], nil } break case TimeArrowTypeInHolidays: //节假日 if isInHolidays(t) { + hitTimeArrowCache[key] = &ta[e] return &ta[e], nil } break @@ -524,5 +558,8 @@ func (th *TimeArrowHelper) GetHitTimeArrow(t time.Time, group string, expandTags log.Println("类型错误:", ta[e].Type) } } + hitTimeArrowCache[key] = &TimeArrow{ + Group: "___nil", + } return nil, nil }