Fix [transport client] <考虑到缓存中间件命中缓存的情况,增加一步在闭包外给reply赋值的操作> #3411
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
尊敬的作者,您好:
最近在项目中使用到了您的kratos框架,我受益匪浅,感谢您能将如此优秀的作品开源分享。
在使用中,我发现有一个问题,希望能与您探讨。
您在中间件中使用了这样的设计:当客户端发起请求,从中间件开始,依次执行,后执行hander,再依次通过中间件返回。
我看到您在Docs说明了,可以自定义中间件,但当我加入缓存中间件时,发现这样一个问题:本代码似乎不支持缓存中间件命中缓存的情况。
下面是我自定义的缓存中间件相关代码,当命中缓存时,直接返回缓存结果,进入中间件返回链路,跳过了内层hander。
//Request Cache middleware
func RequestCacheCache() middleware.Middleware {
return func(handler middleware.Handler) middleware.Handler {
return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
if info, ok := transport.FromClientContext(ctx); ok {
if trans, ok := info.(http.Transporter); ok {
cacheKey := generateCacheKey(trans.Request())
cache, _ := ctx.Value(server.ContextCacheKey).(*server.RequestCache)
if cache != nil {
if value, ok := cache.Get(cacheKey); ok {
return value, nil
}
reply, err = handler(ctx, req)
if err == nil {
cache.Set(cacheKey, reply)
}
return reply, err
}
}
}
return handler(ctx, req)
}
再次感谢您的付出和支持。期待您的回复!
姓名:杜芝若
邮箱:[email protected] (非常期待得到您的回复)