Redis-based message routing method, system, client and device

By establishing a multi-level mapping index and version verification mechanism in the Redis cluster, the problem of connection status awareness between WebSocket service nodes is solved, achieving efficient and accurate cross-node message routing and improving the flexibility and real-time performance of message push.

CN123164055APending Publication Date: 2026-11-24武汉达梦数据技术有限公司
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611296479.7
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-08-25
Publication Date
2026-11-24

AI Technical Summary

Technical Problem

In a multi-node deployment environment, the stateful and long-lived nature of WebSocket connections means that different WebSocket service nodes cannot directly perceive the connection status maintained by each other, resulting in insufficient accuracy and real-time performance of message push. Existing technologies rely on load balancer configuration and cannot handle multi-terminal connections.

Method used

By establishing multi-level mapping indexes in the Redis cluster, including user indexes, connection indexes, and node indexes, a unique connection version number is generated, and version verification is performed before message sending. This enables cross-node message routing and version verification, avoiding misdelivery or duplicate delivery of messages caused by old connection remnants.

Benefits of technology

It significantly improves the accuracy and reliability of cross-node message push, reduces reliance on load balancers, and enhances the flexibility and real-time performance of message push.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123164055A_ABST
    Figure CN123164055A_ABST
Patent Text Reader

Abstract

This invention provides a Redis-based message routing method, system, client, and device, belonging to the field of network communication technology. The method includes: establishing a WebSocket connection with the client and generating a connection identifier and connection version number; obtaining the current node instance identifier of the WebSocket service node device; establishing a multi-level mapping index; querying the multi-level mapping index to obtain the target node instance identifier; based on the matching result between the target node instance identifier and the current node instance identifier, sending message content locally or sending a routing message generated according to a push request across nodes; listening to the message routing channel corresponding to the current node instance identifier; when receiving routing messages from other WebSocket service node devices, performing version verification; and after successful version verification, sending message content to the client according to the connection identifier in the routing message. This invention improves the accuracy of message push.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of network communication technology, and specifically to a message routing method, system, client, and device based on Redis. Background Technology

[0002] With the increasing prevalence of applications such as online customer service, instant messaging, real-time notifications, and cloud platform event notifications, the demand for low-latency, bidirectional real-time communication between servers and clients is constantly growing. WebSocket, as a full-duplex communication protocol based on TCP, can establish persistent connections between clients and servers, reducing resource consumption from polling and improving message exchange efficiency. After a WebSocket connection is established, the server needs to maintain the session state of that connection so that it can proactively push messages to the client when business events are triggered.

[0003] In monolithic applications or single-node deployments, WebSocket connections are typically maintained directly by the current service process, allowing the server to push messages to clients based on the connection object in its local memory. However, in multi-node deployments, clients usually connect to backend WebSocket service nodes via load balancers or Ingress. Because WebSocket connections are stateful and persistent, the connection object is typically maintained in local memory by the specific access node after connection establishment. When multiple WebSocket service nodes exist in the system, they cannot directly perceive each other's connection status. This makes it difficult for any business service or WebSocket service node to accurately determine which WebSocket service node the target client is currently connected to when initiating a message push, thus affecting the accuracy and real-time performance of message pushes. Common solutions include session stickiness, sticky sessions based on load balancers, using Redis (Remote Dictionary Server) for publish / subscribe (Pub / Sub) message broadcasting, or maintaining a simple user-to-node mapping at the business layer. In addition, some solutions use message queues (such as RabbitMQ) to forward messages between different service nodes, while others use consistent hashing algorithms to route connection requests from specific users to the same service node.

[0004] However, while the above methods can solve the cross-node push problem to some extent, they still have the following shortcomings: First, they are highly dependent on the load balancer configuration, which is not conducive to the elastic scaling of services in a cloud-native environment; second, simple user-to-node mapping cannot handle multiple connections, duplicate connections, and connection version changes for the same user, resulting in inaccurate message routing between different service nodes. Summary of the Invention

[0005] In view of this, it is necessary to provide a message routing method, system, client and device based on Redis to solve the technical problems of insufficient message routing accuracy caused by the reliance on load balancing session persistence and the inability to handle multi-end connections in the existing technology.

[0006] To address the aforementioned technical problems, in a first aspect, this invention provides a Redis-based message routing method applied to a WebSocket service node device, comprising: Establish a WebSocket connection with the client and generate a connection identifier and a connection version number; obtain the current node instance identifier of the WebSocket service node device; write the connection identifier, the connection version number, and the current node instance identifier into the Redis cluster and establish a multi-level mapping index. Receive a push request sent by a business service, which includes a user identifier and message content, and query the multi-level mapping index based on the user identifier to obtain the target node instance identifier; Based on the matching result between the target node instance identifier and the current node instance identifier, the message content is sent locally or a routed message generated based on the push request is sent across nodes; Listen to the message routing channel corresponding to the current node instance identifier. When a routing message is received from another WebSocket service node device, perform version verification. After the version verification is successful, send the message content to the client according to the connection identifier in the routing message.

[0007] In one possible implementation, the multi-level mapping index includes a user index, a join index, and a node index, and the establishment of the multi-level mapping index includes: The user index is established based on the connection identifier and the user identifier; The connection index is established based on the connection identifier, the connection version number, and the current node instance identifier; The node index is established based on the current node instance identifier and the connection identifier.

[0008] In one possible implementation, obtaining the target node instance identifier by querying the multi-level mapping index based on the user identifier includes: The user index is queried based on the user identifier to obtain the set of connection identifiers corresponding to the user identifier; the user index stores one or more connection identifiers corresponding to the user identifier, and the set of connection identifiers includes the connection identifiers of all WebSocket connections associated with the user identifier; The target node instance identifier is obtained by querying the connection index based on the target connection identifier; the connection index stores the node instance identifier corresponding to the connection identifier.

[0009] In one possible implementation, the step of sending the message content locally or sending a routed message generated based on the push request across nodes, based on the matching result between the target node instance identifier and the current node instance identifier, includes: When the target node instance identifier matches the current node instance identifier, the message content is sent to the client via the WebSocket connection. When the target node instance identifier is inconsistent with the current node instance identifier, the push request is encapsulated into a routing message and the routing message is sent to the message routing channel in the Redis cluster corresponding to the target node instance identifier.

[0010] In one possible implementation, after establishing the multi-level mapping index, the method further includes: Set the first time-to-live for each of the aforementioned connection indexes; Based on the heartbeat message or protocol layer response frame received from the client, the first time-to-live is refreshed, and the latest heartbeat time in the connection index is updated.

[0011] In one possible implementation, before sending the message content to the client via the WebSocket connection, the method further includes: Verify whether the first time-to-live (TTL) is in a valid state in the Redis cluster; If the first time-to-live has expired, stop sending the message content and clear the record corresponding to the connection identifier in the user index, the connection index, and the node index.

[0012] One possible implementation also includes: If the first time-to-live is in the valid state, verify whether the connection version number stored locally is consistent with the connection version number recorded in the Redis cluster; If there is a discrepancy, stop sending the message content and clear the record corresponding to the connection identifier in the user index, the connection index, and the node index; If they match, the version verification is successful.

[0013] In one possible implementation, after receiving a routing message from another WebSocket service node device and before performing version verification, the method further includes: The local connection table is queried based on the connection identifier in the routing message to determine whether a corresponding WebSocket connection exists locally; the local connection table stores the WebSocket connections established by the WebSocket service node device. If the WebSocket connection does not exist locally, write a failure status to the Redis cluster and clear the record corresponding to the connection identifier in the user index, the connection index, and the node index.

[0014] In one possible implementation, prior to establishing the WebSocket connection with the client, the method further includes: Generate the current node instance identifier and register node lease information with a second time to live in the Redis cluster; The second lifetime is refreshed periodically during the operation of the WebSocket service node device.

[0015] One possible implementation also includes: If the second time-to-live has expired, query the node index based on the current node instance identifier to obtain the associated connection identifier; Batch delete the records corresponding to the associated connection identifiers.

[0016] In one possible implementation, after sending the message content to the client, the method further includes: If no acknowledgment is received within a preset time, the message content is added to the retry queue and re-delivered. During the delivery process, deduplication is performed based on the message identifier of the message content.

[0017] One possible implementation also includes: Receive the connection request initiated by the client through the load balancing component, and return the connection identifier and the connection version number to the client according to the connection request; Receive heartbeat messages or protocol layer response frames periodically sent by the client and refresh the first time-to-live of the corresponding connection index in the Redis cluster; The message content is pushed to the client, and a confirmation receipt is received from the client. When the client reconnects, the system receives the new connection version number sent by the client and writes the new connection version number into the Redis cluster to overwrite the old connection version number.

