• netty-reacter写一个http服务器


    使用Netty和Reactor编写一个HTTP服务器,首先需要添加相关依赖到项目中。在Maven项目的pom.xml文件中添加以下依赖:

    ```xml

       
            io.netty
            netty-all
            4.1.68.Final
       

       
            io.projectreactor
            reactor-core
            3.4.0
       


    ```

    接下来,创建一个Netty HTTP服务器的示例代码:

    ```java
    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.ChannelOption;
    import io.netty.channel.EventLoopGroup;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioServerSocketChannel;
    import io.netty.handler.codec.http.HttpRequestDecoder;
    import io.netty.handler.codec.http.HttpResponseEncoder;
    import reactor.core.publisher.Mono;

    public class NettyHttpServer {

        private final int port;

        public NettyHttpServer(int port) {
            this.port = port;
        }

        public void start() throws InterruptedException {
            EventLoopGroup bossGroup = new NioEventLoopGroup();
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            try {
                ServerBootstrap b = new ServerBootstrap();
                b.group(bossGroup, workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .childHandler(new ChannelInitializer() {
                            @Override
                            protected void initChannel(SocketChannel ch) throws Exception {
                                ch.pipeline().addLast(new HttpRequestDecoder());
                                ch.pipeline().addLast(new HttpResponseEncoder());
                                ch.pipeline().addLast(new HttpServerHandler());
                            }
                        })
                        .option(ChannelOption.SO_BACKLOG, 128)
                        .childOption(ChannelOption.SO_KEEPALIVE, true);

                ChannelFuture f = b.bind(port).sync();
                System.out.println("HTTP服务器启动,监听端口:" + port);
                f.channel().closeFuture().sync();
            } finally {
                workerGroup.shutdownGracefully();
                bossGroup.shutdownGracefully();
            }
        }

        public static void main(String[] args) throws InterruptedException {
            new NettyHttpServer(8080).start();
        }
    }
    ```

    上面的代码中,创建了一个Netty HTTP服务器,监听8080端口。当有客户端连接时,会调用`HttpServerHandler`来处理请求。接下来,我们需要实现`HttpServerHandler`类来处理HTTP请求:

    ```java
    import io.netty.buffer.Unpooled;
    import io.netty.channel.ChannelFutureListener;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.SimpleChannelInboundHandler;
    import io.netty.handler.codec.http.*;
    import reactor.core.publisher.Mono;

    import java.nio.charset.StandardCharsets;

    public class HttpServerHandler extends SimpleChannelInboundHandler {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
            if (req.method() == HttpMethod.GET) {
                handleGet(ctx, req);
            } else {
                sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
            }
        }

        private void handleGet(ChannelHandlerContext ctx, FullHttpRequest req) {
            String responseBody = "Hello, Netty and Reactor!";
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer(responseBody, StandardCharsets.UTF_8));
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, responseBody.length());

            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        }

        private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);

            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        }
    }
    ```

    在上面的代码中,我们实现了一个简单的HTTP服务器,只处理GET请求,并返回"Hello, Netty and Reactor!"作为响应。运行`NettyHttpServer`的`main`方法,启动服务器后,可以使用浏览器或其他HTTP客户端访问`http://localhost:8080`,看到返回的响应。 

  • 相关阅读:
    @Aspect注解使用说明
    ​孤网双机并联逆变器下垂控制策略(包括仿真模型,功率计算模块、下垂控制模块、电压电流双环控制模块​)(Simulink仿真)
    计算机网络那些事之 MTU 篇 pt.2
    全网最全谷粒商城记录_08、环境-linux安装docker
    Filebeat自定义index和fields
    『华强买瓜』奇袭好莱坞!Jupyter也能创建可交互仪表板啦!超全面的英语论文写作套路;神经辐射场NeRF工具包;前沿论文 | ShowMeAI资讯日报
    flask与fastapi性能测试
    三篇卫星切换的论文
    【BookStack】搭建 BookStack(docker)的记录
    多节点树的层序遍历
  • 原文地址:https://blog.csdn.net/qq_34874784/article/details/139587743