• Netty Websocket SpringBoot Starter


    netty websocket starter

    Quick Start

    Demo 项目

    添加依赖

    
    <repository>
        <id>githubid>
        <url>https://maven.pkg.github.comurl>
        <snapshots>
            <enabled>trueenabled>
        snapshots>
    repository>
    
    
    <dependency>
        <groupId>com.github.kuangcpgroupId>
        <artifactId>netty-ws-spring-boot-starterartifactId>
        <version>1.0.5-RELEASEversion>
    dependency>
    

    基础配置

    netty-ws:
      port: 5455
      max-content-length: 4096
      max-frame-size: 65536
      reader-idle-sec: 60
      reader-idle-threshold: 2
      connect-auth: true
    

    自定义连接处理类

    
    @Component
    @ChannelHandler.Sharable
    public class DemoHandler extends AbstractBizHandler {
    
        public DemoHandler(CacheDao cacheDao, UserDao userDao, WsServerConfig config) {
            super(cacheDao, userDao, config);
            this.schedulerPollQueueMsg(Executors.newScheduledThreadPool(1));
        }
    
        @Override
        public void connectSuccess(Long userId) {
            log.info("connected {}", userId);
        }
    
        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            String id = WsSocketUtil.id(ctx);
            Long userId = channelUserMap.get(id);
            log.info("disconnect {}", userId);
            super.channelInactive(ctx);
        }
    
        @Override
        protected void handSharkHttpRequest(ChannelHandlerContext ctx, FullHttpRequest request) {
            super.handSharkHttpRequest(ctx, request);
        }
    }
    

    实现存储扩展 com.github.kuangcp.websocket.store.CacheDao
    实现认证扩展 com.github.kuangcp.websocket.store.UserDao

    • 然后启动项目, 验证websocket通信。 可使用 Js 测试客户端 测试
      • 连接地址 ws://127.0.0.1:5455/ws?uid={uid}&token={token}
      • 注意认证的实现方式为HTTP握手时,将Token作为url参数或者作为Header,参数名都是token

    设计思路

    Netty作为通信基础,每个用户连接时通过前置的Nginx等SLB层负载均衡到WS集群。

    1. 用户和主机ip关系绑定到Redis map结构中
    2. 每个主机ip绑定一个Redis的list队列,存放了其他节点写入的消息数据,解决应用层向用户推送消息时,用户连接随机分散的问题。

    注意:Redis可替换成任意中心存储, 已由 CacheDao 抽象,应用层自己实现。

  • 相关阅读:
    USBCAN在江淮新能源汽车诊断工具的应用案例
    Linux中的nmap命令
    在线实时监测离子风机的功能
    ORA-00904: “EQUIPMENTS0_“.“CREATETIME“: 标识符无效
    TensorRT来加速YOLO v5推理与检测
    腾讯云服务器完整建站过程(新手搭建网站教程)
    软件工程师都应该知道的10个定律
    入股合作协议要不要写章程
    神经网络处理器设计原理,神经网络控制系统设计
    奥地利博士联培申请签证经验(奥地利签证)
  • 原文地址:https://blog.csdn.net/kcp606/article/details/140391661