[0018] Secondly, this invention also provides a Redis-based message routing method applied to a client, including: A connection request is initiated to the WebSocket service node device through the load balancing component, and a WebSocket connection is established with the WebSocket service node device; wherein... The WebSocket connection is used to enable the WebSocket service node device to generate a connection identifier and a connection version number after establishing a connection, obtain the current node instance identifier of the WebSocket service node device, write the connection identifier, the connection version number and the current node instance identifier into the Redis cluster and establish a multi-level mapping index; The multi-level mapping index is used to enable the WebSocket service node device to obtain the target node instance identifier by querying the multi-level mapping index based on the user identifier after receiving a push request from the business service, which includes a user identifier and message content. The target node instance identifier is used to enable the WebSocket service node device to determine, based on its matching result with the current node instance identifier, whether to send the message content locally or to send the routed message generated according to the push request across nodes through the message routing channel corresponding to the target node instance identifier; The message routing channel is used for the WebSocket service node device to listen, and when it receives the routing message sent by other WebSocket service node devices, it performs version verification. After the version verification is passed, it sends the message content to the client according to the connection identifier in the routing message. The message content pushed by the WebSocket service node device is obtained through the WebSocket connection; The WebSocket connection is used to send an acknowledgment to the WebSocket service node device.

[0019] In one possible implementation, after establishing a WebSocket connection with the WebSocket service node device, the method further includes: The WebSocket service node device periodically sends heartbeat messages or protocol layer response frames to refresh the second lifetime of the connection index based on the heartbeat messages or protocol layer response frames.

[0020] One possible implementation also includes: When a reconnection occurs, the currently established WebSocket connection is disconnected, and a new connection request is initiated to the WebSocket service node device through the load balancing component. A new connection version number is sent to the WebSocket service node device so that the WebSocket service node device writes the new connection version number into the Redis cluster to overwrite the old connection version number.

[0021] Thirdly, the present invention also provides a WebSocket service node device, including a memory and a processor, wherein, The memory is used to store programs; The processor, coupled to the memory, is used to execute the program stored in the memory to implement the steps in the Redis-based message routing method described above.

[0022] Fourthly, the present invention also provides a client, including a memory and a processor, wherein, The memory is used to store programs; The processor, coupled to the memory, is used to execute the program stored in the memory to implement the steps in the Redis-based message routing method described above.

[0023] Fifthly, the present invention also provides a Redis-based message routing system, comprising: The client described in the fourth aspect; Multiple WebSocket service node devices, such as third-party devices; The Redis cluster communicates with the WebSocket service node device to store multi-level mapping indexes and provide message routing channels; The business service communicates with the WebSocket service node device and is used to send a push request including user identifier and message content to any WebSocket service node device; A load balancing component is communicatively connected to both the client and the WebSocket service node device, and is used to distribute the client's connection requests to the WebSocket service node device.

[0024] The beneficial effects of this invention are as follows: Firstly, by establishing a multi-level mapping index in the Redis cluster, the distributed WebSocket connection status is centrally managed, enabling any WebSocket service node device to accurately locate the node where the target client is located by querying the index, thereby significantly improving the accuracy of cross-node message push. Furthermore, by generating a unique connection version number for each connection and performing version verification before message sending, new and old connections established by the same client at different times are effectively distinguished, avoiding misdelivery or duplicate delivery of messages caused by old connection remnants, thus enhancing the reliability of message push. Furthermore, through the cross-node message routing mechanism, business services can complete cross-node message delivery by initiating a push request to any WebSocket service node device, without relying on the session persistence capability of the load balancer, thereby improving the flexibility of message push. Attached Figure Description

[0025] To more clearly illustrate the technical solutions in the embodiments of the present invention, the accompanying drawings used in the description of the embodiments will be briefly introduced below. Obviously, the accompanying drawings described below are only some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0026] Figure 1 This is a schematic diagram of an embodiment of the Redis-based message routing method provided by the present invention; Figure 2 This is a schematic diagram of an embodiment of the Redis-based message routing system provided by the present invention; Figure 3 This is a flowchart and timing diagram of an embodiment of the Redis-based message routing method provided by the present invention; Figure 4 For the present invention Figure 1 A schematic diagram of an embodiment of S102; Figure 5 This is a flowchart illustrating another embodiment of the Redis-based message routing method provided by the present invention. Detailed Implementation

[0027] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only a part of the embodiments of the present invention, and not all of them. All other embodiments obtained by those skilled in the art based on the embodiments of the present invention without creative effort are within the scope of protection of the present invention.

[0028] In the description of the embodiments of the present invention, unless otherwise stated, "multiple" means two or more. "And / or" describes the relationship between related objects, indicating that there can be three relationships. For example, A and / or B can represent three situations: A exists alone, A and B exist simultaneously, and B exists alone.

[0029] The terms "first," "second," etc., used in the embodiments of this invention are for descriptive purposes only and should not be construed as indicating or implying their relative importance or implicitly specifying the number of technical features indicated. Therefore, a technical feature defined with "first" or "second" may explicitly or implicitly include at least one of that feature.

[0030] In this document, the term "embodiment" means that a particular feature, structure, or characteristic described in connection with an embodiment may be included in at least one embodiment of the invention. The appearance of this phrase in various places throughout the specification does not necessarily refer to the same embodiment, nor is it a separate or alternative embodiment mutually exclusive with other embodiments. It will be explicitly and implicitly understood by those skilled in the art that the embodiments described herein can be combined with other embodiments.

[0031] This invention provides a message routing method, system, client, and device based on Redis, which are described below.

[0032] Figure 1 This is a schematic diagram of an embodiment of the Redis-based message routing method provided by the present invention, as shown below. Figure 1 As shown, the Redis-based message routing method, applied to the WebSocket service node device, includes the following: S101. Establish a WebSocket connection with the client and generate a connection identifier and a connection version number. Obtain the current node instance identifier of the WebSocket service node device. Write the connection identifier, the connection version number, and the current node instance identifier into the Redis cluster and establish a multi-level mapping index.

[0033] It should be noted that: such as Figure 2 As shown, the architecture of the Redis-based message routing system includes a client, a load balancing component, multiple WebSocket service nodes (including WebSocket service node A, WebSocket service node B, and WebSocket service node C), a Redis cluster, business services, and a cleanup and fault tolerance module. The execution sequence diagram of the Redis-based message routing method is shown below. Figure 3 As shown, each WebSocket service node device deploys the exact same code; therefore, the same WebSocket service node device plays different roles at different time stages, such as... Figure 3 As shown, WebSocket service node A acts as the initiating push node and WebSocket service node B acts as the access node. Alternatively, WebSocket service node B can act as the initiating push node and WebSocket service node A as the access node. The client first initiates a WebSocket connection request to the WebSocket service node device through a load balancer or Ingress component. After receiving the connection request, the load balancer or Ingress component distributes the request to a specific WebSocket service node device according to a preset load balancing strategy; in this embodiment, it is assumed to be distributed to WebSocket service node B. After receiving the connection request, WebSocket service node B establishes a WebSocket connection with the client.

[0034] like Figure 3 As shown, during the connection establishment process, WebSocket service node B generates a globally unique connection identifier (connectionId) and connection version number (version) for the current connection, and obtains its own current node instance identifier (nodeInstanceId). The connectionId uniquely identifies the current WebSocket connection; a new connectionId is generated each time the same client refreshes the page, reconnects to the network, or migrates the service. The version identifies the current connection version; a new version is generated each time the client re-establishes a connection to distinguish between old and new connections. The nodeInstanceId identifies the running instance of the current WebSocket service node device; a new nodeInstanceId is generated when the node device restarts, migrates, or undergoes a rolling upgrade. Subsequently, WebSocket service node B writes the connection information to the Redis cluster and establishes a multi-level mapping index.

[0035] S102. Receive a push request sent by the service, which includes a user identifier and message content, and query the multi-level mapping index based on the user identifier to obtain the target node instance identifier.

[0036] It should be noted that when a business service needs to push a message to a user, it sends a push request to any WebSocket service node device. The push request includes at least a user identifier (userId), a message identifier (messageId), and a message content (payload). In this embodiment, it is assumed that the business service sends the push request to WebSocket service node A. After receiving the push request, WebSocket service node A queries the multi-level mapping index in the Redis cluster based on the user identifier in the push request to obtain the target node instance identifier corresponding to the push request.

[0037] S103. Based on the matching result between the target node instance identifier and the current node instance identifier, send the message content locally or send the routing message generated according to the push request across nodes.

