先貼代碼,這種測試沒多少意義,僅作為記錄。以後搞清楚golang的套路之後,估計性能還能有提高的空間。
因為對golang還不是很熟悉,是以隻能寫成這個程度了。希望未來能打臉。
package main
import "net/http"
type handler struct{}
var welcome = []byte{97, 98}
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
//OK
w.WriteHeader(200)
if _, e := w.Write(welcome); e != nil {
panic(e)
}
}
func main() {
server := http.Server{
Addr: "0.0.0.0:8088",
Handler: &handler{},
}
err := server.ListenAndServe()
if err != nil {
panic(err)
}
}
Java使用最新的穩定版本netty 4.1.39.Final,不使用tc-native,不調優。
public class SimpleHttpServer {
public static void main(String[] args) throws InterruptedException {
ServerBootstrap server = new ServerBootstrap()
.group(new NioEventLoopGroup(), new NioEventLoopGroup())
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline()
.addLast(new HttpServerCodec())
.addLast(new HttpHelloWorldServerHandler());
}
});
Channel ch = server.bind(8088).sync().channel();
ch.closeFuture().sync();
}
}
public class HttpHelloWorldServerHandler extends SimpleChannelInboundHandler {
private static final byte[] CONTENT = {97, 98};
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
if (msg instanceof HttpRequest) {
HttpRequest req = (HttpRequest) msg;
boolean keepAlive = HttpUtil.isKeepAlive(req);
FullHttpResponse response = new DefaultFullHttpResponse(req.protocolVersion(), OK,
Unpooled.wrappedBuffer(CONTENT));
if (keepAlive) {
if (!req.protocolVersion().isKeepAliveDefault()) {
response.headers().set(CONNECTION, KEEP_ALIVE);
}
} else {
// Tell the client we're going to close the connection.
response.headers().set(CONNECTION, CLOSE);
}
ChannelFuture f = ctx.write(response);
if (!keepAlive) {
f.addListener(ChannelFutureListener.CLOSE);
}
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
筆記本測試,性能不是太高,CPU太爛(i5 8250U 1.6GHz 1.8GHz),系統(windows 10 home basic)
golang http server
28900 requests/sec
netty http server
冷啟動:31000 requests/sec
熱身後:35900 requests/sec
測試指令
ab -n 1000000 -c 1000 -k http://localhost:8088/hello/world
有疑問加站長微信聯系(非本文作者)