【二】Netty 搭建简单的http服务

文章介绍了Netty是一个高性能的异步事件驱动的网络应用框架,用于快速开发服务器和客户端。文中通过代码展示了如何创建Netty服务器端(NettyServer)和设置编码解码器,以及自定义的MyClientHandler来处理业务逻辑。此外,还提到了使用Postman进行测试的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Netty 简介

首先netty是什么,官网是这样定义的。
Netty is an asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients.
Netty是一个异步事件驱动的网络应用程序框架用于快速开发可维护的高性能协议服务器和客户端。
Netty是目前所有NIO框架中性能最好的框架,Java本身提供的有NIO工具,但是在实际操作过程中,复杂繁琐,且对编程人员要求比较高,多线程环境下不容易定位问题,且容易出现问题,所以netty的出现极大的简化了这种操作,且性能稳定高效,其架构设计也非常优秀,值得深入学习总结。
netty官网:https://netty.io/

代码展示

netty 依赖

        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.36.Final</version>
        </dependency>

NettyServer netty 服务端启动类

public static void main(String[] args) {
        new NettyServer().bing(8082);
    }

    private void bing(int port) {
        //配置服务端NIO线程组
        EventLoopGroup parentGroup = new NioEventLoopGroup();
        EventLoopGroup childGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(parentGroup, childGroup)
                    .channel(NioServerSocketChannel.class)//非阻塞模式
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new MyChannelInitializer());
            ChannelFuture future = bootstrap.bind(port).sync();
            System.out.println("hello ,server is start up");
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            parentGroup.shutdownGracefully();
            childGroup.shutdownGracefully();
        }
    }

MyChannelInitializer 设置编码解码器,并添加自己的业务方法

public class MyChannelInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        //数据解码操作
        socketChannel.pipeline().addLast(new HttpResponseEncoder());
        //数据编码操作
        socketChannel.pipeline().addLast(new HttpRequestDecoder());
        //在管道中添加自己的业务方法
        socketChannel.pipeline().addLast(new MyClientHandler());
    }
}

MyClientHandler 实现自己的业务方法。主要方法 是读取到数据后处理

public class MyClientHandler extends ChannelInboundHandlerAdapter {

    public void channelRead(ChannelHandlerContext context,Object msg){
        if (msg instanceof HttpRequest){
            DefaultHttpRequest request=(DefaultHttpRequest)msg;
            System.out.println("URI: "+request.uri());
            System.out.println(msg);
        }

        if (msg instanceof HttpContent){
            LastHttpContent content=(LastHttpContent) msg;
            ByteBuf byteBuf=content.content();
            if (!(byteBuf instanceof EmptyByteBuf)){
                //接收msg消息
                byte[]msgByte=new byte[byteBuf.readableBytes()];
                byteBuf.readBytes(msgByte);
                System.out.println(new String(msgByte,Charset.forName("UTF-8")));
            }
        }

        String sendMsg = "hello ni hao,这是netty -respondse 返回的信息.";

        FullHttpResponse response=new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                Unpooled.wrappedBuffer(sendMsg.getBytes(Charset.forName("UTF-8")))
        );
        //返回值类型
        response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=UTF-8");
        //返回值的大小
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH,response.content().readableBytes());
        //返回值 保持长连接
        response.headers().set(HttpHeaderNames.CONNECTION,HttpHeaderValues.KEEP_ALIVE);

        context.write(response);
        context.flush();
    }

    public void channelReadComplete(ChannelHandlerContext context){
        context.flush();
    }

    public void exceptionCaught(ChannelHandlerContext context,Throwable c){
        context.close();
        c.printStackTrace();
    }

效果展示

服务端打印截图

在这里插入图片描述

采用Postman 测试 截图

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

echoecho_tongtong

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值