前言

我们使用的是golang标准库的http client,对于一些http请求,我们在处理的时候,会考虑加上超时时间,防止http请求一直在请求,导致业务长时间阻塞等待。

最近同事写了一个超时的组件,这几天访问量上来了,网络也出现了波动,造成了接口在报错超时的情况下,还是出现了请求结果的成功。

分析下具体的代码实现

type request struct {
 method string
 url    string
 value  string
 ps     *params
}

type params struct {
 timeout     int //超时时间
 retry       int //重试次数
 headers     map[string]string
 contenttype string
}

func (req *request) do(result interface{}) ([]byte, error) {
 res, err := asynccall(dorequest, req)
 if err != nil {
  return nil, err
 }

 if result == nil {
  return res, nil
 }

 switch req.ps.contenttype {
 case "application/xml":
  if err := xml.unmarshal(res, result); err != nil {
   return nil, err
  }
 default:
  if err := json.unmarshal(res, result); err != nil {
   return nil, err
  }
 }

 return res, nil
}
type timeout struct {
 data []byte
 err  error
}


func dorequest(request *request) ([]byte, error) {
 var (
  req    *http.request
  errreq error
 )
 if request.value != "null" {
  buf := strings.newreader(request.value)
  req, errreq = http.newrequest(request.method, request.url, buf)
  if errreq != nil {
   return nil, errreq
  }
 } else {
  req, errreq = http.newrequest(request.method, request.url, nil)
  if errreq != nil {
   return nil, errreq
  }
 }
 // 这里的client没有设置超时时间
 // 所以当下面检测到一次超时的时候,会重新又发起一次请求
 // 但是老的请求其实没有被关闭,一直在执行
 client := http.client{}
 res, err := client.do(req)
 ...
}

// 重试调用请求
// 当超时的时候发起一次新的请求
func asynccall(f func(request *request) ([]byte, error), req *request) ([]byte, error) {
 p := req.ps
 ctx := context.background()
 done := make(chan *timeout, 1)

 for i := 0; i < p.retry; i++ {
  go func(ctx context.context) {
   // 发送http请求
   res, err := f(req)
   done <- &timeout{
    data: res,
    err:  err,
   }
  }(ctx)
  // 错误主要在这里
  // 如果超时重试为3,第一次超时了,马上又发起了一次新的请求,但是这里错误使用了超时的退出
  // 具体看上面
  select {
  case res := <-done:
   return res.data, res.err
  case <-time.after(time.duration(p.timeout) * time.millisecond):
  }
 }
 return nil, ecode.timeouterr
}

错误的原因

1、超时重试,之后过了一段时间没有拿到结果就认为是超时了,但是http请求没有被关闭;

2、错误使用了http的超时,具体的做法要通过context或http.client去实现,见下文;

修改之后的代码

func dorequest(request *request) ([]byte, error) {
 var (
  req    *http.request
  errreq error
 )
 if request.value != "null" {
  buf := strings.newreader(request.value)
  req, errreq = http.newrequest(request.method, request.url, buf)
  if errreq != nil {
   return nil, errreq
  }
 } else {
  req, errreq = http.newrequest(request.method, request.url, nil)
  if errreq != nil {
   return nil, errreq
  }
 }

 // 这里通过http.client设置超时时间
 client := http.client{
  timeout: time.duration(request.ps.timeout) * time.millisecond,
 }
 res, err := client.do(req)
 ...
}

func asynccall(f func(request *request) ([]byte, error), req *request) ([]byte, error) {
 p := req.ps
 // 重试的时候只有上一个http请求真的超时了,之后才会发起一次新的请求
 for i := 0; i < p.retry; i++ {
  // 发送http请求
  res, err := f(req)
  // 判断超时
  if neterr, ok := err.(net.error); ok && neterr.timeout() {
   continue
  }

  return res, err

 }
 return nil, ecode.timeouterr
}

服务设置超时

http.server有两个设置超时的方法:

readtimeout
readtimeout的时间计算是从连接被接受(accept)到request body完全被读取(如果你不读取body,那么时间截止到读完header为止)

