WebSocket 集群解决方案

前言

WebSocket是一种在网络应用程序中,使客户度端和服务器之间可以进行双向通信的协议。它允许数据可以在建立连接后进行实时交换,而不必依赖传统的HTTP请求-响应模式。WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。

在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。

方案一:广播方案

图片

  • Step1: 客户端连接到某个Websocket Server,在该websocket Server中建立userid和session的绑定关系

  • Step2: 其它服务或者客户端通过MQ广播消息所有Websocket Server(消息体中带有userid)

  • Step3: 所有Websocket Server 根据客户端userid找到对应session, 只有存在userid和session的绑定关系的Websocket Server才发送消息到客户端

代码演示

1.Websocket Server 建立userid和session的绑定关系

@ServerEndpoint("/websocket/{businessType}/{userId}")
@Component
public class WebSocketServer {
    /**
     * 若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
     * 注意:allSession 只记录当前机器的 客户端连接,不是所有session连接
     */

    public static ConcurrentHashMap<String, Session> allSession = new ConcurrentHashMap<>();

    @Resource
    private RedisService redisService;

    /**
     * 连接建立成功调用的方法
     *
     * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(@PathParam(value = "businessType") String businessType, @PathParam(value = "userId") String userId, Session session, EndpointConfig config) {
        if (StringUtils.isEmpty(userId)) {
            return;
        }
        /**
         * 加入到本地map
         */
        allSession.put(userId, session);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam(value = "userId") String userId, Session session) {
        if (StringUtils.isNotEmpty(userId)) {
            allSession.remove(userId);
        }
    }


    /**
     * 发生错误时调用
     *
     * @param
     * @param
     */
    @OnError
    public void onError(@PathParam(value = "userId") String userId, Session session, Throwable error) {
    }


    /**
     * 用户id
     *
     * @param userId
     * @param message
     */
    public void sendMessageToOneUser(Integer userId, String message, String msgId) {
        if (userId == null) {
            return;
        }
        Session session = allSession.get(String.valueOf(userId));
        if (session != null) {
         //所有Websocket Server 根据客户端userid找到对应session, 只有存在userid和session的绑定关系的Websocket Server才发送消息到客户端
          session.getAsyncRemote().sendText(message);
        } else {
            System.err.println("session为空");
            allSession.remove(userId + "");
        }
    }
}

2.所有Websocket Server 接收消息并处理

@Component
@RequiredArgsConstructor
public class CreateOrderConsumer implements BaseConsumer {


    private final WebSocketServer webSocketServer;


    @Override
    public Action handleMessage(Message message) {
        CreateOrderMessage createOrderMessage = JSON.parseObject(message.getBody(), LinkCreateOrderMessage.class);

        try {
           //业务校验省略...
           //调用WebSocketServer的sendMessageToOneUser方法,里面根据客户端userid找到对应session, 只有存在userid和session的绑定关系的Websocket Server才发送消息到客户端
            webSocketServer.sendMessageToOneUser(createOrderMessage.getUserId(), JSON.toJSONString(linkActionRes),message.getMsgID());
        } catch (Exception e) {
            e.printStackTrace();
            return Action.ReconsumeLater;
        }
        return Action.CommitMessage;
    }
}    

方案二:目标询址方案(推荐)

图片

Id标识有两种实现形式:

  • 为唯一的服务名:每一个WebSocketServer生成唯一的服务名(serviceName="XXX-" + IdUtil.oneId())并注册到naocs服务组册中心,uesrid与其绑定,服务适用方使用Feign 或其它RPC调用http://{serviceName}/xxx/xxx到指定WebSocketServer

  • 为唯一的IP+端口:每一个WebSocketServer 获取自己IP+端口,uesrid与其绑定,服务调用方使用该IP+端口

代码演示(唯一Id为唯一的服务名的形式)

1.绑定userid和服务名唯一Id的关系(以ApplicationName形式为例)

