From 7c375988049a62e33c06be508276f0597fdcfc9d Mon Sep 17 00:00:00 2001 From: tsosunchia <59512455+tsosunchia@users.noreply.github.com> Date: Fri, 2 Jun 2023 18:13:27 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B0=86GeoIPInformatinDataCache=E6=8E=A8?= =?UTF-8?q?=E5=B9=BF=E5=88=B0=E6=89=80=E6=9C=89=E6=95=B0=E6=8D=AE=E6=BA=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ipgeo/leo.go | 8 -------- trace/trace.go | 13 ++++++++++++- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/ipgeo/leo.go b/ipgeo/leo.go index 9c7f27b..6d62649 100644 --- a/ipgeo/leo.go +++ b/ipgeo/leo.go @@ -28,7 +28,6 @@ type IPPool struct { var IPPools = IPPool{ pool: make(map[string]chan IPGeoData), } -var queryCache = sync.Map{} func sendIPRequest(ip string) { wsConn := wshandle.GetWsConn() @@ -90,11 +89,6 @@ func LeoIP(ip string, timeout time.Duration, lang string, maptrace bool) (*IPGeo if timeout < 5*time.Second { timeout = 5 * time.Second } - if value, ok := queryCache.Load(ip); ok { - // 从缓存中成功获取到IP信息 - //fmt.Println("Get IP Data From Cache", ip) - return value.(*IPGeoData), nil - } // 缓存中没有找到IP信息,需要请求API获取 IPPools.poolMux.Lock() @@ -111,8 +105,6 @@ func LeoIP(ip string, timeout time.Duration, lang string, maptrace bool) (*IPGeo // 拥塞,等待数据返回 select { case res := <-IPPools.pool[ip]: - // 将API请求到的IP信息存入缓存 - queryCache.Store(ip, &res) return &res, nil // 5秒后依旧没有接收到返回的IP数据,不再等待,超时异常处理 case <-time.After(timeout): diff --git a/trace/trace.go b/trace/trace.go index a85c099..ddf3050 100644 --- a/trace/trace.go +++ b/trace/trace.go @@ -14,6 +14,7 @@ var ( ErrInvalidMethod = errors.New("invalid method") ErrTracerouteExecuted = errors.New("traceroute already executed") ErrHopLimitTimeout = errors.New("hop timeout") + geoCache = sync.Map{} ) type Config struct { @@ -173,7 +174,17 @@ func (h *Hop) fetchIPData(c Config) (err error) { if c.Timeout < 2*time.Second { timeout = 2 * time.Second } - h.Geo, err = c.IPGeoSource(h.Address.String(), timeout, c.Lang, c.Maptrace) + //h.Geo, err = c.IPGeoSource(h.Address.String(), timeout, c.Lang, c.Maptrace) + if cacheVal, ok := geoCache.Load(h.Address.String()); ok { + // 如果缓存中已有结果,直接使用 + h.Geo = cacheVal.(*ipgeo.IPGeoData) + } else { + // 如果缓存中无结果,进行查询并将结果存入缓存 + h.Geo, err = c.IPGeoSource(h.Address.String(), timeout, c.Lang, c.Maptrace) + if err == nil { + geoCache.Store(h.Address.String(), h.Geo) + } + } } } // Fetch Done