Netty Websocket SpringBoot Starter

netty websocket starter

Quick Start

Demo 项目

添加依赖

xml 复制代码
<!--添加源-->
<repository>
    <id>github</id>
    <url>https://maven.pkg.github.com</url>
    <snapshots>
        <enabled>true</enabled>
    </snapshots>
</repository>
xml 复制代码
<dependency>
    <groupId>com.github.kuangcp</groupId>
    <artifactId>netty-ws-spring-boot-starter</artifactId>
    <version>1.0.5-RELEASE</version>
</dependency>

基础配置

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

自定义连接处理类

java 复制代码
@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 抽象,应用层自己实现。

相关推荐
利刃大大36 分钟前
【SpringBoot】validation参数校验 && JWT鉴权实现 && 加密/加盐
java·spring boot·jwt·加密
郑泰科技1 小时前
SpringBoot项目实践:之前war部署到服务器好用,重新打包部署到服务器报404
服务器·spring boot·后端
计算机毕设VX:Fegn08952 小时前
计算机毕业设计|基于springboot + vue个人博客系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·课程设计
独自破碎E2 小时前
Spring Boot 3.x和2.x版本相比有哪些区别与改进?
java·spring boot·后端
幽络源小助理2 小时前
SpringBoot+Vue美食网站系统源码 | Java餐饮项目免费下载 – 幽络源
java·vue.js·spring boot
Coder_Boy_3 小时前
基于SpringAI企业级智能教学考试平台考试模块全业务闭环方案
java·人工智能·spring boot·aiops
爱学java的ptt3 小时前
TCP详解
网络·网络协议·tcp/ip
Skrrapper4 小时前
TCPTP协议是什么?以及Socket使用指南
网络·c++·websocket·计算机网络
阿拉伯柠檬4 小时前
传输层协议TCP(一)
linux·网络·网络协议·tcp/ip·面试
Coder_Boy_4 小时前
基于SpringAI的智能AIOps项目:部署相关容器化部署管理技术
人工智能·spring boot·k8s·运维开发