writetimeout
writetimeout的时间计算正常是从request header的读取结束开始,到response write结束为止 (也就是servehttp方法的生命周期)

srv := &http.server{  
    readtimeout: 5 * time.second,
    writetimeout: 10 * time.second,
}

 
srv.listenandserve()

net/http包还提供了timeouthandler返回了一个在给定的时间限制内运行的handler

func timeouthandler(h handler, dt time.duration, msg string) handler

第一个参数是handler,第二个参数是time.duration(超时时间),第三个参数是string类型,当到达超时时间后返回的信息

func handler(w http.responsewriter, r *http.request) {
 time.sleep(3 * time.second)
 fmt.println("测试超时")

 w.write([]byte("hello world"))
}

func server() {
 srv := http.server{
  addr:         ":8081",
  writetimeout: 1 * time.second,
  handler:      http.timeouthandler(http.handlerfunc(handler), 5*time.second, "timeout!\n"),
 }
 if err := srv.listenandserve(); err != nil {
  os.exit(1)
 }
}

客户端设置超时

http.client
最简单的我们通过http.client的timeout字段,就可以实现客户端的超时控制

http.client超时是超时的高层实现,包含了从dial到response body的整个请求流程。http.client的实现提供了一个结构体类型可以接受一个额外的time.duration类型的timeout属性。这个参数定义了从请求开始到响应消息体被完全接收的时间限制。

func httpclienttimeout() {
 c := &http.client{
  timeout: 3 * time.second,
 }

 resp, err := c.get("http://127.0.0.1:8081/test")
 fmt.println(resp)
 fmt.println(err)
}

context
net/http中的request实现了context,所以我们可以借助于context本身的超时机制,实现http中request的超时处理

func contexttimeout() {
 ctx, cancel := context.withtimeout(context.background(), 3*time.second)
 defer cancel()

 req, err := http.newrequest("get", "http://127.0.0.1:8081/test", nil)
 if err != nil {
  log.fatal(err)
 }

 resp, err := http.defaultclient.do(req.withcontext(ctx))
 fmt.println(resp)
 fmt.println(err)
}

使用context的优点就是,当父context被取消时,子context就会层层退出。

http.transport
通过transport还可以进行一些更小维度的超时设置

  • net.dialer.timeout 限制建立tcp连接的时间
  • http.transport.tlshandshaketimeout 限制 tls握手的时间
  • http.transport.responseheadertimeout 限制读取response header的时间
  • http.transport.expectcontinuetimeout 限制client在发送包含 expect: 100-continue的header到收到继续发送body的response之间的时间等待。注意在1.6中设置这个值会禁用http/2(defaulttransport自1.6.2起是个特例)
func transporttimeout() {
 transport := &http.transport{
  dialcontext:           (&net.dialer{}).dialcontext,
  responseheadertimeout: 3 * time.second,
 }

 c := http.client{transport: transport}

 resp, err := c.get("http://127.0.0.1:8081/test")
 fmt.println(resp)
 fmt.println(err)
}

问题
如果在客户端在超时的临界点,触发了超时机制,这时候服务端刚好也接收到了,http的请求

这种服务端还是可以拿到请求的数据,所以对于超时时间的设置我们需要根据实际情况进行权衡,同时我们要考虑接口的幂等性。

总结

1、所有的超时实现都是基于deadline,deadline是一个时间的绝对值,一旦设置他们永久生效,不管此时连接是否被使用和怎么用,所以需要每手动设置,所以如果想使用setdeadline建立超时机制,需要每次在read/write操作之前调用它。

2、使用context进行超时控制的好处就是,当父context超时的时候,子context就会层层退出。

参考

【[译]go net/http 超时机制完全手册】
【go 语言 http 请求超时入门】
【使用 timeout、deadline 和 context 取消参数使 go net/http 服务更灵活】

到此这篇关于go语言中http超时引发的事故解决的文章就介绍到这了,更多相关go语言 http超时内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!