From 9b0069f8991af97bea8827e08dcfce662b077adc Mon Sep 17 00:00:00 2001 From: keepchen Date: Sun, 4 Feb 2024 14:44:49 +0800 Subject: [PATCH] fix:sync.Once usage --- constants/code.go | 7 +++++-- http/middleware/prometheusexporter.go | 3 ++- lib/cache/localkv.go | 7 +++++-- schedule/schedule.go | 10 +++++++--- 4 files changed, 19 insertions(+), 8 deletions(-) diff --git a/constants/code.go b/constants/code.go index 5433ea3..5bbe54e 100644 --- a/constants/code.go +++ b/constants/code.go @@ -16,7 +16,10 @@ type errorCodeTypeMsgMap struct { maps map[LanguageCode]map[ICodeType]string } -var ctm *errorCodeTypeMsgMap +var ( + ctm *errorCodeTypeMsgMap + once sync.Once +) // RegisterCode 注册常量代码 // @@ -30,7 +33,7 @@ func RegisterCode(language LanguageCode, i18nMsg map[ICodeType]string) { } func init() { - (&sync.Once{}).Do(func() { + once.Do(func() { ctm = &errorCodeTypeMsgMap{ mux: &sync.RWMutex{}, maps: make(map[LanguageCode]map[ICodeType]string), diff --git a/http/middleware/prometheusexporter.go b/http/middleware/prometheusexporter.go index 6cd5810..2a10a99 100644 --- a/http/middleware/prometheusexporter.go +++ b/http/middleware/prometheusexporter.go @@ -38,12 +38,13 @@ func (r responseBodyWriter) Write(b []byte) (int, error) { } var ( + once sync.Once metricsSummaryVecLatency *prometheus.SummaryVec metricsSummaryVecHttpStatus *prometheus.SummaryVec ) func init() { - (&sync.Once{}).Do(func() { + once.Do(func() { svl := prometheus.NewSummaryVec(prometheus.SummaryOpts{ Name: "api_durations", Help: "[api] http latency distributions (milliseconds)", diff --git a/lib/cache/localkv.go b/lib/cache/localkv.go index 4af577f..e7ca493 100644 --- a/lib/cache/localkv.go +++ b/lib/cache/localkv.go @@ -17,10 +17,13 @@ type localCache struct { maps map[string]*localCacheValue } -var lc *localCache +var ( + lc *localCache + once sync.Once +) func init() { - (&sync.Once{}).Do(func() { + once.Do(func() { lc = &localCache{ mux: &sync.Mutex{}, maps: make(map[string]*localCacheValue), diff --git a/schedule/schedule.go b/schedule/schedule.go index 89d10e3..268b54d 100644 --- a/schedule/schedule.go +++ b/schedule/schedule.go @@ -117,10 +117,14 @@ type taskJobPool struct { var taskSchedules *taskJobPool -var cronJob *cron.Cron +var ( + cronJob *cron.Cron + cronStartOnce sync.Once + initOnce sync.Once +) func init() { - (&sync.Once{}).Do(func() { + initOnce.Do(func() { taskSchedules = &taskJobPool{ mux: &sync.RWMutex{}, pool: make(map[string]*taskJob), @@ -241,7 +245,7 @@ func (j *taskJob) run() { // // +------------------------- minute (0 - 59) func (j *taskJob) RunAt(crontabExpr string) (cancel CancelFunc) { - (&sync.Once{}).Do(func() { + cronStartOnce.Do(func() { cronJob = cron.New() cronJob.Start() })