SpringBoot 集成 Netty 使用Socket功能

SpringBoot 集成 Netty 使用Socket功能

  1. 引入Netty的jar包
<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.77.Final</version>
</dependency>
  1. 与Springboot集成
package com.netty;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
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.MessageToMessageDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * NettyBooter
 *
 * @author 七濑武【Nanase Takeshi】
 * @date 2022/06/23 10:14
 */
@Slf4j
@Component
public class NettyBooster {

    private final NettyServerHandler nettyServerHandler;

    private EventLoopGroup bossGroup;

    private EventLoopGroup workerGroup;

    public NettyBooster(NettyServerHandler nettyServerHandler) {
        this.nettyServerHandler = nettyServerHandler;
    }

    @PostConstruct
    public void start() throws InterruptedException {
    	//创建BossGroup,这里指定线程数1就够了,bossGroup 就相当于领导,workerGroup 就相当于员工,领导有一个差不多了
        bossGroup = new NioEventLoopGroup(1);
        //创建WorkerGroup
        workerGroup = new NioEventLoopGroup();
        //创建服务器端的启动对象,配置参数
        ServerBootstrap serverBootstrap =
                new ServerBootstrap()
                        .group(bossGroup, workerGroup)
                        //使用NioServerSocketChannel作为服务器的通道实现
                        .channel(NioServerSocketChannel.class)
                        //设置日志处理器
                        .handler(new LoggingHandler(LogLevel.INFO))
                        //设置线程队列得到的连接个数
                        .option(ChannelOption.SO_BACKLOG, 128)
                        //设置保持活动连接的状态
                        .childOption(ChannelOption.SO_KEEPALIVE, true)
                        //给我们的workerGroup的EventLoop对应的管道设置处理器
                        .childHandler(new ChannelInitializer<SocketChannel>() {
	                        /**
	                         * 创建一个通道测试对象(匿名对象)
	                         * 给pipeline设置处理器
	                         */
                            @Override
                            protected void initChannel(SocketChannel socketChannel) throws Exception {
                                socketChannel.pipeline().addLast(
                                		//设置一个空闲状态处理程序(心跳机制),读空闲,写空闲,读写空闲
                                        new IdleStateHandler(20, 0, 0),
                                        //一般客户端和服务端传递数据使用的JSON字符串,这里就使用String类型的编码和解码处理程序
                                        new StringDecoder()
                                        new StringEncoder(),
                                        //自定义处理程序
                                        nettyServerHandler
                                );
                            }
                        });
        serverBootstrap.bind(10000).sync();
        log.info("NettyBooster.start --> Netty 启动成功");
    }

	/**
	 * Springboot关闭时关闭Netty
	 */
    @PreDestroy
    private void destroy() throws InterruptedException {
        log.info("NettyBooster.destroy --> : 关闭 Netty...");
        if (ObjectUtil.isNotNull(bossGroup)) {
            bossGroup.shutdownGracefully().sync();
        }
        if (ObjectUtil.isNotNull(workerGroup)) {
            workerGroup.shutdownGracefully().sync();
        }
        log.info("NettyBooster.destroy --> : Netty 线程已全部关闭...");
    }

}
  1. 编写自定义处理程序
package com.netty;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 说明 1.我们自定义一个Handler,需要继承Netty规定好的某个HandlerAdapter 2.这时我们自定义一个Handler,才能称为一个Handler
 *
 * @author 七濑武【Nanase Takeshi】
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class NettyServerHandler extends SimpleChannelInboundHandler<String> {

    /**
     * 用户事件触发
     *
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        //通过判断IdleStateEvent的状态来实现自己的读空闲,写空闲,读写空闲处理逻辑
        if (evt instanceof IdleStateEvent && ((IdleStateEvent) evt).state() == IdleState.READER_IDLE) {
            //读空闲,关闭通道
            log.info("NettyWebSocketHandler.userEventTriggered --> : 读空闲,关闭通道");
            ctx.close();
        }
    }

    /**
     * 接受到了客户端发送的消息
     *
     * @param ctx the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler}
     *            belongs to
     * @param msg the message to handle
     * @throws Exception is thrown if an error occurred
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        log.info("客户端的地址:{}", ctx.channel().remoteAddress());
        log.info("客户端发送来的消息:{}", msg);
    }

    /**
     * 通道注册成功
     *
     * @param ctx
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        log.info("NettyServerHandler.handlerAdded --> 通道注册成功");
    }

    /**
     * 通道移除了
     *
     * @param ctx
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        log.info("NettyServerHandler.handlerRemoved --> 通道移除了");
    }

    /**
     * 通道开启了
     *
     * @param ctx
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("NettyServerHandler.channelActive --> 通道开启了");
    }

    /**
     * 通道关闭了
     *
     * @param ctx
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("NettyServerHandler.channelInactive --> 通道关闭了");
    }

    /**
     * 处理异常,一般是需要关闭通道
     *
     * @param ctx
     * @param cause
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中集成Netty可以通过以下步骤完成: 1. 添加Netty依赖:在你的Spring Boot项目的pom.xml文件中添加Netty的依赖。 ```xml <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.53.Final</version> </dependency> ``` 2. 创建Netty服务器:创建一个Netty服务器类,该类需要继承自`io.netty.channel.ChannelInboundHandlerAdapter`。 ```java public class NettyServer extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { // 处理接收到的消息 // ... } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // 处理异常情况 // ... } @Override public void channelActive(ChannelHandlerContext ctx) { // 在连接建立时执行一些初始化操作 // ... } @Override public void channelInactive(ChannelHandlerContext ctx) { // 在连接关闭时执行一些清理操作 // ... } } ``` 3. 配置Netty服务器:在Spring Boot的配置文件中配置Netty服务器的相关参数,例如端口号、线程池等。 ```properties # application.properties netty.server.port=8080 netty.server.workerThreads=10 ``` 4. 启动Netty服务器:在Spring Boot的启动类中初始化并启动Netty服务器。 ```java @SpringBootApplication public class YourApplication { @Autowired private NettyServer nettyServer; public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } @PostConstruct public void startNettyServer() { // 获取Netty服务器配置参数 int port = Integer.parseInt(env.getProperty("netty.server.port")); int workerThreads = Integer.parseInt(env.getProperty("netty.server.workerThreads")); // 创建EventLoopGroup和ServerBootstrap EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(workerThreads); ServerBootstrap serverBootstrap = new ServerBootstrap(); try { // 设置服务器参数 serverBootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); // 添加自定义的Handler pipeline.addLast(nettyServer); } }); // 启动Netty服务器 ChannelFuture channelFuture = serverBootstrap.bind(port).sync(); channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { // 处理启动异常 } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } } ``` 这样,你就成功地在Spring Boot项目中集成Netty。你可以在`NettyServer`类中编写自定义的业务逻辑来处理接收到的消息,并在`channelRead`方法中进行处理。同时,你也可以根据需要在`exceptionCaught`、`channelActive`和`channelInactive`方法中处理异常、连接建立和连接关闭等事件。记得在服务器关闭时进行资源的释放和清理操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值