netty编程之结合springboot一起使用

news2024/9/20 1:03:16

写在前面

源码 。
本文看下netty结合springboot如何使用。

1:netty server部分

server类(不要main,后续通过springboot来启动咯!)

package com.dahuyou.netty.springboot.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

@Component("nettyServer")
public class NettyServer {

    private Logger logger = LoggerFactory.getLogger(NettyServer.class);

    //配置服务端NIO线程组
    private final EventLoopGroup parentGroup = new NioEventLoopGroup(); //NioEventLoopGroup extends MultithreadEventLoopGroup Math.max(1, SystemPropertyUtil.getInt("io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));
    private final EventLoopGroup childGroup = new NioEventLoopGroup();
    private Channel channel;

    public ChannelFuture bing(InetSocketAddress address) {
        ChannelFuture channelFuture = null;
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(parentGroup, childGroup)
                    .channel(NioServerSocketChannel.class)    //非阻塞模式
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childHandler(new MyChannelInitializer());

            channelFuture = b.bind(address).syncUninterruptibly();
            channel = channelFuture.channel();
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            if (null != channelFuture && channelFuture.isSuccess()) {
                logger.info("netty server start done. {大忽悠有限没责任公司}");
            } else {
                logger.error("netty server start error. {大忽悠有限没责任公司}");
            }
        }
        return channelFuture;
    }

    public void destroy() {
        if (null == channel) return;
        channel.close();
        parentGroup.shutdownGracefully();
        childGroup.shutdownGracefully();
    }

    public Channel getChannel() {
        return channel;
    }

}

MyChannelInitializer:

package com.dahuyou.netty.springboot.server;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.Charset;

public class MyChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel channel) {
        // 解码转String,注意调整自己的编码格式GBK、UTF-8
        channel.pipeline().addLast(new StringDecoder(Charset.forName("GBK")));
        // 解码转String,注意调整自己的编码格式GBK、UTF-8
        channel.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));
        // 在管道中添加我们自己的接收数据实现方法
        channel.pipeline().addLast(new MyServerHandler());
    }

}

MyServerHandler:

package com.dahuyou.netty.springboot.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MyServerHandler extends ChannelInboundHandlerAdapter {

    private Logger logger = LoggerFactory.getLogger(MyServerHandler.class);

    /**
     * 当客户端主动链接服务端的链接后,这个通道就是活跃的了。也就是客户端与服务端建立了通信通道并且可以传输数据
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketChannel channel = (SocketChannel) ctx.channel();
        logger.info("链接报告开始");
        logger.info("链接报告信息:有一客户端链接到本服务端");
        logger.info("链接报告IP:{}", channel.localAddress().getHostString());
        logger.info("链接报告Port:{}", channel.localAddress().getPort());
        logger.info("链接报告完毕");
        //通知客户端链接建立成功
        String str = "通知客户端链接建立成功" + " " + new Date() + " " + channel.localAddress().getHostString() + "\r\n";
        ctx.writeAndFlush(str);
    }

    /**
     * 当客户端主动断开服务端的链接后,这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("客户端断开链接{}", ctx.channel().localAddress().toString());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //接收msg消息{与上一章节相比,此处已经不需要自己进行解码}
        logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " 服务端接收到消息:" + msg);
        //通知客户端链消息发送成功
        String str = "服务端收到:" + new Date() + " " + msg + "\r\n";
        ctx.writeAndFlush(str);
    }

    /**
     * 抓住异常,当发生异常的时候,可以做一些相应的处理,比如打印日志、关闭链接
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        logger.info("异常信息:\r\n" + cause.getMessage());
    }

}

2:springboot部分

springboot app:

package com.dahuyou.netty.springboot.web;

import com.dahuyou.netty.springboot.server.NettyServer;
import io.netty.channel.ChannelFuture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import java.net.InetSocketAddress;

// CommandLineRunner接口方法会在springboot启动完毕之后调用org.springframework.boot.SpringApplication.callRunners
@SpringBootApplication
@ComponentScan("com.dahuyou.netty.springboot")
public class NettyApplication implements CommandLineRunner {

    @Value("${netty.host}")
    private String host;
    @Value("${netty.port}")
    private int port;
    @Autowired
    private NettyServer nettyServer;

    public static void main(String[] args) {
        SpringApplication.run(NettyApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        InetSocketAddress address = new InetSocketAddress(host, port);
        ChannelFuture channelFuture = nettyServer.bing(address);
        // 在jvm钩子中停止netty(jvm正常退出时回调用)
        Runtime.getRuntime().addShutdownHook(new Thread(() -> nettyServer.destroy()));
        channelFuture.channel().closeFuture().syncUninterruptibly();
    }

}

这里通过CommandLineRunner接口来启动netty程序,另外为了获取netty的相关状态还定义了一个controller:

package com.dahuyou.netty.springboot.web;

import com.dahuyou.netty.springboot.server.NettyServer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;

@RestController
@RequestMapping(value = "/nettyserver", method = RequestMethod.GET)
public class NettyController {

    @Resource
    private NettyServer nettyServer;

    @RequestMapping("/localAddress")
    public String localAddress() {
        return "nettyServer localAddress " + nettyServer.getChannel().localAddress();
    }

    @RequestMapping("/isOpen")
    public String isOpen() {
        return "nettyServer isOpen: " + nettyServer.getChannel().isOpen();
    }

}

3:test case部分

代码:

package com.dahuyou.netty.springboot.test;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ApiTest {

    public static void main(String[] args) {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.AUTO_READ, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel channel) throws Exception {
                    // 基于换行符号
                    channel.pipeline().addLast(new LineBasedFrameDecoder(1024));
                    // 解码转String,注意调整自己的编码格式GBK、UTF-8
                    channel.pipeline().addLast(new StringDecoder(Charset.forName("GBK")));
                    // 解码转String,注意调整自己的编码格式GBK、UTF-8
                    channel.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));
                    // 在管道中添加我们自己的接收数据实现方法
                    channel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            //接收msg消息{与上一章节相比,此处已经不需要自己进行解码}
                            System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " 客户端接收到消息:" + msg);
                        }
                    });
                }
            });
            ChannelFuture f = b.connect("127.0.0.1", 7397).sync();
            System.out.println("netty client start done. {大忽悠有限没责任公司}");

            //向服务端发送信息
            f.channel().writeAndFlush("你好,SpringBoot启动的netty服务端,这里是大忽悠有限没责任公司,你可不要被我忽悠了哦!!!”\r\n");
            f.channel().writeAndFlush("你好,SpringBoot启动的netty服务端,这里是大忽悠有限没责任公司,你可不要被我忽悠了哦!!!”\r\n");
            f.channel().writeAndFlush("你好,SpringBoot启动的netty服务端,这里是大忽悠有限没责任公司,你可不要被我忽悠了哦!!!”\r\n");
            f.channel().writeAndFlush("你好,SpringBoot启动的netty服务端,这里是大忽悠有限没责任公司,你可不要被我忽悠了哦!!!”\r\n");
            f.channel().writeAndFlush("你好,SpringBoot启动的netty服务端,这里是大忽悠有限没责任公司,你可不要被我忽悠了哦!!!”\r\n");

            f.channel().closeFuture().syncUninterruptibly();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

}

运行client输出:
在这里插入图片描述
服务端输出:
在这里插入图片描述
等等,好像有问题,在client明明是write了几句话的,就这样的:
在这里插入图片描述
怎么当作一句话来接收了呢?其实,这就是发生了粘包了,知道了问题所在,解决也就简单了,增加一个相关的解码器即可,因为在每句话的结尾我们都增加了换行符,所以这里我们直接使用netty提供的基于换行符的解码器LineBasedFrameDecoder就行,即修改MyChannelInitializer类即可:
在这里插入图片描述
接着重新启动测试,server输出就正常了:
在这里插入图片描述

写在后面

参考文章列表

springboot之项目搭建并say hi 。

扩展

在以上的client测试类中,我们在write数据的时候,每句话的结尾都增加了换行符\r\n,这显然是一个重复的工作了。是否可以将这个工作只做一遍呢,可以的,使用netty提供的outboundhandler就可以很轻松的来解决这个问题了,首先我们需要先来定义一个ChannelOutboundHandler:

package com.dahuyou.netty.springboot.test;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;

/**
 * 同意增加换行符的outbound handler
 */
public class MyAddNewLineOutMsgHandler extends ChannelOutboundHandlerAdapter {

    @Override // 调用ctx的writeAndFlush方法时会被该方法拦截执行
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        System.out.println("MyAddNewLineOutMsgHandler--统一增加换行符咯!!!");
        msg += "\r\n";
        super.write(ctx, msg, promise);
    }

}