[0038] It should be noted that after obtaining the target node instance identifier, WebSocket service node A compares the target node instance identifier with its own current node instance identifier. Based on the matching result, the message content is sent to the client locally. That is, the current node directly sends the message content to the client through the locally maintained WebSocket connection, without going through the Redis routing channel. The local sending process is: business service → current WebSocket service node (initiating push) → client. Alternatively, based on the matching result, a routing message generated by the push request is sent across nodes. That is, WebSocket service node A encapsulates the push request into a routing message and writes the routing message into the message routing channel in the Redis cluster corresponding to the target node instance identifier. The target WebSocket service node (e.g., node B) listens to this channel in advance, obtains the routing message from the channel, and sends the message content to the client through the local WebSocket connection. Thus, through the message routing channel provided by the Redis cluster, the cross-node sending process is: business service → WebSocket service node A (initiating push) → Redis routing channel → WebSocket service node B (target node) → client.

[0039] S104. Listen to the message routing channel corresponding to the current node instance identifier. When a routing message is received from another WebSocket service node device, perform version verification. After the version verification is passed, send the message content to the client according to the connection identifier in the routing message.

[0040] It should be noted that each WebSocket service node device starts a listening thread or process to continuously listen to the message routing channel corresponding to its current node instance identifier. After WebSocket service node B listens to the message routing channel corresponding to it in the Redis cluster, it retrieves the routing message sent by WebSocket service node A from that channel. After receiving the routing message, WebSocket service node B first performs version verification. If the verification passes, WebSocket service node B sends the message content to the client through the local WebSocket connection.

[0041] In this embodiment, by establishing a multi-level mapping index in the Redis cluster, the distributed WebSocket connection state is centrally managed. This allows any WebSocket service node device to accurately locate the node where the target client is located by querying the index, thereby significantly improving the accuracy of cross-node message push. Furthermore, by generating a unique connection version number for each connection and performing version verification before message sending, new and old connections established by the same client at different times are effectively distinguished, avoiding misdelivery or duplicate delivery of messages caused by old connection remnants, thus enhancing the reliability of message push. Furthermore, through the cross-node message routing mechanism, business services can complete cross-node message delivery by initiating a push request to any WebSocket service node device, without relying on the session persistence capability of the load balancer, thereby improving the flexibility of message push.

[0042] In some embodiments of the present invention, the multi-level mapping index includes a user index, a connection index, and a node index, and the establishment of the multi-level mapping index includes: S1011. Establish the user index based on the connection identifier and the user identifier; S1012. Establish the connection index based on the connection identifier, the connection version number, and the current node instance identifier; S1013. Establish the node index based on the current node instance identifier and the connection identifier.

[0043] It should be noted that after generating the connection identifier, WebSocket service node B obtains the user identifier from the client's connection request. The user identifier is a unique identifier for the user at the business level, such as a user account ID, mobile phone number, or email address, used to uniquely identify a user at the business level.

[0044] WebSocket service node B establishes a user index in the Redis state center, using the user identifier as the key and the connection identifier as the value. The user index uses a Redis Set data structure to store one or more connection identifiers corresponding to the same user identifier. WebSocket service node B establishes a connection index in the Redis state center, using the connection identifier as the key. The connection index uses a Hash structure to store fields such as userId, version, nodeId, nodeInstanceId, status, and lastHeartbeatTime. In this system, `userId` is the user identifier, used to record the user to whom the connection belongs; `version` is the connection version number, used to identify the version of the connection, with a new version number generated each time the client re-establishes a connection; `nodeId` is the logical service node identifier, used to identify the logical identity of the WebSocket service node device; `nodeInstanceId` is the node instance identifier, used to identify the currently running WebSocket service node device instance; `status` is the connection status, used to identify the current status of the connection, such as normal or failed and awaiting closure; `lastHeartbeatTime` is the last heartbeat time, used to record the timestamp of the last heartbeat of the connection; and `ttl` is the first time-to-live, i.e., the connection lease validity period, used to control the automatic expiration time of the connection index in Redis. WebSocket service node B uses the logical service node identifier corresponding to the current node instance identifier as the key to create a node index in the Redis state center. The node index uses a Redis Set data structure to store one or more connection identifiers carried on the same WebSocket service node device.

[0045] In this embodiment, by establishing a multi-level mapping index including user index, connection index, and node index, the system can quickly locate the connection status from the user, connection, and node dimensions, achieving efficient querying in cross-node scenarios. Furthermore, the user index can meet the actual business requirement of multiple devices of the same user being online simultaneously and all able to receive messages. Furthermore, the connection index stores a connection version number field, enabling the system to verify the old and new status of connections when routing messages, avoiding sending messages to expired old connections, thereby effectively preventing misdelivery of messages. Furthermore, establishing a node index allows for the rapid retrieval and batch cleanup of all connection identifiers carried on a node based on the node identifier, improving processing efficiency.

[0046] In some embodiments of the present invention, such as Figure 4 As shown, step S102 includes: S401. Query the user index according to the user identifier to obtain the connection identifier set corresponding to the user identifier; the user index stores one or more connection identifiers corresponding to the user identifier, and the connection identifier set includes the connection identifiers of all WebSocket connections associated with the user identifier; S402. Query the connection index according to the target connection identifier to obtain the target node instance identifier corresponding to the connection identifier; the connection index stores the node instance identifier corresponding to the connection identifier.

[0047] It should be noted that after receiving a push request from the business service, WebSocket service node A extracts the user identifier from the push request. Using this user identifier as the key, WebSocket service node A queries the user index in the Redis cluster. Since the user index is stored using a Redis Set data structure, the same user can correspond to one or more connection identifiers. Therefore, the query result is a set of connection identifiers. The set of connection identifiers includes the connection identifiers of all WebSocket connections associated with that user identifier. For example, when the same user logs in simultaneously on a mobile phone, tablet, and PC, this set will contain three connection identifiers, each corresponding to a WebSocket connection on a different device. If the query result is an empty set, it means that the user currently has no active WebSocket connections, and WebSocket service node A returns an error status to the business service indicating that the user is offline or there are no deliverable connections. After obtaining the set of connection identifiers, WebSocket service node A retrieves the target connection identifier from this set.

[0048] In this embodiment, a two-level query mechanism using user index and join index is employed to locate the target node instance identifier step by step, starting from the user identifier. The query path is clear, avoiding global scanning or broadcast queries, thereby significantly improving the query efficiency of cross-node message routing.

[0049] In some embodiments of the present invention, step S103 includes: S1031. When the target node instance identifier is consistent with the current node instance identifier, the message content is sent to the client through the WebSocket connection.

[0050] It's important to note that after WebSocket service node A obtains the target node instance identifier, it compares this identifier with its own current node instance identifier. If they match, it means the target client is currently connected to the WebSocket service node itself, meaning the target connection is located locally on the current node. In this case, WebSocket service node A doesn't need to go through a Redis routing channel; instead, it directly sends messages to the client through the WebSocket connection maintained in its local memory. This process is called "local sending."

[0051] S1032. When the target node instance identifier is inconsistent with the current node instance identifier, the push request is encapsulated into a routing message, and the routing message is sent to the message routing channel in the Redis cluster corresponding to the target node instance identifier.

[0052] It should be noted that if the target node instance identifier is inconsistent with the current node instance identifier, it means that the target client is currently connected to another WebSocket service node device, and the current node (WebSocket service node A) cannot directly send messages to the client through the WebSocket connection in local memory. In this case, WebSocket service node A needs to execute a cross-node sending process to forward the message to the target node. That is, WebSocket service node A encapsulates the push request into a routed message. Based on the target node instance identifier, WebSocket service node A determines the message routing channel in the Redis state center corresponding to the target node instance identifier. Subsequently, WebSocket service node A publishes the encapsulated routed message to that message routing channel. Taking Redis Pub / Sub mode as an example, if... Figure 3 As shown in timing 11B, WebSocket service node A publishes a routing message to the message routing channel corresponding to node B in the Redis state center, and node B listens for and obtains the routing message.

[0053] Local sending is suitable for scenarios where the target client is connected to the current node, meaning the client is connected to the same node device that received the service push request. Cross-node sending is suitable for scenarios where the target client is connected to other nodes, meaning the client is connected to other node devices in the distributed cluster. In actual business operations, load balancing or Ingress components distribute client connection requests to different node devices according to a preset load balancing strategy; therefore, client connections may be distributed across any node in the cluster. By combining local sending and cross-node sending mechanisms, the technical solution of this invention can support a complete distributed message routing closed loop where any node receives push requests and any node completes message delivery.

