RPC VS HTTP go语言实现
理论分析
RPC
和 HTTP
都是基于 TCP
协议的,所以两者在 网络链路层 网络层 传输层 都是一样的,唯一不同的地方就是 应用层的协议不同
两者共同的开销 : 以太网头部(14个字节) + IP头部(20个字节或更多)+ TCP头部(20个字节或更多)
HTTP
协议的开销 : 主要是集中在请求头,当然了,出于效率的考虑,你可以减少携带的请求头数量. (50个字节或者更多)
POST /hello HTTP1.1
Content-type:text/html;
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36
....
Body
RPC
协议的开销: 函数名,参数.几乎没有其他额外的开销.
type Call struct {
ServiceMethod string // The name of the service and method to call.
Args any // The argument to the function (*struct).
Reply any // The reply from the function (*struct).
Error error // After completion, the error status.
Done chan *Call // Receives *Call when Go is complete.
}
可以发现 RPC
的开销是更小的,但是也不多,我个人认为两者的性能差距是很小的,不过我的测试结果似乎不太相同.
设计实验
简单来说就是分别开启 HTTP
服务器 和 RPC
服务器,利用go语言自带的测试框架比较其性能就好了.
HTTP服务器
func HttpServer() {
// 创建一个http服务器
server := http.Server{
Addr: config.HttpServerPort,
}
http.HandleFunc("/hello", func(writer http.ResponseWriter, request *http.Request) {
request.ParseForm()
length := request.Form.Get("length")
atoi, _ := strconv.Atoi(length)
writer.Write([]byte(CreateString(atoi)))
})
server.ListenAndServe()
}
发送HTTP请求
func HttpRequest() {
url := "http://localhost" + config.HttpServerPort + "/hello?length=10"
method := "GET"
client := &http.Client