Netty001

Netty是一个提供异步事件驱动的网络应用开发框架(NIO框架)。
首先沾上我们的Manen依赖↓

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

如何建立服务器?如下↓

    public void bind(int port){
        //实例化两个线程组
        //负责接受客户端的连接 因为它只负责接受客户端连接所以一般指定为1就行
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        //负责读写以及其他操作
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        //服务器的引导类,负责配置服务器的各种参数
        ServerBootstrap serverBootstrap = new ServerBootstrap();


        serverBootstrap.group(bossGroup,workGroup)//绑定两个线程组
                .channel(NioServerSocketChannel.class)//设置NIO的模式
                .childHandler(new MyInitializer()).bind(port); //子处理器
    }

子处理器干代码↓

//channel注册后,会执行里面的相应的初始化方法
public class MyInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        // 通过SocketChannel去获得对应的管道
        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline.addLast("MyDecoder",new MyDecoder());//自定义解码器 入栈
        pipeline.addLast(new StringEncoder());//框架自带编码器 出栈
        pipeline.addLast(new MyHandle2());//添加自定义处理器(读取客户端发送的数据,在此之前经过了前面解码器的解码)项目业务一般写在此处
    }
}

自定义解码器↓

public class MyDecoder extends ByteToMessageDecoder {
//    private final Queue<String> values = new LinkedList<>();
//    private final ByteBuf tmpByteBuf = Unpooled.buffer(1024);

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf inBuf, List<Object> list) throws Exception {
        int i = inBuf.readableBytes();
        byte[] array = new byte[i];
        inBuf.readBytes(array,0,i);
        String s1 = new String(array, Charset.forName("UTF-8"));
        list.add(s1);
    }
}

自定义处理器读取客户端数据

public class MyHandle2 extends  SimpleChannelInboundHandler<String>  {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msgStr) throws Exception {

        ctx.writeAndFlush(msgStr+" world!");
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel注册时调用");
        super.channelRegistered(ctx);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel移除时调用");
        super.channelUnregistered(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel活跃时调用");
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel不活跃时调用");
        super.channelInactive(ctx);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channeld读取完毕时调用");
        super.channelReadComplete(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println("用户事件触发时调用");
        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel可写更改时调用");
        super.channelWritabilityChanged(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("捕获到异常时调用");
        super.exceptionCaught(ctx, cause);
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("自定义处理器类添加时调用");
        super.handlerAdded(ctx);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("自定义处理器类移除调用");
        super.handlerRemoved(ctx);
    }
}

客户端如何建立?↓

       public void bind(String ip,int port){
        try {
            Bootstrap bootstrap =  new Bootstrap();
            bootstrap .group(new NioEventLoopGroup())
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ch.pipeline().addLast(new StringEncoder());//编码器
                            ch.pipeline().addLast(new MyDecoder());//解码器
                            ch.pipeline().addLast(new MyHandle());//自定义处理器 一般项目的业务写在这里
                        }
                    });
            //连接服务端
            ChannelFuture future = bootstrap.connect(ip, port).sync();
            //对通道关闭进行监听
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

总结:客户端和服务端的开发过程大致差不多,区别如下
1-两者的引导类不同服务端的引导类是ServerBootstrap,而客户端的引导类是Bootstrap
2-服务端的一般情况下最好使用两个EventLoopGroup,而客户端一个就行,因为客户端并不需要独立的线程去监听客户端连接,也不需要通过一个单独的客户端线程去连接服务端。

### 使用 Netty 和 Kafka 实现物联网通信 #### 1. 物联网通信的需求分析 在物联网场景下,设备数量庞大且分布广泛,数据传输需求多样化。Netty 提供了一种高效的异步事件驱动框架用于网络编程[^4],而 Kafka 则作为消息中间件负责高吞吐量的数据传递和存储[^1]。 #### 2. Netty 的角色定位 Netty 被用来构建轻量级的 TCP 或 WebSocket 服务端程序,能够高效处理大量并发连接请求。对于 IoT 设备而言,它们可能通过 MQTT、CoAP 等协议与云端交互。在这种情况下,可以利用 Netty 来实现这些协议的支持并完成设备接入管理功能[^3]。 以下是基于 Spring Boot 和 Netty 构建的一个简单的初始化代码示例: ```java import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; public class NettyIoTServer { private int port; public NettyIoTServer(int port){ this.port = port; } public void run() throws Exception{ EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try{ ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class); ChannelFuture f = b.bind(port).sync(); // 绑定端口等待直到绑定成功 System.out.println("Netty server started at "+port+"..."); f.channel().closeFuture().sync(); // 阻塞当前线程直至通道关闭 }finally{ workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } public static void main(String[] args)throws Exception{ new NettyIoTServer(8080).run(); } } ``` 此部分主要展示了如何启动一个基本的服务端监听器。 #### 3. Kafka 的作用说明 当接收到由 Netty 处理后的传感器读数或其他形式的信息之后,就可以把这些信息发送到 Kafka 主题上以便进一步加工或长期保存。由于 Kafka 支持水平扩展以及快速写入操作的特点使其成为理想的选择之一[^2]。 下面给出一段向指定主题推送记录的例子: ```java Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); Producer<String, String> producer = new KafkaProducer<>(props); producer.send(new ProducerRecord<>("iot_data_topic", "device_id_001", "{\"temperature\": \"72F\"}")); producer.close(); ``` 上述片段演示了怎样配置生产者并将 JSON 格式的温度测量值传送到名为 `iot_data_topic` 的 Kafka topic 中去。 #### 4. 整体架构概述 整个系统的运作流程大致如下: - **前端**: 各类智能终端(如温湿度计)经由自定义协议或者标准化协议(MQTT/HTTP)上传其状态更新至后端; - **中间层**(即本项目): 借助于高性能 I/O 库——Netty 接收来自不同源的数据包;随后依据业务逻辑解析有效载荷内容再转发给下游组件; - **后台数据库&计算引擎**: 数据最终会被存放到像 HDFS 这样的分布式文件系统里头或者是导入 Elasticsearch 当作全文检索索引基础等等;与此同时还可以触发一些即时告警机制通知相关人员采取行动。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值