[0054] In this embodiment, by automatically selecting the local sending or cross-node sending method based on the matching result of the target node instance identifier and the current node instance identifier, when the target node is the current node, the message is sent directly through the local connection, avoiding unnecessary Redis relay, thereby reducing the transmission latency of message push and improving the real-time performance of message push.

[0055] In some embodiments of the present invention, after establishing the multi-level mapping index, the method further includes: Set the first time-to-live for each of the aforementioned connection indexes; Based on the heartbeat message or protocol layer response frame received from the client, the first time-to-live is refreshed, and the latest heartbeat time in the connection index is updated.

[0056] It should be noted that after WebSocket service node B completes the establishment of multi-level mapping indexes (including user index, connection index, and node index), it sets a first time-to-live (TTL) for the connection index. The first time-to-live indicates the validity period of the connection lease. The first time-to-live means that when the time-to-live countdown of the connection index reaches zero, the Redis state center will automatically delete the connection index.

[0057] During the connection maintenance period, the client sends heartbeat messages or protocol layer response frames (Pong frames, control frames used in the WebSocket protocol to respond to Ping frames) to the WebSocket service node B according to a preset heartbeat cycle. Heartbeat messages can be custom application-layer heartbeat messages or standard WebSocket protocol layer Pong frames. The WebSocket service node B continuously receives messages from the client through its WebSocket connection listening thread. When it receives a heartbeat message or protocol layer Pong frame from the client, the WebSocket service node B first identifies the message type. If it is a protocol layer Pong frame, it directly enters the lease renewal process; if it is an application-layer heartbeat message, it parses the message body to confirm it is a heartbeat message before entering the lease renewal process. After confirming the receipt of a valid heartbeat message or protocol layer Pong frame, the WebSocket service node B refreshes the first time-to-live (TTL) of the corresponding connection index in the Redis state center to reset the remaining TTL of the connection index to its initial value (e.g., 30 seconds), thus restarting the countdown. In addition, the WebSocket service node B also updates the latest heartbeat time field in the connection index. That is, as long as the client continues to send heartbeat messages, the first time-to-live (TTL) and latest heartbeat time of the connection index will be continuously refreshed, ensuring that the connection index remains valid as long as the client is active. For example... Figure 3As shown in timing 7, after receiving the heartbeat message, WebSocket service node B sends a request to the Redis state center to refresh the TTL.

[0058] In this embodiment, by setting a first time-to-live (TTL) for the connection index, abnormally disconnected connections can be automatically cleaned up by Redis after their leases expire, without manual intervention. This effectively reduces the generation of zombie and dirty connection records, improving the system's self-maintenance capabilities and robustness. Furthermore, by periodically triggering the refresh of the first TTL through client heartbeat messages or protocol-layer Pong frames, active connections continuously renew their leases before the first TTL expires, ensuring the continued validity of normal connections in the Redis state center. This allows message routing to always make decisions based on accurate connection status. Furthermore, by simultaneously updating the latest heartbeat time in the connection index, monitoring data on connection activity is provided for system maintenance, facilitating the troubleshooting of connection anomalies and locating the root cause of problems, thereby improving the system's observability and maintainability.

[0059] In some embodiments of the present invention, before sending the message content to the client via the WebSocket connection, the method further includes: Verify whether the first time-to-live (TTL) is in a valid state in the Redis cluster; If the first time-to-live has expired, stop sending the message content and clear the record corresponding to the connection identifier in the user index, the connection index, and the node index.

[0060] It should be noted that after WebSocket service node A determines that the target node instance identifier matches the current node instance identifier (i.e., the target connection is located locally on the current node), it first needs to verify the validity of the connection before sending messages. The first step of the verification is to check whether the first time-to-live (TTL) of the corresponding connection index in the Redis state center is still valid. WebSocket service node A queries the remaining TTL of the connection index in the Redis state center using the connection identifier as the key. WebSocket service node A determines whether the TTL is valid based on the return value.

[0061] If the return value or remaining time-to-live (TTL) is less than or equal to zero, it indicates that the first TTL has expired, meaning the WebSocket connection is in an invalid state. WebSocket connection failure may be caused by the following reasons: 1) The client has abnormally disconnected but did not trigger a normal close callback; 2) The client's heartbeat timed out, causing the connection index to be automatically cleaned up by Redis; 3) The WebSocket connection has been replaced by a new connection on another node device. In this case, WebSocket service node A immediately stops sending the message content to the client to avoid sending the message to the invalid WebSocket connection. Simultaneously, WebSocket service node A returns an error status indicating that the connection has failed to deliver, informing the business service that the message could not be successfully delivered. Furthermore, WebSocket service node A removes the connection identifier from the user index in the Redis state center, deletes the key-value pair corresponding to the connection index in the Redis state center, and removes the connection identifier from the node index in the Redis state center, thus cleaning up all records of the invalid WebSocket connection in the multi-level mapping index.

[0062] In this embodiment, by verifying the lifetime of the connection index before sending a message, it is ensured that only valid connections with confirmed leases can receive messages, preventing messages from being sent to expired or invalid connections, thereby significantly improving the accuracy and reliability of message push. Furthermore, when a connection lease expires, all records of that connection in the user index, connection index, and node index are simultaneously cleaned up, ensuring that no expired connection information remains in the multi-level mapping indexes, thus maintaining the consistency of connection states in the Redis state center and preventing subsequent routing queries from being interfered with by dirty data. Furthermore, the combination of automatic lease expiration cleanup and proactive heartbeat timeout cleanup forms a dual protection mechanism, ensuring that connection records are cleaned up in a timely manner regardless of whether the connection fails due to abnormal client disconnection, network jitter, or node failure, thereby reducing the risk of system state inconsistency.

[0063] In some embodiments of the present invention, it further includes: If the first time-to-live is in the valid state, verify whether the connection version number stored locally is consistent with the connection version number recorded in the Redis cluster; If there is a discrepancy, stop sending the message content and clear the record corresponding to the connection identifier in the user index, the connection index, and the node index; If they match, the version verification is successful.

[0064] It should be noted that after WebSocket service node A confirms that the first time-to-live (TTL) of the connection index is valid in S601, it performs connection version number verification. WebSocket service node A retrieves the connection version number corresponding to the connection from its local memory. WebSocket service node B generates a connection version number when establishing a connection, and this version number is stored in two locations: one is in WebSocket service node B's local memory, associated with the WebSocket connection itself; the other is in the connection index in the Redis state center, persistently stored as a version field. The locally stored version number is used to identify the version of the connection instance currently held locally by WebSocket service node A.

[0065] WebSocket service node A queries the connection index in the Redis state center using the connection identifier as the key to retrieve the connection version number field stored in the index. WebSocket service node A compares the locally stored connection version number with the connection version number recorded in the Redis state center. If the locally stored connection version number matches the connection version number recorded in the Redis cluster, it indicates that the current local connection is the latest valid connection. In this case, WebSocket service node A determines that the version verification has passed and then performs the message sending operation. If the locally stored connection version number does not match the connection version number recorded in the Redis cluster, it indicates that the current connection is an old, expired connection. In this case, all records of expired WebSocket connections in the multi-level mapping index can be cleaned up, referring to the above embodiment.

[0066] In this embodiment, by further verifying the consistency of the connection version number after the first time-to-live (TTL) expires, message sending is only allowed when both the lease and the version number are consistent. This avoids sending messages to older, updated connections, significantly improving the accuracy and reliability of message push. Furthermore, when version verification fails, all records of the connection in the user index, connection index, and node index are synchronously cleaned up. This ensures that residual information of the old connection in the multi-level mapping index is completely removed, thus maintaining the consistency of the connection state in the Redis state center and preventing subsequent routing queries from being interfered with by dirty data.

[0067] In some embodiments of the present invention, before performing version verification after receiving a routing message sent by another WebSocket service node device, the method further includes: The local connection table is queried based on the connection identifier in the routing message to determine whether a corresponding WebSocket connection exists locally; the local connection table stores the WebSocket connections established by the WebSocket service node device. If the WebSocket connection does not exist locally, write a failure status to the Redis cluster and clear the record corresponding to the connection identifier in the user index, the connection index, and the node index.

[0068] It should be noted that WebSocket service node B (as the target node) obtains routing messages from the message routing channel in the Redis state center through its listening thread. The routing message is encapsulated and published by the initiating node (WebSocket service node A), and includes at least the following fields: message identifier, user identifier, connection identifier, connection version number, target node instance identifier, and message content.

