From 10a21dc35745a9290e99faa65b17d28ef1db8de7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Wed, 9 Oct 2024 19:05:38 +0800 Subject: [PATCH] =?UTF-8?q?http=E8=AF=B7=E6=B1=82=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E9=A2=84=E7=83=AD=E6=8E=A5=E5=8F=A3=E6=95=B0=E6=8D=AE=E5=B9=B6?= =?UTF-8?q?=E7=BC=93=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- client.go | 37 ++++++++++++++++++++++++++++++++++++- define/cache.go | 3 ++- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/client.go b/client.go index 0cc7802..611271c 100644 --- a/client.go +++ b/client.go @@ -148,7 +148,42 @@ func (hc *HttpClient) Request() *define.Response { ) if cacheResult = hc.getCacheResult(); nil != cacheResult { - return cacheResult + // 判断是否开启预热 + inputCachePreHeatConfig := hc.cacheInstance.PreHeatConfig() + var cachePreHeatConfig define.CachePreHeatConfig + serialize.JSON.TransitionIgnoreError(inputCachePreHeatConfig, &cachePreHeatConfig) + if !cachePreHeatConfig.Enable || (cachePreHeatConfig.MinTTL <= 0 && cachePreHeatConfig.MinPercent <= 0 && !cachePreHeatConfig.Force) { + // 无预热配置或未启用预热或者未设置预热规则 + return cacheResult + } + go func() { + // 判断是否触发预热 + if cachePreHeatConfig.Force { + _ = hc.requestBackendApi() + return + } + // 将百分比的配置归一化成最小剩余时间的配置 + if cachePreHeatConfig.MinPercent > 0 { + expectMinTTL := hc.cacheInstance.CacheTime() * cachePreHeatConfig.MinPercent / 100 + if cachePreHeatConfig.MinTTL == 0 || cachePreHeatConfig.MinTTL > expectMinTTL { + cachePreHeatConfig.MinTTL = expectMinTTL + } + } + if cachePreHeatConfig.MinTTL <= 0 { + // 未配置最小剩余时间 + return + } + ttl := hc.cacheInstance.TTL(cacheResult.CacheInfo.CacheKey) + if ttl < 0 { + // 不存在或者未设置有效期 + return + } + + if ttl <= cachePreHeatConfig.MinTTL { + // 配置了最小剩余时间,并且key剩余有效期小于最小剩余时间 + _ = hc.requestBackendApi() + } + }() } return hc.requestBackendApi() diff --git a/define/cache.go b/define/cache.go index c503208..24c74a3 100644 --- a/define/cache.go +++ b/define/cache.go @@ -14,6 +14,7 @@ package define // Date : 18:40 2024/10/9 type CachePreHeatConfig struct { Enable bool `json:"enable"` // 缓存预热是否可用 - MinPercent int `json:"min_percent"` // 最小百分比, 剩余有效期低于此百分比进行预热 + MinPercent int64 `json:"min_percent"` // 最小百分比, 剩余有效期低于此百分比进行预热 MinTTL int64 `json:"min_ttl"` // 最小剩余生命周期, 低于此百分比进行预热 + Force bool `json:"force"` // 启用预热的情况下, 强制预热, 会忽略 MinPercent / MinTTL 的配置 }