Golang搭建jsonRPC服务器,Python客户端高并发10000组请求压力测试
By
jerryxjr1220
at 2022-10-31 • 0人收藏 • 801人看过
Golang原生支持多线程(协程),所以处理高并发有非常优异的性能表现,非常适合用来搭建服务器。
这里用Golang搭建jsonRPC服务器,Python客户端高并发10000组请求压力测试
Golang jsonRPC服务器:
package main import ( "net" "net/rpc" "net/rpc/jsonrpc" "strings" ) type MyFunc struct { } func (self MyFunc) DoSomething(p []string, reply *string) error { *reply = strings.Join(p, ", ") return nil } func main() { server := rpc.NewServer() server.RegisterName("Do", new(MyFunc)) listener, _ := net.Listen("tcp", "127.0.0.1:10001") defer listener.Close() for { conn, _ := listener.Accept() defer conn.Close() //rpc.ServeConn(conn) go server.ServeCodec(jsonrpc.NewServerCodec(conn)) } }
Python jsonRPC客户端
import json import socket import time from threading import Thread class RPCClient(): def __init__(self, addr): self.socket = socket.create_connection(addr) self.id = 0 def message(self, name, *params): self.id += 1 return dict(id=self.id, params=list(params), method=name) def call(self, name, *params): req = self.message(name, *params) id = req.get('id') mesg = json.dumps(req) self.socket.sendall(mesg.encode()) resp = self.socket.recv(4096) resp = json.loads(resp.decode()) return resp def close(self): self.socket.close() def call(names): rpc = RPCClient(("127.0.0.1", 10001)) rpc.call("Do.DoSomething", list(names)) start = time.time() for _ in range(10000): t = Thread(target=call, args=(("Tom", "Jerry"),)) t.daemon = True t.start() print("10000组jsonRPC高并发请求,用时", time.time()-start, "秒")
测试结果:
10000组jsonRPC高并发请求,用时 1.7656581401824951 秒
Golang的服务器响应还是非常令人满意的
8 个回复 | 最后更新于 2022-11-01
2022-10-31
#2
如果用Golang的jsonRPC客户端,同样进行10000次高并发请求
package main import ( "fmt" "net" "net/rpc" "net/rpc/jsonrpc" "time" ) type ReplyStruct struct { Success bool Result string } func main() { st := time.Now().UnixMilli() ch := make(chan string, 10000) for i := 1; i < 10000; i++ { go visit(ch) } for i := 1; i < 10000; i++ { <-ch } ed := time.Now().UnixMilli() fmt.Println("10000组jsonRPC高并发,耗时", ed-st, "毫秒") } func visit(ch chan string) { //client, _ := rpc.Dial("tcp", "127.0.0.1:10001") conn, _ := net.Dial("tcp", "127.0.0.1:10001") //defer client.Close() defer conn.Close() client := rpc.NewClientWithCodec(jsonrpc.NewClientCodec(conn)) reply := new(ReplyStruct) client.Call("Do.DoSomething", []string{"I", "Love", "you"}, &reply) ch <- reply.Result }
测试结果:
10000组jsonRPC高并发,耗时 1581 毫秒
登录后方可回帖
Golang性能优异,但Python的多线程就没那么高效了,所以,如果自己的电脑不太行的话,不要轻易尝试10000组高并发,很容易把电脑搞崩溃的