[0069] After receiving a routing message, WebSocket service node B first extracts the connection identifier from the message. Then, using this connection identifier as the key, WebSocket service node B queries its local connection table. The local connection table is a data structure stored in the local memory of the WebSocket service node device, used to record all WebSocket connections currently held by that node device. The content stored in the local connection table differs from the connection index in the Redis state center. The local connection table stores the actual memory references to the WebSocket connections (including objects such as TCP connection handles and session states during program runtime), while the connection index in the Redis state center stores connection metadata (including user identifier, connection version number, node instance identifier, connection state, most recent heartbeat time, and first time-to-live). The local connection table is used to confirm whether the node device actually holds the physical connection for that connection, while the Redis connection index is used for cross-node queries and routing decisions.

[0070] If a corresponding WebSocket connection exists in the local connection table, it means that the WebSocket service node B does indeed have a WebSocket connection corresponding to the connection identifier, that is, the connection is indeed established on the local node device, and the WebSocket service node B continues to execute the subsequent version verification process.

[0071] The absence of a corresponding WebSocket connection in the local connection table indicates that the WebSocket service node B does not have a WebSocket connection corresponding to this connection identifier locally. This means that although the connection is still recorded in the connection index in the Redis state center, it does not actually exist in the local memory of this node device, and the connection state is inconsistent. In this case, WebSocket service node B writes the delivery status corresponding to the message identifier in the routing message to the Redis state center, marking the message delivery as failed. Furthermore, WebSocket service node B removes the connection identifier from the user index in the Redis state center, deletes the key-value pair corresponding to the connection index in the Redis state center, and removes the connection identifier from the node index in the Redis state center. Through the above operations, all records of the failed WebSocket connection in the multi-level mapping index are cleared, and the connection state in the Redis state center is restored to consistency with the actual connection state in the local memory of the node device.

[0072] In cross-node sending scenarios, after receiving the routing message, the target node first queries its local connection table to confirm the existence of the connection, and then performs version verification and lease verification. In local sending scenarios, the current node also needs to ensure that the local connection exists before performing version verification.

[0073] In this embodiment, by first querying the local connection table to confirm the existence of the connection after receiving a cross-node routing message, the system can promptly detect and handle inconsistencies between the Redis state center and the node's local memory, thereby maintaining eventual consistency of the connection state in the distributed system. Furthermore, when the local connection does not exist, a failure status is written to the Redis state center and multi-level mapping index records are simultaneously cleaned up. This transforms the process of repairing connection inconsistencies from passive waiting to active repair, shortening the duration of inconsistencies and reducing the risk of message misrouting due to dirty index data. Moreover, the local connection table query, as a pre-step before version verification, can quickly filter out invalid routing messages generated by released local connections before version verification, avoiding unnecessary version verification overhead and thus improving the overall processing efficiency of message routing.

[0074] In some embodiments of the present invention, prior to establishing the WebSocket connection with the client, the method further includes: Generate the current node instance identifier and register node lease information with a second time to live in the Redis cluster; The second lifetime is refreshed periodically during the operation of the WebSocket service node device.

[0075] It should be noted that when a WebSocket service node device (taking node B as an example) starts up, it first generates a current node instance identifier for itself. The current node instance identifier is used to uniquely identify the currently running WebSocket service node device instance, and its generation method can be any one or more of the following combinations: (1) hostname, that is, the hostname of the operating system of the physical machine or virtual machine where the node device is located; (2) container instance name, that is, the Pod name of the node device in the container orchestration platform (such as Kubernetes); (3) startup timestamp, that is, the system timestamp when the node device starts up; (4) random unique identifier (UUID), that is, a universally unique identifier.

[0076] After generating the current node instance identifier, WebSocket service node B registers node lease information with a second time-to-live (TTL) in the Redis state center. After completing the lease registration, WebSocket service node B starts a background lease renewal thread during runtime. This thread periodically refreshes the TTL of the node lease information according to a preset renewal cycle (e.g., every 30 seconds). In short, at the end of each renewal cycle, the renewal thread first checks the running status of WebSocket service node B to confirm whether the node device is still in a normal operating state. If the node device is undergoing a normal shutdown process, the renewal operation is not performed, and the renewal thread terminates directly. If the node device is in a normal operating state, the renewal thread uses the node instance identifier as the key to refresh the node lease TTL. After completing the TTL refresh, the lease thread can selectively update the latest renewal time field in the node lease to facilitate operation and maintenance monitoring and troubleshooting.

[0077] If the lease renewal thread fails in one or more renewal attempts (e.g., due to Redis becoming unreachable due to network partitioning), WebSocket service node B will log the renewal failures. When the number of consecutive renewal failures exceeds a preset threshold, the node device enters a self-protection mode, meaning it no longer accepts new client connection requests but retains the renewal logic for existing connections to avoid accidental batch connection cleanup caused by Redis abnormalities leading to node lease expiration. Once Redis recovers, the lease renewal thread successfully renews the lease again, and the node device automatically resumes normal operation.

[0078] In this embodiment, by generating a unique node instance identifier for each WebSocket service node device and registering the node lease in the Redis state center, the system can accurately identify the running instance of each node device in the distributed cluster, providing a basic identifier for node-level state management and fault detection. Furthermore, by periodically refreshing the lifetime of the node lease during node operation, normally operating node devices maintain their active status in the Redis state center through continuous lease renewal, ensuring that message routing decisions are always based on accurate node availability information.

[0079] In some embodiments of the present invention, it further includes: If the second time-to-live has expired, query the node index based on the current node instance identifier to obtain the associated connection identifier; Batch delete the records corresponding to the associated connection identifiers.

[0080] It should be noted that the cleanup and fault tolerance module, acting as a daemon process in the system background, periodically (e.g., every 10 seconds) scans all node lease information in the Redis state center to check whether the second lifetime of each node lease is still valid. Possible reasons for node lease expiration include: the node device stops renewing leases due to abnormal downtime; the node device is scaled down or destroyed in the Kubernetes cluster; the node device cannot renew leases due to network partitioning; the node device is stopped due to rolling upgrades. When the cleanup and fault tolerance module detects that the second lifetime of a node lease is less than or equal to zero, it determines that the second lifetime of the node lease has expired and needs to perform a cleanup operation on all connections associated with that node instance. Specifically, it uses the logical service node identifier corresponding to the current node instance identifier as the key, queries the node index in the Redis state center to obtain the set of all connection identifiers associated with the failed node device, and performs a batch cleanup operation on each connection identifier in this set. The batch cleanup operation includes the following steps: For each connection identifier, the cleanup and fault tolerance module first needs to obtain the user identifier corresponding to that connection identifier from the user index. It uses the connection identifier as the key to query the connection index to obtain the user identifier. After obtaining the user identifier, the cleanup and fault tolerance module removes the connection identifier from the user index. Furthermore, the cleanup and fault tolerance module deletes the key-value pair corresponding to the connection index in the Redis state center, and removes the connection identifier from the node index in the Redis state center. Additionally, after all associated connection records of the failed node device have been cleaned up, the cleanup and fault tolerance module can also choose to delete the node lease record itself for that failed node instance. Through these operations, all related records of the failed node device in the multi-level mapping index and node leases are cleaned up.

[0081] In this embodiment, the cleanup and fault tolerance module periodically checks the validity of node leases and automatically triggers the cleanup process when a node lease expires, without manual intervention. This enables rapid and automatic recovery of failed connections in node failure scenarios, significantly improving the system's self-healing capabilities and operational efficiency. Furthermore, by querying the node index based on the instance identifier of the failed node to obtain all connection identifiers associated with that node, and then deleting the corresponding records of these connection identifiers in the user index, connection index, and node index in batches, the failure of a node device can be cleaned up with a single query and batch operation, avoiding the tedious process of querying each connection one by one, thereby greatly improving the efficiency of failed connection cleanup.

[0082] In some embodiments of the present invention, after sending the message content to the client, the method further includes: If no acknowledgment is received within a preset time, the message content is added to the retry queue and re-delivered. During the delivery process, deduplication is performed based on the message identifier of the message content.

[0083] It should be noted that after sending a message to the client, the WebSocket service node device (taking node B as an example) starts a timeout timer, waiting for the client to return an acknowledgment (ACK). This preset time can be configured according to the business scenario and network environment, for example, set to 30 seconds. After receiving the message, the client returns an acknowledgment to WebSocket service node B via the WebSocket connection. This acknowledgment includes at least the message identifier.

