• 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`,看到返回的响应。 

  • 相关阅读:
    PDF文件太大怎么办?三招教会你PDF文件压缩
    小常识:琢磨一下淘宝上手机换套餐的生意
    cka/ckad应试指南 从docker到kubernetes完全攻略
    力扣-232.用栈实现队列
    【狂神】MyBatisPlus笔记
    MViT:性能杠杠的多尺度ViT | ICCV 2021
    Excel导入导出,增删改查的实现
    5.14.1.2 Get Log Page – Smart Log
    elasticsearch 8.5.3问题记录
    Java程序设计——事务管理(JDBC编程)
  • 原文地址:https://blog.csdn.net/qq_34874784/article/details/139587743