接着修改client测试类,将所有的换行符删掉:
在这里插入图片描述
还需要将统一增加换行符的handler添加到channel中:
在这里插入图片描述
再重新启动clienit测试:
在这里插入图片描述
效果还是一样的,但是少做了很多重复的工作,是吧???

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2081026.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

设置视图的宽高

AndroidManifest.xml <?xml version"1.0" encoding"utf-8"?> <manifest xmlns:android"http://schemas.android.com/apk/res/android"><applicationandroid:allowBackup"true"android:icon"mipmap/ic_launcher…

JS 实现栈和队列

JS实现栈和队列 栈是先进后出 function Stack() {this.arr [];// push方法是把数据放入栈中this.push function (value) {this.arr.push(value);}// pop 是取数组的最后一个数据&#xff0c;从而实现先进后出this.pop function () {this.arr.pop();} }var stack new Stac…

Spring如何既返回实体同时下载文件

业务背景&#xff1a;下载文件的接口需要返回文件信息或者密码等信息&#xff0c;这时候就需要接口返回文件及相关实体信息&#xff1b; 在Spring中&#xff0c;如果你需要在同一个请求中既下载文件也返回一个实体信息&#xff0c;你需要特别注意HTTP协议本身并不直接支持这种操…

Matplotlib 详解

1. 基本概念和历史背景 Matplotlib核心概念详解 Matplotlib 是 Python 中最流行的数据可视化库之一&#xff0c;它提供了一系列强大且灵活的工具&#xff0c;用于创建各种类型的图表和图形。无论你是数据科学家、工程师还是研究人员&#xff0c;理解 Matplotlib 的核心概念都…

机加工行业MES系统的特点及优势

一、机加工行业MES系统的特点 机加工行业MES系统作为面向制造企业车间执行层的生产信息化管理系统&#xff0c;具有以下几个显著特点&#xff1a; 高度定制化&#xff1a;由于不同机加工企业的生产流程和业务需求千差万别&#xff0c;MES系统的搭建需要高度定制化&#xff0c;…

93.WEB渗透测试-信息收集-Google语法(7)

免责声明&#xff1a;内容仅供学习参考&#xff0c;请合法利用知识&#xff0c;禁止进行违法犯罪活动&#xff01; 内容参考于&#xff1a; 易锦网校会员专享课 上一个内容&#xff1a;92.WEB渗透测试-信息收集-Google语法&#xff08;6&#xff09; • intext • intext 的作…

Java 使用 POI 导出Excel,实现横向和纵向的合并单元格

在使用Apache POI的库生成Excel的时候&#xff0c;有时候需要在导出的文件中合并单元格&#xff0c;比如对excel文件形成统一的标题栏&#xff0c;改如何写这个代码呢&#xff1f;下面是一个示例代码&#xff0c;演示如何横向和纵向合并单元格。 代码 import org.apache.poi.s…

Java新手零基础教程!(●‘◡‘●)运算符类型讲解

Java 算术运算符 Java教程 - Java算术运算符 在数学表达式中使用算术运算符。 所有算术运算符 下表列出了算术运算符: 运算符结果加法-减法*乘法/除法%余数自增加法分配-减法分配*乘法分配/除法分配%模量分配--自减 算术运算符的操作数必须是数字类型。您不能在 boolean 类…

55.基于IIC协议的EEPROM驱动控制(2)

升腾A7pro的EEPROM芯片为24C64芯片&#xff0c;器件地址为1010_011。 &#xff08;1&#xff09;Visio整体设计视图&#xff08;IIC_SCL为250KHz&#xff0c;IIC_CLK为1MHz&#xff0c;addr_num为1&#xff0c;地址字节数为2字节&#xff0c;addr_num为0&#xff0c;地址字节数…

Windows Docker 部署 SolrCloud

一、简介 Solr 集群是一个基于 Lucene 的高性能全文搜索服务器集群&#xff0c;它通过集成 ZooKeeper 来实现分布式索引和搜索功能。Solr 集群具备以下特点&#xff1a; 分布式索引与搜索&#xff1a;Solr 能够将大索引分成多个小索引&#xff0c;分布在多个节点上&#xff0…

网络安全实训六(靶机实例DC-3)

1 信息收集 1.1 获取靶机IP 1.2 扫描靶机网站的目录 1.3 扫描端口和服务器信息 1.4 进入网站 1.5 在msf中给搜索joomla扫描器 1.6 设置参数查看joomla版本信息 1.7 按照版本号搜索漏洞 1.8 查看漏洞使用 2 渗透 2.1 查看是否存在SQL注入 2.2 获取到数据库信息 2.3 爆破列表 2…

Datawhale AI夏令营第五期学习!

学习日志 日期&#xff1a; 2024年8月27日 今日学习内容&#xff1a; 今天&#xff0c;我学习了如何在深度学习任务中使用卷积神经网络&#xff08;CNN&#xff09;进行图像分类的基本流程&#xff0c;并成功地在JupyterLab中运行了一个完整的项目。以下是我今天的学习和操作…

【html+css 绚丽Loading】000021 万象轮回珠

前言&#xff1a;哈喽&#xff0c;大家好&#xff0c;今天给大家分享htmlcss 绚丽Loading&#xff01;并提供具体代码帮助大家深入理解&#xff0c;彻底掌握&#xff01;创作不易&#xff0c;如果能帮助到大家或者给大家一些灵感和启发&#xff0c;欢迎收藏关注哦 &#x1f495…

使用C#进行屏幕截图(screenCapturer)

1.具体是应用了Nuget包 ScreenCapturer 2.编写相关核心代码&#xff0c;实现截取电脑部分区域图片 ScreenCapturer.ScreenCapturerTool screenCapturer new(); if (screenCapturer.ShowDialog() DialogResult.OK) {Bitmap bmp (Bitmap)screenCapturer.Image;pictureBox1.Ba…

【不合理的递归区间】快排递归引发区间错误,除以0未定义

问题描述 力扣语法报错&#xff1a;含义是有可能会除以0&#xff0c;该行为未定义&#xff0c;但问题是我这里压根就没用到除法。 #include<stdlib.h> #include<time.h>class Solution { public:vector<int> sortArray(vector<int>& nums) {sra…

【JavaWeb】定时任务和批量插入数据库数据

定时任务 需要在项目启动类添加注解开启支持定时任务&#xff1a; 以下示例是定时任务插入数据的操作&#xff1a; package com.yupi.yupao.once.importuser;import com.yupi.yupao.mapper.UserMapper; import com.yupi.yupao.model.domain.User; import org.springframework…

软件测试——论坛系统测试用例

功能测试 其他测试 测试用例 用例编号 用例描述 优先级 预置条件 操作步骤 测试数据 预期结果 测试结果Bug ID软件版本测试员SNS_User_Register_001注册成功使用合法的数据成功注册一个新账号P11、已打开注册页面 2、准备一个未注册用户信息1、输入用户昵称 2、输入用户名 3、…

Unity(2022.3.41LTS) - 摄像机

目录 一、基本概念 二、重要属性 三、摄像机模式 四、脚本控制 五、渲染设置 六. 组件详细介绍 一、基本概念 作用&#xff1a;摄像机决定了玩家在游戏中能够看到的内容。它就像是玩家的眼睛&#xff0c;从特定的位置和角度观察场景&#xff0c;并将场景中的物体渲染到屏…

北冥坞“学件”系统

简介 学件由周志华教授在 2016 年提出 [1, 2]。在学件范式下&#xff0c;世界各地的开发者可分享模型至学件基座系统&#xff0c;系统通过有效查搜和复用学件帮助用户高效解决机器学习任务&#xff0c;而无需从零开始构建机器学习模型。 北冥坞是学件的第一个系统性开源实现&…

客户端字符集小于数据库字符集导致乱码

一、现象 使用plsql或者sqlplus客户端 查询某个表的数据库均显示乱码&#xff0c;如下图所示&#xff1a; 二、原因分析 1、查看数据库的字符集 2、查看客户端的字符集 3、比较 数据库的字符集AL16UTF18&#xff08;服务端&#xff09;是大于en_US.UTF-8&#xff08;客户端&…