我正在golang写两个服务,需要每秒发送约200万条消息。每条消息约为50个字节,因此吞吐量应仅为100MB/s。我想为此使用TCP。但是,结果非常慢。我配置了setNodelay(false(,以确保在发送之前对数据进行缓冲,但这没有任何区别。
我只能每秒发送约50k消息,消息大小并不重要,因此我认为代码在某个地方被阻止。这是我的测试代码:
package main
import "net"
import "fmt"
import "bufio"
import (
//"strings"
"time"
)
func startserver() {
fmt.Println("Launching server...")
ln, _ := net.Listen("tcp", ":8081")
conn, _ := ln.Accept()
for {
bufio.NewReader(conn).ReadString('n')
//fmt.Println(message)
//newmessage := strings.ToUpper(message)
//conn.Write([]byte(newmessage + "n"))
}
}
func startclient() {
time.Sleep(time.Second) // so that server has time to start
servAddr := "127.0.0.1:8081"
tcpAddr, _ := net.ResolveTCPAddr("tcp", servAddr)
conn, _ := net.DialTCP("tcp", nil, tcpAddr)
conn.SetNoDelay(false)
conn.SetWriteBuffer(10000)
msg := "abcn"
start := time.Now()
for i := 0; i < 1000000; i++ {
conn.Write([]byte(msg))
//bufio.NewReader(conn).ReadString('n')
//fmt.Print("Message from server: ", response)
}
fmt.Println("took:", time.Since(start))
}
func main() {
go startserver()
startclient()
}
任何建议?
syscalls很昂贵,并且通过回环编写数据非常快,因此这实际上只是时间到达您可以拨打100万个write
的时间。
进行大量的小读物和写入是使用缓冲io的主要用例。将普通net.TCPConn
包装在bufio.Writer
中将提供预期的性能提高。