@SpringBootApplication
public class WsApplication  {

    public static void main(String[] args) {
        //动态服务名
        System.setProperty("myApplicationName", "WS-" + IdUtil.oneId());
        SpringApplication.run(WsApplication.class, args);
    }
}
spring:
  application:
    #随机名字,做ws集群使用
    name: ${myApplicationName}
@ServerEndpoint("/websocket/{businessType}/{userId}")
@Component
public class WebSocketServer {
    /**
     * 若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
     * 注意:allSession 只记录当前机器的 客户端连接,不是所有session连接
     */

    public static ConcurrentHashMap<String, Session> allSession = new ConcurrentHashMap<>();
    /**
     *
     */
    private String myApplicationName = System.getProperty("myApplicationName");
    @Resource
    private RedisService redisService;

    /**
     * 连接建立成功调用的方法
     * 关键代码
     * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(@PathParam(value = "businessType") String businessType, @PathParam(value = "userId") String userId, Session session, EndpointConfig config) {
        if (StringUtils.isEmpty(userId)) {
            return;
        }
        /**
         * 加入到本地map
         */
        allSession.put(userId, session);
        //绑定userid和服务名唯一Id的关系
        redisService.hset(WS_MAPPING, userId + "", myApplicationName);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam(value = "userId") String userId, Session session) {
        if (StringUtils.isNotEmpty(userId)) {
            allSession.remove(userId);
        }
    }

    /**
     * 发生错误时调用
     *
     * @param
     * @param
     */
    @OnError
    public void onError(@PathParam(value = "userId") String userId, Session session, Throwable error) {
    }

    /**
     * 用户id
     *
     * @param userId
     * @param message
     */
    public void sendMessageToOneUser(Integer userId, String message) {
        if (userId == null) {
            return;
        }
        Session session = allSession.get(String.valueOf(userId));
        if (session != null) {
         //所有Websocket Server 根据客户端userid找到对应session, 只有存在userid和session的绑定关系的Websocket Server才发送消息到客户端
          session.getAsyncRemote().sendText(message);
        } else {
            System.err.println("session为空");
            allSession.remove(userId + "");
        }
    }
}

2.Websocket Server提供的调用接口

@RestController
@RequestMapping("push")
public class  WebSocketPushController {


    @PostMapping("{userId}")
    public void pushMessage(@PathVariable Long userId, @RequestBody Object message) {
            webSocketServer.sendMessageToOneUser(userId, message);
    }

}

3.调用方通过nacos调用目标Websocket Server

//业省略
MyApplicationName myApplicationName =  redisService.hget(WS_MAPPING, userId + "");

Feign:
http://${myApplicationName}/push/{userId}

图片

