http请求支持预热接口数据并缓存 #1

Merged
zhangdeman merged 3 commits from feature/preheat_cache into master 2024-10-09 19:06:14 +08:00
2 changed files with 38 additions and 2 deletions
Showing only changes of commit 10a21dc357 - Show all commits

View File

@ -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()

View File

@ -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 的配置
}