0


Spring Cloud Gateway接入WebSocket:实现实时通信

在现代的微服务架构中,实时通信变得越来越重要。Spring Cloud Gateway作为Spring Cloud生态中的API网关,提供了动态路由、监控、弹性、安全等功能。本文将介绍如何通过Spring Cloud Gateway接入WebSocket,实现服务之间的实时通信。

为什么需要WebSocket

WebSocket提供了全双工通信机制,允许服务器主动向客户端发送消息,这在需要实时数据推送的场景(如聊天应用、实时通知等)中非常有用。

Spring Cloud Gateway配置

首先,我们需要在Spring Cloud Gateway中配置WebSocket路由。以下是配置示例:

spring:cloud:gateway:discovery:locator:lowerCaseServiceId:trueenabled:trueroutes:-id: ruoyi-system2
          uri: lb:ws://ruoyi-system
          predicates:- Path=/admin/websocket/**filters:- StripPrefix=1

这里配置了一个WebSocket路由,将

/admin/websocket/**

路径的请求转发到

ruoyi-system

服务。

安全配置

为了确保WebSocket通信的安全,我们还需要进行一些安全配置:

security:xss:enabled:trueexcludeUrls:- /system/notice
  # 不校验白名单ignore:whites:- /auth/logout
      - /auth/login
      - /auth/register
      - /*/v2/api-docs- /csrf
      - /admin/websocket/**

依赖配置

admin

模块中添加WebSocket依赖:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>

WebSocket配置类

创建一个配置类,启用WebSocket支持:

importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.socket.server.standard.ServerEndpointExporter;@ConfigurationpublicclassWebSocketConfig{@BeanpublicServerEndpointExporterserverEndpointExporter(){returnnewServerEndpointExporter();}}

WebSocket实现

实现WebSocket服务端:

importlombok.extern.slf4j.Slf4j;importorg.springframework.stereotype.Component;importjavax.websocket.*;importjavax.websocket.server.PathParam;importjavax.websocket.server.ServerEndpoint;importjava.io.IOException;importjava.util.concurrent.CopyOnWriteArraySet;@ServerEndpoint("/websocket/{sid}")@Component@Slf4jpublicclassWebSocketServer{privatestaticint onlineCount =0;privatestaticCopyOnWriteArraySet<WebSocketServer> webSocketSet =newCopyOnWriteArraySet<>();privateSession session;privateString sid ="";@OnOpenpublicvoidonOpen(Session session,@PathParam("sid")String sid){this.session = session;
        webSocketSet.add(this);addOnlineCount();
        log.info("有新窗口开始监听:"+ sid +", 当前在线人数为"+getOnlineCount());this.sid = sid;try{sendMessage("连接成功");}catch(IOException e){
            log.error("websocket IO异常");}}@OnClosepublicvoidonClose(){
        webSocketSet.remove(this);subOnlineCount();
        log.info("有一连接关闭!当前在线人数为"+getOnlineCount());}@OnMessagepublicvoidonMessage(String message,Session session){
        log.info("收到来自窗口"+ sid +"的信息:"+ message);for(WebSocketServer item : webSocketSet){try{
                item.sendMessage(message);}catch(IOException e){
                e.printStackTrace();}}}@OnErrorpublicvoidonError(Session session,Throwable error){
        log.error("发生错误");
        error.printStackTrace();}publicvoidsendMessage(String message)throwsIOException{this.session.getBasicRemote().sendText(message);}publicstaticvoidsendInfo(String message,@PathParam("sid")String sid)throwsIOException{
        log.info("推送消息到窗口"+ sid +",推送内容:"+ message);for(WebSocketServer item : webSocketSet){try{if(sid ==null){
                    item.sendMessage(message);}elseif(item.sid.equals(sid)){
                    item.sendMessage(message);}}catch(IOException e){continue;}}}publicstaticsynchronizedintgetOnlineCount(){return onlineCount;}publicstaticsynchronizedvoidaddOnlineCount(){WebSocketServer.onlineCount++;}publicstaticsynchronizedvoidsubOnlineCount(){WebSocketServer.onlineCount--;}publicstaticCopyOnWriteArraySet<WebSocketServer>getWebSocketSet(){return webSocketSet;}}

测试工具

可以使用WebSocket在线测试工具进行测试。

测试步骤

  1. 通过网关连接:ws://127.0.0.1:8080/admin/websocket/123
  2. 直接连接服务:ws://127.0.0.1:9201/websocket/123

通过以上步骤,可以实现Spring Cloud Gateway与WebSocket的集成,实现实时通信功能。
在这里插入图片描述


本文转载自: https://blog.csdn.net/qq_29752857/article/details/142595779
版权归原作者 好奇的菜鸟 所有, 如有侵权,请联系我们删除。

“Spring Cloud Gateway接入WebSocket:实现实时通信”的评论:

还没有评论