Netty Websocket SpringBoot Starter

netty websocket starter

Quick Start

Demo 项目

添加依赖

<!--添加源-->
<repository>
    <id>github</id>
    <url>https://maven.pkg.github.com</url>
    <snapshots>
        <enabled>true</enabled>
    </snapshots>
</repository>

<dependency>
    <groupId>com.github.kuangcp</groupId>
    <artifactId>netty-ws-spring-boot-starter</artifactId>
    <version>1.0.5-RELEASE</version>
</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 抽象,应用层自己实现。

Spring Boot中,你可以使用Embedded Tomcat作为Web服务器,并且使用Spring WebSocket来实现WebSocket通信。在Netty中,你可以使用Netty WebSocket来实现WebSocket通信。 要将它们监听同一个端口号,你可以使用Spring Boot的嵌入式Netty服务器来替换Embedded Tomcat。这样,你就可以使用Netty WebSocket来实现WebSocket通信,并且监听相同的端口号。 以下是示例代码: 首先,在Spring Boot中添加以下依赖项: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.22.Final</version> </dependency> ``` 然后,在你的Spring Boot应用程序中,创建一个新的WebSocket配置类,并在其中注册Netty WebSocket: ```java @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(new NettyWebSocketHandler(), "/websocket") .setAllowedOrigins("*") .withSockJS(); } } ``` 在上面的代码中,我们将Netty WebSocket注册到路径“/websocket”上,并启用SockJS支持。此外,我们还设置了跨域请求的允许来源。 最后,在你的主应用程序类中,添加以下代码来配置嵌入式Netty服务器: ```java @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } @Bean public NettyServerCustomizer nettyServerCustomizer() { return server -> { server.httpPort(8080); server.tcpConfiguration(tcp -> tcp.bootstrap(serverBootstrap -> { serverBootstrap.localAddress(new InetSocketAddress(8080)); }) ); }; } } ``` 在上面的代码中,我们创建了一个NettyServerCustomizer Bean,并使用它来配置嵌入式Netty服务器的监听端口。我们还配置了TCP参数,以便Netty WebSocket可以在相同的端口上进行通信。 现在,你可以使用Spring BootNetty WebSocket来监听同一个端口号了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值