SpringBoot整合Netty处理WebSocket(支持url参数)

SpringBoot整合Netty处理WebSocket(支持url参数)

这篇文章是参考SpringBoot2+Netty+WebSocket(netty实现websocket,支持URL参数)这个博客文章进行编写完善的,有兴趣可以多多关注原博主。

后面经过自己的研究,看了Netty相关的WebSocket处理代码,重新写了一篇文章使用Netty处理WebSocket请求,可以更加优雅的处理WebSocket请求。


添加MAVEN依赖

<!-- Netty -->
<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.45.Final</version>
</dependency>

WebSocketProperties配置类

为了能在SpringBoot项目中灵活配置相关的值,这里使用了配置类,并使用了默认值。

@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "chat.websocket")
public class WebSocketProperties {
   
   

  private Integer port = 8081; // 监听端口
  private String path = "/ws"; // 请求路径
  private Integer boss = 2; // bossGroup线程数
  private Integer work = 2; // workGroup线程数

}

WebSocket连接通道池

用来管理已经连接的客户端通道,方便数据传输交互。

@Slf4j
@Component
public class NioWebSocketChannelPool {
   
   

  private final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

  /**
   * 新增一个客户端通道
   *
   * @param channel
   */
  public void addChannel(Channel channel) {
   
   
    channels.add(channel);
  }

  /**
   * 移除一个客户端连接通道
   *
   * @param channel
   */
  public void removeChannel(Channel channel) {
   
   
    channels.remove(channel);
  }

}

请求路径工具类

public class RequestUriUtils {
   
   

  /**
   * 将路径参数转换成Map对象,如果路径参数出现重复参数名,将以最后的参数值为准
   * @param uri 传入的携带参数的路径
   * @return
   */
  public static Map<String, String> getParams(String uri) {
   
   
    Map<String, String> params = new HashMap<>(10);

    int idx = uri.indexOf("?");
    if (idx != -1) {
   
   
      String[] paramsArr = uri.substring(idx + 1).split("&");

      
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值