[0084] If WebSocket service node B receives an acknowledgment from the client within a preset time, it writes the delivery status corresponding to the messageId to the Redis state center, marking the message as successfully delivered. If WebSocket service node B does not receive an acknowledgment within the preset time, it determines that the message delivery has timed out and adds the message content (along with metadata such as message identifier, user identifier, and connection identifier) ​​to the retry queue. The retry queue can be implemented using Redis's List data structure or a dedicated message queue (such as RabbitMQ or Apache RocketMQ). Before each redelivery, the message status index in the Redis state center is queried based on the message identifier to determine whether the message has been successfully acknowledged. If the query result indicates that the message has been successfully acknowledged, the retry consumer stops retries for the message and removes it from the retry queue to avoid duplicate sending. If the query result indicates that the message has not been acknowledged, the retry consumer performs a redelivery operation.

[0085] In this embodiment, by combining a preset timeout with an acknowledgment mechanism, the system can accurately identify whether message delivery was successful, thus providing an accurate and reliable triggering basis for subsequent retry processes. Furthermore, by adding the message to the retry queue and re-delivering it according to a preset strategy when no acknowledgment is received, the system can automatically compensate for message transmission failures, avoiding message loss and improving message delivery reliability. Furthermore, by querying the delivery status based on the message identifier during the retry process for deduplication, the system can confirm whether the message has been successfully acknowledged before retrying, avoiding duplicate delivery due to acknowledgment delays or concurrent retrying, thereby ensuring the idempotency of message delivery.

[0086] In some embodiments of the present invention, such as Figure 5 As shown, it also includes: S501. Receive the connection request initiated by the client through the load balancing component, and return the connection identifier and the connection version number to the client according to the connection request.

[0087] It should be noted that the client first initiates a WebSocket connection request to the WebSocket service node device through a load balancer or Ingress component. The load balancer or Ingress component then distributes the connection request to a specific WebSocket service node device (e.g., node B) according to a preset load balancing strategy.

[0088] After receiving a connection request, WebSocket service node B establishes a WebSocket connection with the client, generates a connection identifier and connection version number, and obtains a node instance identifier (writing the connection information to the Redis state center and establishing a multi-level mapping index) according to steps S101 to S104 above. After completing the connection establishment and index registration, WebSocket service node B returns a response message to the client based on the connection request. The response message includes at least the connection identifier and connection version number. After receiving the response, the client stores the connection identifier and connection version number locally for subsequent heartbeat message sending, reconnection request carrying, and message confirmation operations.

[0089] S502. Receive the heartbeat message or protocol layer response frame periodically sent by the client, and refresh the first time-to-live of the corresponding connection index in the Redis cluster.

[0090] It should be noted that during the establishment and maintenance of the WebSocket connection, the client sends heartbeat messages or protocol layer response frames (Pong frames, control frames used in the WebSocket protocol to respond to Ping frames) to the WebSocket service node B according to a preset heartbeat period (e.g., every 10 seconds). The WebSocket service node B continuously receives messages from the client through its WebSocket connection listening thread. When it receives a heartbeat message or a protocol layer Pong frame from the client, the WebSocket service node B first identifies the type of message. If it is a protocol layer Pong frame, it directly enters the lease renewal process; if it is an application layer heartbeat message, it parses the message body to confirm it is a heartbeat message before entering the lease renewal process. After confirming the receipt of a valid heartbeat message or protocol layer Pong frame, the WebSocket service node B refreshes the first time-to-live (TTL) of the corresponding connection index in the Redis state center.

[0091] S503. Push the message content to the client and receive the confirmation receipt returned by the client.

[0092] It should be noted that after WebSocket service node B completes the message routing decision, it pushes the message content to the client via its local WebSocket connection. Upon receiving the message content, the client returns an acknowledgment to WebSocket service node B via the WebSocket connection. The acknowledgment includes at least a message identifier to indicate which message was successfully received. After receiving the acknowledgment, WebSocket service node B writes the delivery status corresponding to the message content to the Redis state center. If WebSocket service node B does not receive an acknowledgment within a preset time, it triggers a retry process, adding the message content to the retry queue and re-delivering it according to a preset strategy.

[0093] S504. When the client reconnects, receive the new connection version number sent by the client and write the new connection version number into the Redis cluster to overwrite the old connection version number.

[0094] It's important to note that when a client reconnects due to network fluctuations, page refreshes, terminal switching, or service restarts, the client re-initiates a connection request to the WebSocket service node device via load balancing or Ingress components. This reconnection request carries a new connection version number to distinguish the newly established connection from the previous one. Upon receiving the reconnection request, the WebSocket service node device (which could be node B or another node after load balancing, such as node A) re-establishes the WebSocket connection. During the connection establishment process, the WebSocket service node device receives the new connection version number sent by the client. This new connection version number is generated by the client during the reconnection (e.g., incrementing the old version number or using a timestamp plus a random number). The WebSocket service node device writes the new connection version number to the corresponding connection index in the Redis state center, overwriting the old connection version number.

[0095] In this embodiment, by returning a connection identifier and connection version number to the client, the client can carry these identifiers in subsequent interactions. This facilitates the server's ability to quickly locate the corresponding connection and version information in scenarios such as heartbeat renewal, message confirmation, and reconnection processing, thereby improving system manageability. Furthermore, by receiving periodically sent heartbeat messages from the client and refreshing the lifetime of the connection index in the Redis state center, active connections can maintain a valid state, while abnormally disconnected connections are automatically cleaned up due to the cessation of renewal, thus reducing zombie connections and dirty connection records and lowering system maintenance overhead. Furthermore, by receiving confirmation receipts from the client and writing the delivery status to the Redis state center, the system can accurately track message delivery results, thereby improving message delivery reliability. Furthermore, by receiving a new connection version number and overwriting the old version number in the Redis state center when the client reconnects, the old connection automatically becomes invalid due to version number inconsistency, effectively solving the problem of misdelivered messages caused by reconnection in distributed scenarios, thus significantly improving the accuracy of message push in client reconnection scenarios.

[0096] To better implement the Redis-based message routing method in this invention embodiment, based on the Redis-based message routing method applied to WebSocket service node devices, this invention also provides a Redis-based message routing method applied to the client, the method comprising: A connection request is initiated to the WebSocket service node device through the load balancing component, and a WebSocket connection is established with the WebSocket service node device; wherein... The WebSocket connection is used to enable the WebSocket service node device to generate a connection identifier and a connection version number after establishing a connection, obtain the current node instance identifier of the WebSocket service node device, write the connection identifier, the connection version number and the current node instance identifier into the Redis cluster and establish a multi-level mapping index; The multi-level mapping index is used to enable the WebSocket service node device to obtain the target node instance identifier by querying the multi-level mapping index based on the user identifier after receiving a push request from the business service, which includes a user identifier and message content. The target node instance identifier is used to enable the WebSocket service node device to determine, based on its matching result with the current node instance identifier, whether to send the message content locally or to send the routed message generated according to the push request across nodes through the message routing channel corresponding to the target node instance identifier; The message routing channel is used for the WebSocket service node device to listen, and when it receives the routing message sent by other WebSocket service node devices, it performs version verification. After the version verification is passed, it sends the message content to the client according to the connection identifier in the routing message. The message content pushed by the WebSocket service node device is obtained through the WebSocket connection; The WebSocket connection is used to send an acknowledgment to the WebSocket service node device.

[0097] It should be noted that when a client (e.g., an instant messaging application running on a smartphone) needs to establish a real-time communication channel, it initiates a WebSocket connection request to the load balancer or Ingress component. The connection request includes at least a user identifier. Upon receiving the connection request, the load balancer or Ingress component distributes the request to a specific WebSocket service node device in the backend according to a preset load balancing strategy (e.g., round-robin, least connections, or IP hashing). The WebSocket service node device (e.g., a WebSocket service node) establishes a WebSocket connection with the client, referring to the corresponding embodiments of steps S101 to S104 described above.

[0098] After establishing a WebSocket connection, the client keeps the connection open and continuously listens for message arrival events. The client listens for message events through the WebSocket protocol's event-driven mechanism. When the WebSocket service node (i.e., the target node, such as node B) completes version and lease verification and determines that the message can be sent, it sends the message content (payload) to the client through the WebSocket connection. The client's event listening mechanism triggers the `onMessage` callback function, which reads the message content pushed by the server from the WebSocket connection. This message content is the actual data that the business service needs to push to the client, such as chat messages in instant messaging scenarios, system alarms or event notifications in real-time notification scenarios, etc. Its data format can be any format agreed upon by the client and server, such as JSON, Protocol Buffers, or plain text.

[0099] After receiving the message content, the client parses it and extracts the business data (such as the message content itself, message identifier, message type, and sending timestamp). The message content also includes a message identifier (messageId), which the client needs to record locally so that it can be included when returning a confirmation receipt later.