来源:juejin.cn/post/7306451559928348709

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: Spring RabbitMQ与WebSocket集群的概念是将RabbitMQ和WebSocket技术结合,实现分布式集群的消息传递和实时通信的需求。 首先,Spring RabbitMQ是一个基于AMQP协议的消息队列中间件,它使用消息队列来实现系统之间的异步通信。而WebSocket是一种基于HTTP的协议,可以在客户端和服务器之间建立实时的双向通信通道。 在Spring中,我们可以使用RabbitMQ来实现分布式集群的消息队列,用于异步任务的处理和消息的传递。同时,使用WebSocket可以实现客户端和服务器之间的实时通信,可以在需要的时候向客户端推送实时的消息或数据。 要实现Spring RabbitMQ与WebSocket集群,可以采取以下步骤: 1. 首先搭建RabbitMQ集群,确保多个节点之间的消息能够正确传递。可以使用Spring Boot的RabbitMQ Starter快速集成RabbitMQ。 2. 使用Spring WebSocket模块来建立WebSocket服务器,处理客户端的连接请求和消息传递。可以使用Spring Boot的WebSocket Starter快速集成WebSocket。 3. 在WebSocket服务器中,可以使用RabbitMQ的Java客户端来监听消息队列,实时地获取新的消息。一旦有新的消息到达,可以将消息推送给相应的客户端。 4. 在客户端中,使用WebSocket的API来建立与服务器的连接,通过订阅特定的消息主题或队列来接收实时推送的消息。 通过以上步骤,我们就可以实现Spring RabbitMQ与WebSocket集群。这样的集群可以实现消息的异步传递和实时通信的功能,适用于需要处理大量异步任务或实时交互的系统。 ### 回答2: Spring RabbitMQ与WebSocket集群的概念和实现方式如下: Spring RabbitMQ是一个用于实现AMQP(高级消息队列协议)的Java开发框架,用于构建可靠、可扩展和灵活的消息传递应用程序。它与WebSocket的集成可以在应用程序中实现实时的双向通信。 在构建WebSocket集群时,需要考虑以下几个关键点: 1. 实现集群的消息代理(Message Broker):RabbitMQ作为一个可靠的消息代理,可以用于在WebSocket集群中传递消息。每个节点都可以独立连接到RabbitMQ服务器,并通过交换机和队列来传递消息。 2. 使用Spring Boot集成WebSocket:Spring Boot提供了WebSocket的支持,通过@EnableWebSocketMessageBroker注解可以简化WebSocket的配置。可以使用@MessageMapping注解定义处理消息的方法,并通过@SendTo注解将消息发送到指定的目标。 3. 实现负载均衡和会话共享:在WebSocket集群中,可以使用负载均衡器来将客户端的请求分发到不同的节点上,以实现负载均衡。同时,还需要实现会话共享,确保用户在不同的节点上具有相同的会话状态,以便实现跨节点的消息传递和处理。 4. 配置消息队列和交换机:使用RabbitMQ作为消息代理,需要配置交换机和队列,以确保消息的传递和路由。可以使用Spring AMQP提供的注解来定义交换机和队列,并在处理方法中使用@RabbitListener注解监听指定的队列。 综上所述,Spring RabbitMQ与WebSocket集群可以通过使用RabbitMQ作为消息代理,将消息传递到多个WebSocket节点,从而实现分布式的实时双向通信。通过合理的配置和负载均衡策略,可以实现高可用性和可伸缩性的WebSocket集群。 ### 回答3: Spring 和 RabbitMQ 是两个独立的项目,分别用于构建企业级的Java应用程序和实现可靠的消息传递系统。而 WebSocket 是一种在 Web 应用程序中实现双向通信的协议。 要将 Spring、RabbitMQ 和 WebSocket 结合在一起形成集群,需要以下步骤: 1. 构建 Spring 集群:可以使用 Spring Cloud 或者 Spring Boot 来构建应用程序的集群。这样可以使应用程序能够在多个节点上进行负载均衡,并提高可用性和性能。 2. 集成 RabbitMQ:使用 Spring AMQP(Advanced Message Queuing Protocol)来集成 RabbitMQ。提供了一套抽象的 API,使得在 Spring 应用程序中使用 RabbitMQ 变得更加简单。 3. 创建 RabbitMQ 集群:在 RabbitMQ 中创建一个集群,将多个 RabbitMQ 服务器组合在一起。这样可以提高消息的可靠性和性能,并提供高可用性和可扩展性。 4. WebSocket 集群:在 Spring 中集成 WebSocket。可以使用 Spring WebSocket 模块提供的 API 来定义服务器端和客户端的逻辑,以实现双向通信。 5. 集群间消息传递:使用 RabbitMQ 作为消息传递系统,通过消息队列将集群中的不同节点进行通信。当一个节点收到消息后,可以将消息广播给其他节点,以便实现实时的双向通信。 总的来说,实现 Spring、RabbitMQ 和 WebSocket集群需要使用 Spring 集群、RabbitMQ 集群WebSocket 集群。这将提高应用程序的可用性、可靠性和性能,并实现实时的双向通信。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值