在SpringBoot中整合使用Netty框架

本文介绍了如何在SpringBoot应用中整合Netty框架,提供WebSocket服务。通过添加依赖、配置属性、利用ApplicationRunner启动服务及使用Spring的IOC管理Handler,确保Netty与SpringBoot生命周期同步,并展示了启动客户端、关闭服务端的日志记录。
摘要由CSDN通过智能技术生成

在SpringBoot中整合使用Netty框架

Netty是一个非常优秀的Socket框架。如果需要在SpringBoot开发的app中,提供Socket服务,那么Netty是不错的选择。

Netty与SpringBoot的整合,我想无非就是要整合几个地方

  • 让netty跟springboot生命周期保持一致,同生共死
  • 让netty能用上ioc中的Bean
  • 让netty能读取到全局的配置

整合Netty,提供WebSocket服务

这里演示一个案例,在SpringBoot中使用Netty提供一个Websocket服务。

servlet容器本身提供了websocket的实现,但这里用netty的实现 💖

添加依赖

<dependency>
	<groupId>io.netty</groupId>
	<artifactId>netty-all</artifactId>
</dependency>

是的,不用声明版本号。因为 spring-boot-dependencies 中已经声明了最新的netty依赖。

通过yaml配置基本的属性

server:
  port: 80

logging:
    level:
      root: DEBUG

management:
  endpoints: 
    web:
      exposure:
        include: "*"
    
  endpoint:
    shutdown:
      enabled: true

netty:
  websocket:
    # Websocket服务端口
    port: 1024
    # 绑定的网卡
    ip: 0.0.0.0
    # 消息帧最大体积
    max-frame-size: 10240
    # URI路径
    path: /channel

App使用了,actuator,并且开启暴露了 shutdown 端点,可以让SpringBoot App优雅的停机。
在这里通过 netty.websocket.* 配置 websocket服务相关的配置。

通过 ApplicationRunner 启动Websocket服务

import java.net.InetSocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
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.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值