refactor(proxy): 消除缓存处理中的 goto 语句
重构 ServeHTTP 中的缓存逻辑,用嵌套 if 结构替代 goto proxyRequest, 使控制流更清晰。主要变更: - 缓存命中逻辑内聚到 rule != nil 分支 - 缓存锁等待后重新检查缓存命中 - 移除 proxyRequest 标签 Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
parent
d933c1bd98
commit
4697f39924
@ -601,11 +601,7 @@ func (p *Proxy) ServeHTTP(ctx *fasthttp.RequestCtx) {
|
|||||||
method := string(ctx.Request.Header.Method())
|
method := string(ctx.Request.Header.Method())
|
||||||
path := string(ctx.Request.URI().Path())
|
path := string(ctx.Request.URI().Path())
|
||||||
rule := p.cache.MatchRule(path, method, 0)
|
rule := p.cache.MatchRule(path, method, 0)
|
||||||
if rule == nil {
|
if rule != nil {
|
||||||
// 方法不在允许列表中,跳过缓存
|
|
||||||
goto proxyRequest
|
|
||||||
}
|
|
||||||
|
|
||||||
hashKey, origKey := p.buildCacheKeyHash(ctx)
|
hashKey, origKey := p.buildCacheKeyHash(ctx)
|
||||||
if entry, ok, stale := p.cache.Get(hashKey, origKey); ok {
|
if entry, ok, stale := p.cache.Get(hashKey, origKey); ok {
|
||||||
// 缓存命中
|
// 缓存命中
|
||||||
@ -628,7 +624,7 @@ func (p *Proxy) ServeHTTP(ctx *fasthttp.RequestCtx) {
|
|||||||
p.backgroundRefresh(ctx, target, hashKey, origKey)
|
p.backgroundRefresh(ctx, target, hashKey, origKey)
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
upstreamAddr = "CACHE"
|
upstreamAddr = upstreamCache
|
||||||
upstreamStatus = entry.Status
|
upstreamStatus = entry.Status
|
||||||
|
|
||||||
p.writeCachedResponse(ctx, entry)
|
p.writeCachedResponse(ctx, entry)
|
||||||
@ -644,10 +640,7 @@ func (p *Proxy) ServeHTTP(ctx *fasthttp.RequestCtx) {
|
|||||||
timeout = 5 * time.Second // nginx 默认 5s
|
timeout = 5 * time.Second // nginx 默认 5s
|
||||||
}
|
}
|
||||||
waitCh, timedOut := p.cache.AcquireLockWithTimeout(hashKey, timeout)
|
waitCh, timedOut := p.cache.AcquireLockWithTimeout(hashKey, timeout)
|
||||||
if timedOut {
|
if !timedOut && waitCh != nil {
|
||||||
// 超时,跳过缓存直接请求上游
|
|
||||||
// 不缓存响应(nginx 行为)
|
|
||||||
} else if waitCh != nil {
|
|
||||||
// 有其他请求正在生成缓存,等待
|
// 有其他请求正在生成缓存,等待
|
||||||
loadbalance.DecrementConnections(target)
|
loadbalance.DecrementConnections(target)
|
||||||
<-waitCh
|
<-waitCh
|
||||||
@ -666,9 +659,10 @@ func (p *Proxy) ServeHTTP(ctx *fasthttp.RequestCtx) {
|
|||||||
// 缓存未命中,需要重新选择目标
|
// 缓存未命中,需要重新选择目标
|
||||||
loadbalance.IncrementConnections(target)
|
loadbalance.IncrementConnections(target)
|
||||||
}
|
}
|
||||||
|
// timedOut 或获得锁:继续执行代理请求
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
proxyRequest:
|
|
||||||
// 执行代理请求
|
// 执行代理请求
|
||||||
timing.MarkConnectStart()
|
timing.MarkConnectStart()
|
||||||
err := client.Do(req, &ctx.Response)
|
err := client.Do(req, &ctx.Response)
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user