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 抽象,应用层自己实现。

相关推荐
爱编程的鱼1 小时前
JSON-RPC 2.0 规范中文版——无状态轻量级远程过程调用协议
前端·网络·qt·网络协议·rpc·json
问道飞鱼1 小时前
【springboot知识】配置方式实现SpringCloudGateway相关功能
java·spring boot·后端·gateway
樽酒ﻬق1 小时前
打造美观 API 文档:Spring Boot + Swagger 实战指南
java·spring boot·后端
成都被卷死的程序员2 小时前
简单理解https与http
网络协议·http·https
源码集结号3 小时前
java智慧城管综合管理系统源码,前端框架:vue+element;后端框架:springboot;移动端:uniapp开发,技术前沿,可扩展性强
java·vue.js·spring boot·源代码·大数据分析·城管·电子办案
小马爱打代码4 小时前
Spring Boot × K8s 监控实战-集成 Prometheus 与 Grafana
spring boot·kubernetes·prometheus
秋野酱4 小时前
基于Spring Boot+Vue 网上书城管理系统设计与实现(源码+文档+部署讲解)
vue.js·spring boot·后端
编程毕设5 小时前
【含文档+PPT+源码】基于SpringBoot电脑DIY装机教程网站的设计与实现
java·spring boot·后端
暖苏5 小时前
Spring中bean的生命周期(笔记)
java·spring boot·spring·spring cloud·mvc·bean生命周期·springbean
计算机毕设定制辅导-无忧学长5 小时前
Spring Boot 集成 ActiveMQ 实现异步消息通信(一)
spring boot·activemq·java-activemq