聊聊dubbo-go-proxy的timeoutFilter


本文摘自网络,作者,侵删。

本文主要研究一下dubbo-go-proxy的timeoutFilter

timeoutFilter

dubbo-go-proxy/pkg/filter/timeout/timeout.go

func Init() {
    extension.SetFilterFunc(constant.TimeoutFilter, timeoutFilterFunc(0))
}

func timeoutFilterFunc(duration time.Duration) fc.FilterFunc {
    return New(duration).Do()
}

// timeoutFilter is a filter for control request time out.
type timeoutFilter struct {
    // global timeout
    waitTime time.Duration
}

// New create timeout filter.
func New(t time.Duration) filter.Filter {
    if t <= 0 {
        t = constant.DefaultTimeout
    }
    return &timeoutFilter{
        waitTime: t,
    }
}
timeoutFilter往extension设置了名为`dgp.filters.timeout的timeoutFilterFunc,默认的timeout为1s;timeoutFilterFunc执行的是timeoutFilter的Do方法

Do

dubbo-go-proxy/pkg/filter/timeout/timeout.go

// Do execute timeoutFilter filter logic.
func (f timeoutFilter) Do() fc.FilterFunc {
    return func(c fc.Context) {
        hc := c.(*contexthttp.HttpContext)

        ctx, cancel := context.WithTimeout(hc.Ctx, f.getTimeout(hc.Timeout))
        defer cancel()
        // Channel capacity must be greater than 0.
        // Otherwise, if the parent coroutine quit due to timeout,
        // the child coroutine may never be able to quit.
        finishChan := make(chan struct{}, 1)
        go func() {
            // panic by recovery
            c.Next()
            finishChan <- struct{}{}
        }()

        select {
        // timeout do.
        case <-ctx.Done():
            logger.Warnf("api:%s request timeout", hc.GetAPI().URLPattern)
            bt, _ := json.Marshal(filter.ErrResponse{Message: http.ErrHandlerTimeout.Error()})
            hc.SourceResp = bt
            hc.TargetResp = &client.Response{Data: bt}
            hc.WriteJSONWithStatus(http.StatusGatewayTimeout, bt)
            c.Abort()
        case <-finishChan:
            // finish call do something.
        }
    }
}

func (f timeoutFilter) getTimeout(t time.Duration) time.Duration {
    if t <= 0 {
        return f.waitTime
    }

    return t
}
Do方法会通过context.WithTimeout创建ctx及cancel,然后注册defer这个cancel func;之后创建finishChan,异步执行c.Next(),之后往finishChan写入数据;最后select判断ctx.Done()或者是finishChan;如果是ctx.Done()则表示timeout了,返回http.StatusGatewayTimeout

小结

dubbo-go-proxy的timeoutFilter默认设置了1s超时,它通过context.WithTimeout创建ctx及cancel,并异步执行c.Next(),若ctx.Done()则表示timeout了,返回http.StatusGatewayTimeout;若是读取到了finishChan则表示请求正常响应。

doc

  • dubbo-go-proxy

本文来自:51CTO博客

感谢作者:mb6018ead621887

查看原文:聊聊dubbo-go-proxy的timeoutFilter

相关阅读 >>

Golang和python的区别

非docker部署fabric2.2.0网络

Go调优神器trace介绍

Golang- Go语言学习笔记之定义变量

如何实现一个更全面的Golang版本的布谷鸟过滤器

关于Golang里的future/promise

Golang 自然语言处理工具(Gohanlp)

Go1.4 bootstrap 源码安装新版Go

Golang实现二倍均值算法和抢红包的方法

Go url

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...