dounou9751 2015-11-20 15:58
浏览 28

在Go服务器中使用go例程

I need to write a simple web server in Go. It accepts requests, maps the request to avro object and sends it to Kafka. The requirement is that it answers immediately to keep the latency low for the users. Mapping to avro object and sending to Kafka can happen asynchronously. I came up with the following design, but I wonder if it is using Go structures in the intended way or if it can be optimized using channels for example. I'm omitting private methods and initializing structures. The problem is that the server can handle up to 10500 requests a second and then the response time goes up dramatically. So I was wondering if there is a way to optimize it.

func main() {
 runtime.GOMAXPROCS(runtime.NumCPU()) // not needed in Go 1.5.0
 server := &Server{
    Producer: newProducer(brokerList),
 }
 defer func() {
    if err := server.Close(); err != nil {
        Error.Println("Failed to close server", err)
    }
  }()
  Error.Fatal(server.Run(*addr))
}

func (s *Server) Run(addr string) error {
  httpServer := &http.Server{
    Addr:    addr,
    Handler: s.Handler(),
  }
  return httpServer.ListenAndServe()
}

func (s *Server) Handler() http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    defer r.Body.Close()
    req, err := ParseRequest(r.Body)
    if err != nil {
        Warning.Println("Failed to parse request", err.Error())
    } else {
        go handleRequest(s, req)
    }
    w.WriteHeader(204) // respond with 'no bid'
  )
}

func handleRequest(s *Server, req *openrtb.BidRequest) {
  req.Validate()
  var avroObject, err = createAvro(req)
  if err != nil {
        Warning.Printf(err.Error())
  }
  if avroObject != nil {
    sendToKafka(avroObject, s)
  }
 }
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 测距传感器数据手册i2c
    • ¥15 RPA正常跑,cmd输入cookies跑不出来
    • ¥15 求帮我调试一下freefem代码
    • ¥15 matlab代码解决,怎么运行
    • ¥15 R语言Rstudio突然无法启动
    • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
    • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
    • ¥15 用windows做服务的同志有吗
    • ¥60 求一个简单的网页(标签-安全|关键词-上传)
    • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法