先贴代码,这种测试没多少意义,仅作为记录。以后搞清楚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<SocketChannel>() {
@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<HttpObject> {
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/secnetty http server
冷启动:31000 requests/sec
热身后:35900 requests/sec
测试指令
ab -n 1000000 -c 1000 -k http://localhost:8088/hello/world