[0100] After successfully receiving and parsing the message content, the client generates an acknowledgment (ACK). The acknowledgment includes at least a message identifier (messageId) to identify which message was successfully received, and may also include optional information such as a reception timestamp or processing status code. The client sends the acknowledgment to the WebSocket service node device (i.e., the target node, e.g., node B) that pushed the message via the WebSocket connection. Upon receiving the acknowledgment, the WebSocket service node device writes the delivery status corresponding to the messageId to the Redis status center, marking the message as successfully delivered. If the client fails to receive the message content within a preset time (e.g., due to message loss caused by network failure), it will not return an acknowledgment. If the server does not receive the acknowledgment within the preset time, it will trigger a retry process and automatically re-push the message content. During the retry process, the server deduplicates messages based on the message identifier, ensuring that even if messages are repeatedly pushed due to network jitter, the client can perform idempotent processing at the application layer, avoiding duplicate consumption.

[0101] In this embodiment, the client initiates a connection request to the WebSocket service node device through the load balancing component and establishes a WebSocket connection with the server. This enables the client to access the distributed WebSocket cluster using standard protocols without needing to be aware of the specific deployment details of the backend nodes, thereby improving the client's compatibility and access flexibility.

[0102] Furthermore, after the connection is established, the client continuously listens for messages on the WebSocket connection. When the server pushes a message after completing cross-node routing and version verification, the client can receive and process the message content in a timely manner. The complete message push process forms a clear division of responsibilities between the server's routing decision and the client's passive reception, thereby improving the overall processing efficiency of the system.

[0103] Furthermore, after successfully receiving a message, the client returns an acknowledgment to the server, enabling the server to accurately track the message delivery status. This provides a closed-loop acknowledgment mechanism for reliable message delivery and retrying in case of failure, thereby significantly improving the reliability of message delivery.

[0104] Furthermore, the client does not need to be aware of whether the message originates from a local node or a cross-node, nor does it need to be aware of the server's routing decisions and version verification logic. All the complexity of distributed routing and connection state management is handled by the server and the Redis state center, thereby simplifying the implementation complexity of the client and improving its lightweightness and portability.

[0105] In some embodiments of the present invention, after establishing a WebSocket connection with the WebSocket service node device, the method further includes: The WebSocket service node device periodically sends heartbeat messages or protocol layer response frames to refresh the second lifetime of the connection index based on the heartbeat messages or protocol layer response frames.

[0106] It should be noted that after the client successfully establishes a WebSocket connection with WebSocket service node B, it immediately starts a heartbeat timer to periodically send heartbeat messages or protocol layer response frames (Pong frames, control frames used in the WebSocket protocol to respond to Ping frames) to WebSocket service node B. The preset value of the heartbeat period can be configured according to actual business needs and network environment. WebSocket service node B continuously receives messages from the client through its WebSocket connection listening thread. When WebSocket service node B receives a heartbeat message or protocol layer Pong frame sent by the client, it refreshes the second time-to-live of the connection index.

[0107] In this embodiment, the client periodically sends heartbeat messages or protocol-layer Pong frames to the server, enabling the server to continuously monitor the client's liveness. Upon receiving a heartbeat, the server refreshes and resets the time-to-live (TTL) of the connection index, ensuring that active connections remain valid in the Redis state center. Furthermore, the client can flexibly choose between protocol-layer Pong frames or application-layer heartbeat messages to implement heartbeat keep-alive based on the actual network environment. This optimizes network resource consumption while ensuring connection validity, improving the compatibility and adaptability of the solution across different client environments.

[0108] In some embodiments of the present invention, it further includes: When a reconnection occurs, the currently established WebSocket connection is disconnected, and a new connection request is initiated to the WebSocket service node device through the load balancing component. A new connection version number is sent to the WebSocket service node device so that the WebSocket service node device writes the new connection version number into the Redis cluster to overwrite the old connection version number.

[0109] The client continuously monitors the connection status during the WebSocket connection period. When any of the following triggering conditions are detected, the client determines that a reconnection process is required. These triggering conditions include abnormal network disconnection, heartbeat timeout, client application layer-triggered reconnection due to business needs, and server-side active closure (i.e., the server actively closes the connection due to rolling upgrades, scaling down, or load balancing adjustments, and the client receives a close frame from the server). After determining to execute the reconnection process, the client calls the `close()` method of the WebSocket API (or its equivalent in the corresponding programming language) to send a WebSocket close frame to the WebSocket server node B. The close frame may carry a close code (e.g., 1000 indicates a normal close) and a reason for closure, so that the server knows why the client actively disconnected.

[0110] After sending a close frame, the client releases local resources associated with the connection, including clearing locally stored resources such as the connection identifier, connection version number, message queue, and timers. Simultaneously, the client stops all read and write operations on the current connection and marks the connection status as "closed" or "reconnecting," ensuring no operations are performed on the old connection until reconnection is complete. The client updates the connection status to "RECONNECTING" in its local state, preventing attempts to send heartbeat messages or new messages during reconnection. The client waits for the WebSocket protocol stack to complete the close handshake (i.e., receive a close frame confirmation from the server), ensuring the connection is completely released and preventing port or resource leaks. If no close frame confirmation is received from the server within a preset time (e.g., 5 seconds), the client forcibly closes the underlying TCP connection.

[0111] After disconnecting the old connection, the client re-initiates a connection request to the WebSocket service node device via a load balancer or Ingress component. This connection request follows the same process as the initial connection request, but with the following differences: Upon receiving the reconnection request, the load balancer or Ingress component distributes the connection request to a specific backend WebSocket service node device according to a preset load balancing strategy. Since the client's IP address or network environment may have changed (e.g., switching from Wi-Fi to 5G), the load balancing strategy may distribute the request to a different node device than the old connection. For example, if the old connection was on node B, the reconnection request might be distributed to node A. The WebSocket service node device receiving the reconnection request (which could be node B or node A) executes the same connection establishment process as in S101, including: establishing a WebSocket connection, generating a new connection identifier and a new connection version number, obtaining the node instance identifier, writing the connection information to the Redis state center, and establishing a multi-level mapping index. The client sends the new connection version number to the WebSocket service node device in the reconnection request. After receiving the new connection version number, the WebSocket service node device writes the new connection version number to the corresponding connection index in the Redis state center to overwrite the old connection version number.

[0112] In this embodiment, when the client detects a connection anomaly or triggers a reconnection condition, it actively disconnects the current connection and re-initiates a connection request through the load balancing component. This enables the client to quickly restore the communication channel when the network environment changes or the server node fails, thereby improving the system's self-healing capability and the user experience.

[0113] Furthermore, when the client reconnects, it generates and sends a new connection version number to the server. The server writes the new version number to the Redis state center to overwrite the old version number, so that the old connection automatically becomes invalid due to the version number inconsistency, and the new connection becomes the only valid message receiving channel. This effectively solves the problem of message misdelivery caused by reconnection in distributed scenarios and significantly improves the accuracy of message push.

[0114] In all specific embodiments of this application, when processing data related to user identity or characteristics, such as user information, user behavior data, user historical data, and user location information, user permission or consent is obtained first. Furthermore, the collection, use, and processing of this data comply with relevant laws, regulations, and standards. Additionally, when embodiments of this application require access to sensitive personal information, separate permission or consent from the user is obtained through pop-ups or redirects to confirmation pages. Only after obtaining the user's separate permission or consent is the necessary user-related data required for the proper functioning of these embodiments acquired.

[0115] To better implement the Redis-based message routing method in this embodiment of the invention, based on the Redis-based message routing method, this embodiment of the invention also provides a WebSocket service node device, including a memory and a processor, wherein... The memory is used to store programs; The processor, coupled to the memory, is used to execute the program stored in the memory to implement the steps in the Redis-based message routing method described above.

[0116] To better implement the Redis-based message routing method in this embodiment of the invention, based on the Redis-based message routing method, this embodiment of the invention also provides a client, including a memory and a processor, wherein... The memory is used to store programs; The processor, coupled to the memory, is used to execute the program stored in the memory to implement the steps in the Redis-based message routing method described above.

[0117] To better implement the Redis-based message routing method in this embodiment of the invention, based on the Redis-based message routing method, the corresponding method is as follows: Figure 2 and Figure 3 As shown, this embodiment of the invention also provides a message routing system based on Redis, including: The client described in the above embodiments; Multiple WebSocket service node devices as described in the above embodiments; The Redis cluster communicates with the WebSocket service node device to store multi-level mapping indexes and provide message routing channels; The business service communicates with the WebSocket service node device and is used to send a push request including user identifier and message content to any WebSocket service node device; A load balancing component is communicatively connected to both the client and the WebSocket service node device, and is used to distribute the client's connection requests to the WebSocket service node device.

[0118] The specific implementation details and beneficial effects of this embodiment can be found in the above embodiments, and will not be repeated here.

[0119] The Redis-based message routing method, system, client, and device provided by this invention have been described in detail above. Specific examples have been used to illustrate the principles and implementation methods of this invention. The descriptions of the above embodiments are only for the purpose of helping to understand the method and core ideas of this invention. At the same time, for those skilled in the art, there will be changes in the specific implementation methods and application scope based on the ideas of this invention. Therefore, the content of this specification should not be construed as a limitation of this invention.

Claims

1. A message routing method based on Redis, characterized in that, Applied to WebSocket service node devices, including: Establish a WebSocket connection with the client and generate a connection identifier and a connection version number; obtain the current node instance identifier of the WebSocket service node device; write the connection identifier, the connection version number, and the current node instance identifier into the Redis cluster and establish a multi-level mapping index. Receive a push request sent by a business service, which includes a user identifier and message content, and query the multi-level mapping index based on the user identifier to obtain the target node instance identifier; Based on the matching result between the target node instance identifier and the current node instance identifier, the message content is sent locally or a routed message generated based on the push request is sent across nodes; Listen to the message routing channel corresponding to the current node instance identifier. When a routing message is received from another WebSocket service node device, perform version verification. After the version verification is successful, send the message content to the client according to the connection identifier in the routing message.

2. The message routing method based on Redis according to claim 1, characterized in that, The multi-level mapping index includes a user index, a join index, and a node index. Establishing the multi-level mapping index includes: The user index is established based on the connection identifier and the user identifier; The connection index is established based on the connection identifier, the connection version number, and the current node instance identifier; The node index is established based on the current node instance identifier and the connection identifier.

3. The Redis-based message routing method according to claim 2, characterized in that, The step of querying the multi-level mapping index based on the user identifier to obtain the target node instance identifier includes: The user index is queried based on the user identifier to obtain the set of connection identifiers corresponding to the user identifier; the user index stores one or more connection identifiers corresponding to the user identifier, and the set of connection identifiers includes the connection identifiers of all WebSocket connections associated with the user identifier; The target node instance identifier is obtained by querying the connection index based on the target connection identifier; the connection index stores the node instance identifier corresponding to the connection identifier.

4. The Redis-based message routing method according to claim 2, characterized in that, The step of sending the message content locally or sending a routed message generated based on the push request across nodes, based on the matching result between the target node instance identifier and the current node instance identifier, includes: When the target node instance identifier matches the current node instance identifier, the message content is sent to the client via the WebSocket connection. When the target node instance identifier is inconsistent with the current node instance identifier, the push request is encapsulated into a routing message and the routing message is sent to the message routing channel in the Redis cluster corresponding to the target node instance identifier.

5. The Redis-based message routing method according to claim 2, characterized in that, After establishing the multi-level mapping index, the following is also included: Set the first time-to-live for each of the aforementioned connection indexes; Based on the heartbeat message or protocol layer response frame received from the client, the first time-to-live is refreshed, and the latest heartbeat time in the connection index is updated.

6. The Redis-based message routing method according to claim 5, characterized in that, Before sending the message content to the client via the WebSocket connection, the method further includes: Verify whether the first time-to-live (TTL) is in a valid state in the Redis cluster; If the first time-to-live has expired, stop sending the message content and clear the record corresponding to the connection identifier in the user index, the connection index, and the node index.

7. The Redis-based message routing method according to claim 6, characterized in that, Also includes: If the first time-to-live is in the valid state, verify whether the connection version number stored locally is consistent with the connection version number recorded in the Redis cluster; If there is a discrepancy, stop sending the message content and clear the record corresponding to the connection identifier in the user index, the connection index, and the node index; If they match, the version verification is successful.

8. The Redis-based message routing method according to claim 2, characterized in that, After receiving a routing message from another WebSocket service node device, but before performing version verification, the process further includes: The local connection table is queried based on the connection identifier in the routing message to determine whether a corresponding WebSocket connection exists locally; the local connection table stores the WebSocket connections established by the WebSocket service node device. If the WebSocket connection does not exist locally, write a failure status to the Redis cluster and clear the record corresponding to the connection identifier in the user index, the connection index, and the node index.

9. The Redis-based message routing method according to claim 2, characterized in that, The process, prior to establishing the WebSocket connection with the client, also includes: Generate the current node instance identifier and register node lease information with a second time to live in the Redis cluster; The second lifetime is refreshed periodically during the operation of the WebSocket service node device.

10. The Redis-based message routing method according to claim 9, characterized in that, Also includes: If the second time-to-live has expired, query the node index based on the current node instance identifier to obtain the associated connection identifier; Batch delete the records corresponding to the associated connection identifiers.

11. The Redis-based message routing method according to claim 1, characterized in that, After sending the message content to the client, the method further includes: If no acknowledgment is received within a preset time, the message content is added to the retry queue and re-delivered. During the delivery process, deduplication is performed based on the message identifier of the message content.

12. The Redis-based message routing method according to any one of claims 1 to 11, characterized in that, Also includes: Receive the connection request initiated by the client through the load balancing component, and return the connection identifier and the connection version number to the client according to the connection request; Receive heartbeat messages or protocol layer response frames periodically sent by the client and refresh the first time-to-live of the corresponding connection index in the Redis cluster; The message content is pushed to the client, and a confirmation receipt is received from the client. When the client reconnects, the system receives the new connection version number sent by the client and writes the new connection version number into the Redis cluster to overwrite the old connection version number.

13. A message routing method based on Redis, characterized in that, Applied to the client side, including: A connection request is initiated to the WebSocket service node device through the load balancing component, and a WebSocket connection is established with the WebSocket service node device; wherein... The WebSocket connection is used to enable the WebSocket service node device to generate a connection identifier and a connection version number after establishing a connection, obtain the current node instance identifier of the WebSocket service node device, write the connection identifier, the connection version number and the current node instance identifier into the Redis cluster and establish a multi-level mapping index; The multi-level mapping index is used to enable the WebSocket service node device to obtain the target node instance identifier by querying the multi-level mapping index based on the user identifier after receiving a push request from the business service, which includes a user identifier and message content. The target node instance identifier is used to enable the WebSocket service node device to determine, based on its matching result with the current node instance identifier, whether to send the message content locally or to send the routed message generated according to the push request across nodes through the message routing channel corresponding to the target node instance identifier; The message routing channel is used for the WebSocket service node device to listen, and when it receives the routing message sent by other WebSocket service node devices, it performs version verification. After the version verification is passed, it sends the message content to the client according to the connection identifier in the routing message. The message content pushed by the WebSocket service node device is obtained through the WebSocket connection; The WebSocket connection is used to send an acknowledgment to the WebSocket service node device.

14. The Redis-based message routing method according to claim 13, characterized in that, After establishing a WebSocket connection with the WebSocket service node device, the method further includes: The WebSocket service node device periodically sends heartbeat messages or protocol layer response frames to refresh the second lifetime of the connection index based on the heartbeat messages or protocol layer response frames.

15. The Redis-based message routing method according to claim 13, characterized in that, Also includes: When a reconnection occurs, the currently established WebSocket connection is disconnected, and a new connection request is initiated to the WebSocket service node device through the load balancing component. A new connection version number is sent to the WebSocket service node device so that the WebSocket service node device writes the new connection version number into the Redis cluster to overwrite the old connection version number.

16. A WebSocket service node device, characterized in that, The method includes a memory and a processor, wherein the memory is used to store a program; and the processor is coupled to the memory and is used to execute the program stored in the memory to implement the steps in the Redis-based message routing method according to any one of claims 1 to 12.

17. A client, characterized in that, Includes a memory and a processor, wherein the memory is used to store programs; The processor, coupled to the memory, is used to execute the program stored in the memory to implement the steps in the Redis-based message routing method according to any one of claims 13 to 15.

18. A message routing system based on Redis, characterized in that, include: The client as described in claim 17; Multiple WebSocket service node devices as described in claim 16; The Redis cluster communicates with the WebSocket service node device to store multi-level mapping indexes and provide message routing channels; The business service communicates with the WebSocket service node device and is used to send a push request including user identifier and message content to any WebSocket service node device; A load balancing component is communicatively connected to both the client and the WebSocket service node device, and is used to distribute the client's connection requests to the WebSocket service node device.