Distributed long connection message pushing method and system based on tag routing

By assigning unique tags to microservice instances and building a unified push abstraction layer, combined with Redis caching and message queues, the problem of unstable user connections in microservice architecture is solved, achieving efficient and reliable message push and improved scalability.

CN123185256APending Publication Date: 2026-11-27WUHAN SOUTH SAGITTARIUS INTEGRATION CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611101333.2
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-07-23
Publication Date
2026-11-27

AI Technical Summary

Technical Problem

In a microservice architecture, load balancing leads to inconsistent user connection sessions. Existing technical solutions suffer from broadcast storms, are complex to implement, have poor scalability, and lack reliable mechanisms for offline message processing and push failures.

Method used

Each service instance is assigned a unique label, and the mapping relationship between users and instance labels is cached in Redis to achieve accurate routing; a unified push abstraction layer is built to shield protocol differences; and offline message persistence, failure retry, and automatic fault handling mechanisms are combined.

Benefits of technology

Significantly reduces invalid message processing, improves resource utilization and scalability, ensures reliable message delivery, reduces operational complexity, and provides automatic fault detection and self-healing capabilities.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123185256A_ABST
    Figure CN123185256A_ABST
Patent Text Reader

Abstract

The application discloses a distributed long connection message pushing method based on a labeled routing, which allocates a unique instance label for each service instance; stores a mapping relationship between a user identification and an instance label in which the user is located in a global cache when the user is online; obtains the instance label corresponding to a target user by querying the cache when pushing, and accurately routes a message to the instance, and only the instance holding the target session carries out the pushing. Through the technical scheme, the message consumption quantity is reduced from O(N) of a broadcast mode to O(1), a broadcast storm is avoided significantly, invalid message processing overhead is reduced, and system resource utilization and cluster expansibility are improved. The application also combines an offline persistence, a failure retry and other mechanisms to ensure that a message can be reliably delivered.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the field of computer software technology, and in particular to a distributed long-connection message push method and system based on tag-based routing, which is applicable to the scenario of accurate message push for WebSocket and SSE (Server-Sent Events) long connections under a microservice architecture. Background Technology

[0002] In a microservice architecture, the front-end and back-end typically communicate via long-lived connection protocols such as WebSocket or SSE, enabling server-side proactive push. To ensure high availability and load balancing, the back-end is usually deployed with multiple service instances, and a load balancer (such as Nginx) distributes front-end connection requests to different instances.

[0003] However, the randomness of load balancing means that each service instance holds a different user connection session, meaning the mapping between users and instances is dynamic and not fixed. When a business module needs to push a message to a user, the push request may arrive at a service instance that does not hold that user's session, thus failing to find the target session and causing the push to fail.

[0004] The following solutions are mainly used in existing technologies to address this problem:

[0005] 1. Broadcast Mode: Push messages are delivered to a broadcast topic in the message queue. All service instances subscribe to this topic and consume messages. Each instance locally determines whether it holds the target user's Session; if it does, the message is pushed; otherwise, it is ignored. This solution suffers from a severe broadcast storm problem, where every message is consumed by all instances, resulting in a large amount of invalid message processing, wasting CPU, memory, and network bandwidth resources. Furthermore, the proportion of invalid consumption increases linearly with the number of instances, leading to poor scalability.

[0006] 2. Consistent Hash Routing: This method maps users to fixed instances using a consistent hashing algorithm, and locates the target instance based on the hash value during push notifications. However, this approach requires rehashing when instances go offline or online, leading to a large number of connection migrations, making it complex to implement and impacting the online user experience.

[0007] 3. Centralized Session Storage: All sessions are centrally stored in middleware such as Redis. This approach requires custom session serialization and deserialization logic, and since WebSocket connections are essentially stateful long-lived connections based on TCP, they cannot be directly stored and restored in middleware, making implementation difficult.

[0008] Furthermore, existing solutions typically lack reliable mechanisms for handling offline messages. When a user is offline, push messages may be lost entirely. There is also a lack of automatic retry and compensation mechanisms for failed pushes, making it impossible to guarantee message delivery. Additionally, the differences between WebSocket and SSE long-connection protocols increase the complexity of upper-layer business code. Summary of the Invention

[0009] The purpose of this application is to overcome the above-mentioned defects of the prior art and provide a distributed long-connection message push method and system based on tag-based routing. By assigning a unique tag to each service instance and using Redis to cache the mapping relationship between users and instance tags, the message is accurately routed to the target instance according to the tag during message push, avoiding broadcast storms. At the same time, reliable message delivery is achieved through mechanisms such as offline message persistence and automatic online triggering, automatic retry compensation for push failure, and unified abstraction of WebSocket / SSE protocol.

[0010] To achieve the above objectives, the present application adopts the following technical solution.

[0011] In a first aspect, embodiments of this application provide a distributed long-connection message push method based on tag-based routing, including:

[0012] Assign a unique instance label to each service instance in the distributed cluster;

[0013] In response to a target user establishing a long connection through a target service instance, a local session object of the target user is created, and the mapping relationship between the user identifier of the target user and the instance tag of the target service instance is stored in the global cache;

[0014] In response to receiving a push request for the target user, the system queries the global cache to obtain an instance tag corresponding to the user identifier, and routes the message to be pushed to the target service instance based on the instance tag.

[0015] The target service instance pushes the message to be pushed to the target user through the local session object according to the mapping relationship.

[0016] Furthermore, the long connection includes the WebSocket protocol and the SSE protocol;

[0017] The distributed long-connection message push method further includes: building a unified push abstraction layer on the service instance side; the unified push abstraction layer is used to shield the interface differences between the WebSocket protocol and the SSE protocol, and provide a unified session management interface and message push interface for upper-layer services.

[0018] Furthermore, it also includes a failure retry compensation step, specifically including:

[0019] When the target service instance fails to push the message to be pushed through the local session object, the message to be pushed and its associated retry information are written into the failure message storage unit.

[0020] The scheduled task scans for failure messages in the pending retry state based on the retry information, and re-executes the push operation when the target user's local session object is valid.

[0021] Furthermore, when the target user goes offline, the target service instance destroys the corresponding local session object and deletes the mapping relationship from the global cache;

[0022] When the target user comes back online, the local session object and mapping relationship are rebuilt through a new service instance, and the offline message storage unit is queried to obtain and push offline messages generated during the target user's offline period.

[0023] Furthermore, the service instance periodically sends heartbeat information to the global cache, and the heartbeat information carries the instance tag of the service instance and has an expiration date;

[0024] If the global cache does not receive heartbeat information from the service instance within the validity period, the service instance is determined to be in an abnormal state, and the instance failure handling process is triggered.

[0025] Furthermore, the step of routing the message to be pushed to the target service instance based on the instance tag specifically includes:

[0026] The message to be pushed is sent to the message queue system, and a message tag corresponding to the instance tag is set for the message;

[0027] The target service instance consumes the message to be pushed by subscribing to message tags in the message queue system that match its own instance tag.

[0028] Furthermore, the message records in the failure message storage unit include the number of retries and the next retry time;

[0029] During the scheduled task scan, only message records are obtained where the number of retries has not exceeded the preset limit and the next retry time is earlier than the current time.

[0030] For messages that exceed the preset limit on the number of retries, they are marked as final failures and an alarm is triggered.

[0031] Furthermore, the message to be pushed contains a globally unique message identifier;

[0032] Before consuming and pushing the message to be pushed, the target service instance also includes:

[0033] Based on the globally unique message identifier, an idempotency check is performed in the local cache or global cache. If it is determined that the message to be pushed has already been processed, the current push operation is ignored.

[0034] Secondly, embodiments of this application provide a system capable of implementing the distributed long-connection message push method described in any of the foregoing claims, comprising:

[0035] The service instance management module is used to assign a unique instance label to each service instance in the distributed cluster.

[0036] The connection management module, located in the service instance, is used to create a local session object for the target user in response to the target user establishing a long connection through the target service instance;

[0037] The state synchronization module is used to store the mapping relationship between the user identifier of the target user and the instance tag of the target service instance in the global cache;

[0038] The message routing module is used to respond to receiving a push request for the target user, query the global cache to obtain the instance tag corresponding to the user identifier, and route the message to be pushed to the target service instance according to the instance tag;

[0039] The message push module, located in the target service instance, is used to push the message to be pushed to the target user through the local session object according to the mapping relationship.

[0040] Thirdly, embodiments of this application provide an electronic device, including: one or more processors;

[0041] A memory for storing one or more programs; when the one or more programs are executed by the one or more processors, the one or more processors are able to implement the steps in the distributed long-connection message push method described in any of the preceding claims.

[0042] Fourthly, embodiments of this application provide a computer-readable medium storing a computer program, which, when executed by a processor, can implement the steps in the distributed long-connection message push method described in any of the preceding claims.

[0043] This application discloses a distributed long-connection message push method based on tag-based routing. This method assigns a unique instance tag to each service instance. When a user comes online, the mapping relationship between the user identifier and the instance tag is stored in a global cache. During push notifications, the cache is queried to obtain the instance tag corresponding to the target user, and the message is precisely routed to that instance, with push notifications only performed by the instance holding the target session. Through this technical solution, message consumption is reduced from O(N) in broadcast mode to O(1), significantly avoiding broadcast storms, reducing the overhead of handling invalid messages, and improving system resource utilization and cluster scalability. This application also incorporates offline persistence and failure retry mechanisms to ensure reliable message delivery. Attached Figure Description

[0044] Figure 1 An architecture diagram of a distributed long-connection message push system based on tag-based routing is provided for embodiments of this application;

[0045] Figure 2 This application provides a core flowchart of a distributed long-connection message push method based on tag-based routing, as illustrated in an embodiment of the present application.

[0046] Figure 3 This is a structural block diagram of an electronic device provided in an embodiment of this application. Detailed Implementation

[0047] To enable those skilled in the art to better understand the technical solutions of this application, exemplary embodiments of this application are described below with reference to the accompanying drawings, including various details of the embodiments of this application to aid understanding. These should be considered merely exemplary. Therefore, those skilled in the art should recognize that various changes and modifications can be made to the embodiments described herein without departing from the scope and spirit of this application. Similarly, for clarity and conciseness, descriptions of well-known functions and structures are omitted in the following description. Unless otherwise specified, the various embodiments of this application and the features within those embodiments can be combined with each other.

[0048] As used herein, the term "and / or" includes any and all combinations of one or more of the associated enumerated entries. The terminology used herein is for describing particular embodiments only and is not intended to limit the application. As used herein, the singular forms "a" and "the" are also intended to include the plural forms, unless the context clearly indicates otherwise. It should also be understood that when the terms "comprising" and / or "made of" are used herein, the presence of the stated feature, integral, step, operation, element, and / or component is specified, but the presence or addition of one or more other features, integrals, steps, operations, elements, components, and / or groups thereof is not excluded. Terms such as "connected" or "linked" are not limited to physical or mechanical connections but can include electrical connections, whether direct or indirect.

[0049] Unless otherwise specified, all terms used in this application (including technical and scientific terms) have the same meaning as commonly understood by one of ordinary skill in the art. It should also be understood that terms such as those defined in commonly used dictionaries should be interpreted as having a meaning consistent with their meaning in the context of the relevant art and this application, and will not be interpreted as having an idealized or overly formal meaning, unless expressly so defined in this application.

[0050] In this application, "tag" and "instance tag" are synonymous and both refer to the unique identifier of a service instance; "global cache" is preferably implemented using Redis, but is not limited to this.

[0051] I. System Architecture Overview

[0052] like Figure 1 As shown, an embodiment of this application provides a distributed long-connection message push system based on tag-based routing, which includes the following core components:

[0053] 1. Client layer: The front end can choose to establish a long connection using WebSocket (when bidirectional communication is required) or SSE (when only push notifications are needed) depending on the scenario. The backend processing logic of the two protocols is uniformly encapsulated by the abstraction layer and is transparent to the business.

[0054] 2. Load Balancer / API Gateway: Responsible for distributing frontend connection requests to backend service instances, supporting load balancing strategies such as round-robin and minimum connection count.

[0055] 3. Unified Push Abstraction Layer: Located between the gateway and the microservice instance, it encapsulates a unified push session interface, shielding the protocol differences between WebSocket and SSE. Business modules do not need to be aware of the protocol type when calling the push service.

[0056] 4. Microservice instance cluster: Each instance holds a unique instance tag, including a session management module (maintaining a local user session list), a message queue consumer module (consuming messages that match its own tag), and a failure retry task module (periodically scanning and retrying push failure messages).

[0057] 5. Global Cache (Redis): Stores user-instance tag mapping tables, online user sets, instance user list caches, and instance heartbeat information, providing millisecond-level online status query capabilities.

[0058] 6. Message Queue: RocketMQ message middleware is used, allowing different tag filtering conditions to be created under the same message topic, achieving precise message routing and delivery. Each tag corresponds to different tag filtering conditions under the same topic, and service instances only consume messages matching their own tags.

[0059] 7. Database: Includes an offline message table (stores messages to be pushed to offline users) and a push failure message table (stores messages that need to be retried after a push failure), providing persistent assurance for reliable message delivery.

[0060] The following is combined with Figure 2 The process is described in detail in one embodiment, illustrating the specific implementation of the method of this application.

[0061] II. Instance Tag Assignment and Unified Connection Abstraction

[0062] When a microservice cluster starts, each service instance is assigned a globally unique instance tag (hereinafter referred to as "tag"). This can be achieved in the following ways:

[0063] Read the pre-assigned tag identifier from the configuration center (such as Nacos); or

[0064] Automatically generate tags based on instance IP address and port number (e.g., TAG-192.168.1.10-8080); or

[0065] Apply to the registry center for a tag assignment to ensure global uniqueness.

[0066] In this embodiment, three service instances are used as examples: Instance 1 (IP 192.168.1.10:8080) is assigned the label TAG-A, Instance 2 (IP 192.168.1.11:8080) is assigned the label TAG-B, and Instance 3 (IP 192.168.1.12:8080) is assigned the label TAG-C. This label is determined when the instance starts and remains unchanged throughout its lifecycle, serving as a group identifier for all user connections on that instance.

[0067] On the service instance side, a unified push abstraction layer is built to shield the interface differences between the WebSocket and SSE protocols. The specific design is as follows:

[0068] Define a unified push session interface PushSession, which includes methods such as connect(), push(message), and close().

[0069] WebSocketPushSession implementation class: encapsulates the native WebSocket Session, supporting bidirectional communication and acknowledgment.

[0070] The SSEPushSession implementation class encapsulates SSE's SseEmitter, enabling one-way push via HTTP response streams.

[0071] Provides a PushSessionFactory class to automatically create the corresponding Session implementation class based on the frontend request headers or connection parameters.

[0072] A unified business push interface, PushService.push(userId, message), is exposed externally. Upper-layer business modules do not need to be aware of the underlying protocol type when calling this interface.

[0073] Furthermore, if the frontend fails to establish a connection using the WebSocket protocol, it can automatically downgrade to the SSE protocol. Upon receiving the downgraded request, the backend service instance creates the corresponding SSE session object using PushSessionFactory to ensure a higher connection success rate. This downgrade strategy is completely transparent to the business logic layer.

[0074] III. User Connection Management and Status Synchronization

[0075] Once a target user establishes a long-lived connection through the load balancer and is assigned to a service instance, that instance performs the following online registration process:

[0076] 1. Create a local session object PushSession and store it in a local session table (e.g., ConcurrentHashMap).<userId, PushSession> The key is the user identifier, and the value is the session object.

[0077] 2. Store the mapping relationship between user identifiers and instance tags in the global cache (Redis). The key format is user:tag:{userId}, and the value is the instance tag (such as TAG-A).

[0078] 3. Add the user to the global online user set (Redis Set type, key is online:users).

[0079] 4. Add the user to the user list cache of this instance (Redis Set type, key is instance:users:{TAG}).

[0080] For example, user A001 connects to instance 1 (label TAG-A) via load balancing, and instance 1 performs the following Redis operation:

[0081] SET user:tag:A001 TAG-A

[0082] SADD online:users A001

[0083] SADD instance:users:TAG-A A001

[0084] Meanwhile, Instance 1 stores the A001->WebSocketPushSession object in the local sessionMap.

[0085] When a user connection is detected to be disconnected (either intentionally or due to heartbeat timeout), the service instance executes the offline deregistration process:

[0086] 1. Remove the user's session object from the local session table.

[0087] 2. Delete the mapping from Redis: DEL user:tag:{userId}.

[0088] 3. Remove from the global online collection: SREM online:users{userId}.

[0089] 4. Remove from the instance user list: SREM instance:users:{TAG}{userId}.

[0090] When a user re-logs in, they may be assigned to another service instance by the load balancer (e.g., instance 2, tag TAG-B). The new service instance creates a new local session following the online registration process described above and updates the mapping in Redis to user:tag:A001=TAG-B. At this point, the local session of the old instance (TAG-A) has been destroyed, and its old mapping in Redis has been cleared, ensuring state consistency.

[0091] Each service instance periodically writes heartbeat information to Redis, with the key format `instance:heartbeat:{TAG}` and the value being any liveness flag (such as `alive`), and an expiration time (TTL) is set. For example, instance A executes `SET EX instance:heartbeat:TAG -A 15 alive` every 5 seconds. If the instance is normal, this key is continuously refreshed; if the instance crashes abnormally or experiences a network partition, the key automatically expires after 15 seconds. A global monitoring component (such as a separate fault detection service) periodically scans all heartbeat keys. If it finds that an instance's heartbeat key has expired, it determines that the instance is in an abnormal state and triggers a fault handling process: on the one hand, it issues an alarm, and on the other hand, it actively notifies the load balancer to remove the instance from the upstream server list to prevent new connection requests from being routed to the faulty instance. Meanwhile, since the heartbeat key of the faulty instance has expired, although the corresponding user mapping relationship (user:tag:{userId}) is not deleted immediately, the push service needs to combine the heartbeat status when querying. If the heartbeat of the target instance is found to be invalid, the user can be regarded as offline and the offline message process will be switched to avoid delivering messages to offline instances.

[0092] IV. Tag-based Message Routing

[0093] When a business module triggers a message push to a target user, the push service executes the following routing process:

[0094] 1. Query the global cache (Redis) to obtain the online status and instance tag of the target user. Specifically, execute GET user:tag:{userId}. If a non-empty value is returned, it means the user is online, and the return value is the tag of the instance to which the user belongs.

[0095] 2. If the user is online, the message to be pushed is routed to the target service instance based on the obtained instance tag. In this embodiment, a message queue (RocketMQ) is used to implement the routing.

[0096] 3. If the user is offline (no mapping record in Redis), then switch to the offline message processing flow.

[0097] The specific implementation method for routing messages to the target service instance based on instance tags is as follows:

[0098] Using the RocketMQ message middleware, precise routing is achieved by setting different tags for messages within the same message topic (e.g., PUSH_MSG). When sending a message, the producer (push service) sets the retrieved instance tag as the message's tag attribute. For example, if user A001's tag is TAG-A, the producer would set `message.setTags("TAG-A")` when sending the message.

[0099] When each service instance starts up, its message queue consumer client submits a subscription relationship to the Broker, subscribing only to messages that match its own tags. For example:

[0100] Consumer subscription for Example 1 (TAG-A): consumer.subscribe("PUSH_MSG", "TAG-A").

[0101] Consumer subscription for Example 2 (TAG-B): consumer.subscribe("PUSH_MSG", "TAG-B").

[0102] Consumer subscription for Example 3 (TAG-C): consumer.subscribe("PUSH_MSG", "TAG-C").

[0103] Thus, when a message carrying TAG-A is delivered to the Broker, the Broker will only push the message to the consumer of instance 1 according to the subscription relationship. Consumers of instance 2 and instance 3 will not receive the message at all, thereby achieving zero invalid consumption.

[0104] To ensure the message order of the same user, the producer can use the user identifier as a parameter of the partition selector (MessageQueueSelector) to ensure that all messages of the same user are delivered to the same message queue partition; the consumer uses a single thread to consume the partition, thereby ensuring the global order of messages.

[0105] V. Local Session Push and Anomaly Handling

[0106] After receiving the message, the consumer of the target service instance parses the target user identifier and message content from the message, and then looks up the user's PushSession object in the local session table (sessionMap). If found, the message is pushed to the front end by calling the session.push(message) method through the unified push abstraction layer. If not found (in very rare exceptional cases, such as when the user is going offline), the message is ignored and logged.

[0107] Before pushing, the service instance performs an idempotency check. Specifically, each message to be pushed is assigned a globally unique message identifier (e.g., messageId) upon generation. Upon receiving a message, the consumer first checks its local cache (e.g., Guava Cache) or Redis for a record with the key `msg:processed:{messageId}`. If it exists, the message has already been processed (possibly due to the message queue's "at least once" delivery semantics), and the consumer directly confirms successful message consumption without performing a push operation. If the message does not exist, the push operation continues, and upon successful push, the messageId is written to the cache with a reasonable expiration time (e.g., 5 minutes) to prevent duplicate pushes within a short period. This idempotency mechanism avoids the problem of users receiving duplicate messages due to network retries or duplicate message queue deliveries.

[0108] When an online push operation fails (e.g., due to network errors, session status errors, etc.), the system executes the following failure retry compensation process:

[0109] 1. Write the failed message and its associated information into the push failure message table of the database. The table structure includes the following fields: id (primary key), user_id (target user identifier), message_content (message content in JSON format), fail_reason (failure cause), retry_count (number of retries already performed), max_retry (maximum number of retries, default 5), next_retry_at (next retry time), status (status: 0 - pending retry, 1 - retry succeeded, 2 - final failure), created_at (record creation time). During initial writing, set retry_count=0, next_retry_at=current time + initial backoff interval (e.g., 30 seconds), status=0.

[0110] 2. Periodically (e.g., every 30 seconds) scan the failure message table through scheduled tasks (such as those based on PowerJob or Spring Scheduled), with the query condition being: status=0 AND retry_count<max_retry AND next_retry_at<=NOW(). For each pending retry message scanned, first check whether the Session of the target user is valid (i.e., query whether the user is online in Redis and whether the corresponding Session exists in the local session table). If the Session is valid, re-execute the push operation.

[0111] 3. If the re-push succeeds, update the status of the record to status=1 (retry succeeded), and the process ends.

[0112] 4. If the re-push still fails, increment the value of the retry_count field, and calculate the next retry time according to the exponential backoff strategy. For example, the backoff intervals are 30 seconds, 60 seconds, 120 seconds, 240 seconds, and 480 seconds in sequence, and the specific calculation can adopt next_retry_at=NOW()+(2^retry_count)*initial interval. Wait for the next scan after updating the record.

[0113] 5. If the number of retries for a certain message reaches the preset upper limit (retry_count>=max_retry), update the status of the message to status=2 (final failure), and trigger an alarm notification (such as sending an email or SMS) to remind operation and maintenance personnel to intervene manually. This mechanism prevents invalid messages from retrying infinitely and occupying system resources.

[0114] VI. Offline Message Persistence and Automatic Trigger upon Going Online

[0115] When the push service queries Redis during the tagged message routing step and finds that the target user is offline (i.e., GET user:tag:{userId} returns null), it persistently stores the message to be pushed in the offline message table of the database. The offline message table structure includes: id (primary key), user_id (target user identifier), message_content (message content, JSON format), message_type (message type), created_at (message creation time), and pushed (push status: 0 - pending push, 1 - pushed). The default value of pushed is 0 when writing messages.

[0116] When a user re-logs in (see the online registration process under User Connection Management and State Synchronization), the service instance immediately triggers the automatic offline message push process after completing the local session creation and Redis mapping write. Specifically:

[0117] 1. Query the offline message table to get all pending push records for this user: SELECT * FROM offline_message WHERE user_id=? AND pushed=0 ORDER BY created_at ASC.

[0118] 2. Push each item to the user through the unified push abstraction layer in the order of creation time.

[0119] 3. After each message is successfully pushed, update the pushed field of the record to 1, or delete the record directly.

[0120] 4. After all offline messages have been pushed, the user will enter the normal online push mode.

[0121] For example, if user A001 receives two messages while offline, after coming back online, instance 2 (TAG-B) will push these two messages to A001 in sequence, ensuring that offline messages are not lost and are in the correct order.

[0122] VII. Complete Process Integration

[0123] Based on the above steps, the method flow of this application will be described in detail below with a complete embodiment.

[0124] Cluster configuration:

[0125] Service Example 1: IP 192.168.1.10:8080, tag TAG-A.

[0126] Service Example 2: IP 192.168.1.11:8080, tag TAG-B.

[0127] Service Instance 3: IP 192.168.1.12:8080, TAG-C.

[0128] Message queue: RocketMQ, topic PUSH_MSG, each instance subscribes to TAG-A, TAG-B, and TAG-C respectively.

[0129] Global caching: Redis Sentinel mode 3-node cluster.

[0130] Database: MySQL, containing offline message tables and push failure message tables.

[0131] Scenario 1: User Login and Online Push Notifications

[0132] User A001 connects to the load balancer via WebSocket and is assigned to instance 1 (TAG-A). Instance 1 performs step S2: creates a local session, writes the Redis mapping user:tag:A001 = TAG-A, and adds A001 to online:users and instance:users:TAG-A.

[0133] The business module calls `PushService.push("A001", "hello")`. The push service executes step S3: it queries Redis to obtain TAG-A and sends the message with Tag=TAG-A to the RocketMQ `PUSH_MSG` topic. The consumer in instance 1 pulls the message (instances 2 and 3 do not consume it), and executes step S4: it finds the Session for A001 in the local session table and successfully pushes the message using the unified push interface. Simultaneously, idempotency verification passes, and the message ID is successfully cached.

[0134] Scenario 2: Offline Messages and Retry

[0135] When user A001 disconnects, instance 1 executes the offline process, clearing Redis mappings and local sessions. At this point, the business module pushes a message to A001, queries Redis return null, and the message is written to the offline message table.

[0136] Subsequently, A001 re-entered the network, and the connection was assigned to instance 2 (TAG-B). Instance 2 executed the online process, writing a new mapping user:tag:A001=TAG-B. After the online process was completed, instance 2 queried the offline message table, found offline messages for A001, pushed them successfully in order, and then deleted the offline record.

[0137] If instance 2 fails to push during online push due to network issues, the message will be written to the push failure message table. The scheduled task will scan for this record, check that A001 is online and the session is valid, re-push successfully, and update the status.

[0138] Scenario 3: Instance Failure

[0139] Instance 1 stopped sending heartbeats due to a system crash, and the `instance:heartbeat:TAG-A` value in Redis expired after 15 seconds. Upon detecting this, the monitoring component notified the load balancer to remove instance 1. If a push notification was sent to A001 (assuming its mapping was still TAG-A), the push service, after querying the mapping, found that `instance:heartbeat:TAG-A` had expired, determined that instance 1 was unavailable, treated A001 as offline, and switched to the offline message flow, waiting for the user to come back online before being pushed by a new instance. This mechanism ensures that a failed instance does not affect the final delivery of messages.

[0140] VIII. Correspondence between System Modules and Methods

[0141] In the system embodiments of this application, the correspondence between each module and the above method steps is as follows:

[0142] Service Instance Management Module: Responsible for tag allocation in step S1, generating or obtaining a unique tag when the instance starts, and registering it to the configuration center.

[0143] Connection Management Module: Located in each service instance, it is responsible for the creation, maintenance, and destruction of local session objects in step S2, as well as the triggering of online / offline events.

[0144] State synchronization module: responsible for global cache read and write operations in steps S2 and S4, including storing mapping relationships, updating online collections, and maintaining heartbeat information.

[0145] Message routing module: responsible for user status query and message routing decision in step S3, including calling the message queue API to set message tags.

[0146] The message push module is located in each service instance and is responsible for message consumption, local session lookup, unified push interface calls, and extended functions such as failure retry and idempotency verification in step S4.

[0147] The modules work together to achieve accurate and reliable message delivery based on tag-based routing.

[0148] IX. Other Implementation Methods

[0149] This application may also include the following optimized implementation methods:

[0150] For offline message tables and failure message tables, a table partitioning strategy (such as hash modulo by user ID or partitioning by time) can be adopted to cope with massive data scenarios.

[0151] An `expire_at` field can be added to the offline message table to automatically clean up unread offline messages that have exceeded a certain period of time (such as 7 days), preventing the data from growing indefinitely.

[0152] The exponential backoff strategy for retrying failed pushes can increase the random jitter factor to prevent a large number of failed messages from being retried at the same time, which would cause a spike in system pressure.

[0153] The embodiments of the aforementioned distributed long-connection message push method and the embodiments of the aforementioned distributed long-connection message push system are the same or related in terms of technical concept. They can be referred to and learned from each other in terms of technical details and technical effects, which will not be repeated here.

[0154] Overall, the advantages of this application compared to the prior art include:

[0155] 1. In a microservice architecture, the load balancer randomly distributes users' long-connection requests to different service instances, resulting in the same user's session being stored in different instances. When a business module needs to push a message to a specific user, the push request may reach an instance that does not hold the user's session, thus making it impossible to locate the target session. In existing technologies, the broadcast mode delivers all messages to the broadcast topic of the message queue, and each service instance needs to consume each message and determine locally whether it holds the target session. As the number of instances increases, each message is consumed repeatedly by all instances, and the amount of invalid message processing increases linearly, causing a serious broadcast storm and wasting CPU, memory, and network bandwidth resources. This application assigns a unique label to each service instance and maintains the mapping relationship between user identifiers and instance labels in Redis in real time. When pushing, the cache is first queried to obtain the instance label of the target user, and then the message is delivered to the message queue with the label, so that only the instance holding the label consumes the message, and other instances are completely unaware of the existence of the message, reducing the message consumption from O(N) in the broadcast mode to O(1), fundamentally eliminating the resource waste caused by the broadcast storm.

[0156] 2. Existing consistent hashing routing schemes map users to fixed instances using hash algorithms. While this solves the session location problem to some extent, it requires recalculating hashes and migrating a large number of existing connections when instances go offline or online, resulting in complexity and impacting the online user experience. This application adopts a tag-based routing approach. Adding a new service instance only requires assigning a new tag and subscribing to messages corresponding to that tag in the message queue. The existing tag and user mapping relationships of instances remain completely unaffected, requiring no rehashing or migration of any existing connections. During cluster elastic scaling, the push path for online users remains unchanged, with zero impact on user experience, significantly reducing operational complexity and the risks associated with system expansion.

[0157] 3. Existing push solutions typically lack reliable mechanisms for handling offline messages. When a user is offline, push messages may be lost. While some solutions can temporarily store offline messages, they require the user to actively retrieve them. This application, upon detecting a user's offline status in Redis, persistently stores the message in the database's offline message table. After the user re-establishes the connection and completes status registration, the service instance automatically queries the offline message table and pushes messages sequentially according to time. After a successful push, the corresponding record is deleted. This mechanism ensures zero message loss during user offline periods, and users can automatically receive offline messages upon returning to the internet without any active operation, achieving a complete closed loop from persistence to automatic push.

[0158] 4. Existing push notification solutions lack automatic retry and compensation mechanisms for failed pushes. Push failures caused by temporary network anomalies, session state fluctuations, etc., often result in direct message loss, failing to guarantee eventual delivery. This application addresses this by writing the failure message to a push failure message table, recording the user identifier, message content, reason for failure, number of retries, and next retry time. A scheduled task periodically scans for messages that meet the retry conditions, and re-pushes the message after confirming the user's session is valid. If successful, the record is deleted; otherwise, the retry interval is increased exponentially according to an exponential backoff strategy. This mechanism enables automatic recovery from push failures caused by momentary malfunctions without manual intervention, while the exponential backoff strategy avoids the additional pressure on the system caused by frequent retries.

[0159] 5. WebSocket and SSE, two long-connection protocols, differ significantly in interface specifications, session management, and message transmission methods. If business code directly calls the push interfaces of different protocols, independent push logic needs to be written for each protocol, increasing development and maintenance complexity. This application constructs a unified push abstraction layer on the backend service instance side, defining unified session management and message push interfaces, implementing adapters for WebSocket and SSE respectively. A factory class automatically creates the corresponding session object based on the actual protocol type established by the frontend. Business modules only need to call the unified push interface, without needing to know which long-connection protocol the frontend uses. The protocol differences are completely encapsulated within the abstraction layer, significantly reducing the complexity and maintenance cost of business code.

[0160] 6. In existing solutions, when a service instance crashes abnormally, the load balancer often fails to detect it in time and may still route new connections or push requests to the failed instance, leading to push failures or connection timeouts. This application addresses this by periodically writing heartbeat information with expiration dates to Redis from the instance. The heartbeat key automatically expires upon abnormal crashes. Simultaneously, leveraging the TTL mechanism of user-instance tag mapping in Redis, the mapping relationship corresponding to the failed instance automatically becomes invalid when the heartbeat expires. Subsequent push requests querying Redis will find that the target instance's heartbeat has expired, treating the corresponding user as offline and proceeding with the persistence process, thus avoiding invalid operations of delivering messages to the failed instance. This mechanism enables the system to have automatic fault detection and self-healing capabilities without the need for additional complex health check components.

[0161] Based on the same inventive concept, embodiments of this application also provide an electronic device. Figure 3 This is a structural block diagram of an electronic device provided in an embodiment of this application. Figure 3 As shown in the embodiments of this application, an electronic device includes: one or more processors 101, a memory 102, and one or more I / O interfaces 103. The memory 102 stores one or more programs, which, when executed by the one or more processors, enable the one or more processors to implement any of the distributed long-connection message push methods described in the above embodiments; the one or more I / O interfaces 103 are connected between the processor and the memory, configured to enable information interaction between the processor and the memory.

[0162] The processor 101 is a device with data processing capabilities, including but not limited to a central processing unit (CPU); the memory 102 is a device with data storage capabilities, including but not limited to random access memory (RAM, more specifically SDRAM, DDR, etc.), read-only memory (ROM), electrically erasable programmable read-only memory (EEPROM), and flash memory (FLASH); the I / O interface (read / write interface) 103 is connected between the processor 101 and the memory 102, and can realize information interaction between the processor 101 and the memory 102, including but not limited to a data bus (Bus).

[0163] In some embodiments, the processor 101, memory 102, and I / O interface 103 are interconnected via bus 104, and thus connected to other components of the computing device.

[0164] In some embodiments, the one or more processors 101 include a field-programmable gate array.

[0165] This application also provides a computer-readable medium. The computer-readable medium stores a computer program, which, when executed by a processor, implements the steps of any of the distributed long-connection message push methods described in the above embodiments. The computer-readable storage medium can be volatile or non-volatile.

[0166] This application also provides a computer program product, including computer-readable code, or a non-volatile computer-readable storage medium carrying computer-readable code. When the computer-readable code is run in the processor of an electronic device, the processor in the electronic device executes the above-described distributed long-connection message push method.

[0167] Those skilled in the art will understand that all or some of the steps, systems, and apparatuses disclosed above, and their functional modules / units, can be implemented as software, firmware, hardware, or suitable combinations thereof. In hardware implementations, the division between functional modules / units mentioned above does not necessarily correspond to the division of physical components; for example, a physical component may have multiple functions, or a function or step may be performed collaboratively by several physical components. Some or all physical components may be implemented as software executed by a processor, such as a central processing unit, digital signal processor, or microprocessor, or as hardware, or as an integrated circuit, such as an application-specific integrated circuit (ASIC). Such software can be distributed on a computer-readable storage medium, which may include computer storage media (or non-transitory media) and communication media (or transient media).

[0168] As is known to those skilled in the art, the term computer storage medium includes volatile and non-volatile, removable and non-removable media implemented in any method or technology for storing information, such as computer-readable program instructions, data structures, program modules, or other data. Computer storage media includes, but is not limited to, random access memory (RAM), read-only memory (ROM), erasable programmable read-only memory (EPROM), static random access memory (SRAM), flash memory or other memory technologies, portable compact disc read-only memory (CD-ROM), digital versatile disc (DVD) or other optical disc storage, magnetic cartridges, magnetic tape, disk storage or other magnetic storage devices, or any other medium that can be used to store desired information and is accessible to a computer. Furthermore, it is known to those skilled in the art that communication media typically contain computer-readable program instructions, data structures, program modules, or other data in modulated data signals such as carrier waves or other transmission mechanisms, and may include any information delivery medium.

[0169] The computer-readable program instructions described herein can be downloaded from computer-readable storage media to various computing / processing devices, or downloaded via a network, such as the Internet, local area network, wide area network, and / or wireless network, to an external computer or external storage device. The network may include copper transmission cables, fiber optic transmission, wireless transmission, routers, firewalls, switches, gateway computers, and / or edge servers. A network adapter card or network interface in each computing / processing device receives the computer-readable program instructions from the network and forwards them to the computer-readable storage media in the respective computing / processing device.

[0170] The computer program instructions used to perform the operations of this application may be assembly instructions, instruction set architecture (ISA) instructions, machine instructions, machine-dependent instructions, microcode, firmware instructions, status setting data, or source code or object code written in any combination of one or more programming languages, including object-oriented programming languages ​​such as Smalltalk, C++, etc., and conventional procedural programming languages ​​such as the "C" language or similar programming languages. The computer-readable program instructions may be executed entirely on the user's computer, partially on the user's computer, as a standalone software package, partially on the user's computer and partially on a remote computer, or entirely on a remote computer or server. In cases involving a remote computer, the remote computer may be connected to the user's computer via any type of network—including a local area network (LAN) or a wide area network (WAN)—or may be connected to an external computer (e.g., via the Internet using an Internet service provider). In some embodiments, electronic circuits, such as programmable logic circuits, field-programmable gate arrays (FPGAs), or programmable logic arrays (PLAs), are personalized by utilizing the status information of the computer-readable program instructions. These electronic circuits can execute the computer-readable program instructions to implement various aspects of this application.

[0171] The computer program product described herein can be implemented specifically through hardware, software, or a combination thereof. In one alternative embodiment, the computer program product is specifically embodied in a computer storage medium; in another alternative embodiment, the computer program product is specifically embodied in a software product, such as a software development kit (SDK), etc.

[0172] Various aspects of this application are described herein with reference to flowchart illustrations and / or block diagrams of methods, apparatus (systems), and computer program products according to embodiments of this application. It should be understood that each block of the flowchart illustrations and / or block diagrams, and combinations of blocks in the flowchart illustrations and / or block diagrams, can be implemented by computer-readable program instructions.

[0173] These computer-readable program instructions can be provided to a processor of a general-purpose computer, a special-purpose computer, or other programmable data processing apparatus to produce a machine such that, when executed by the processor of the computer or other programmable data processing apparatus, they create means for implementing the functions / actions specified in one or more blocks of the flowchart and / or block diagram. These computer-readable program instructions can also be stored in a computer-readable storage medium that causes a computer, programmable data processing apparatus, and / or other device to operate in a particular manner; thus, the computer-readable medium storing the instructions comprises an article of manufacture that includes instructions for implementing aspects of the functions / actions specified in one or more blocks of the flowchart and / or block diagram.

[0174] Computer-readable program instructions may also be loaded onto a computer, other programmable data processing apparatus, or other device to cause a series of operational steps to be performed on the computer, other programmable data processing apparatus, or other device to produce a computer-implemented process, thereby causing the instructions executed on the computer, other programmable data processing apparatus, or other device to perform the functions / actions specified in one or more boxes of a flowchart and / or block diagram.

[0175] The flowcharts and block diagrams in the accompanying drawings illustrate the architecture, functionality, and operation of possible implementations of systems, methods, and computer program products according to various embodiments of this application. In this regard, each block in a flowchart or block diagram may represent a module, segment, or portion of an instruction containing one or more executable instructions for implementing a specified logical function. In some alternative implementations, the functions marked in the blocks may occur in a different order than those marked in the drawings. For example, two consecutive blocks may actually be executed substantially in parallel, and they may sometimes be executed in reverse order, depending on the functions involved. It should also be noted that each block in the block diagrams and / or flowcharts, and combinations of blocks in the block diagrams and / or flowcharts, can be implemented using a dedicated hardware-based system that performs the specified function or action, or using a combination of dedicated hardware and computer instructions.

[0176] Exemplary embodiments have been disclosed in this application, and while specific terminology has been used, it is used only and should be interpreted in a general illustrative sense and is not intended to be limiting. In some embodiments, it will be apparent to those skilled in the art that features, characteristics, and / or elements described in conjunction with particular embodiments may be used alone, or in combination with features, characteristics, and / or elements described in conjunction with other embodiments, unless otherwise expressly indicated. Therefore, those skilled in the art will understand that various changes in form and detail may be made without departing from the scope of this application as set forth by the appended claims.

Claims

1. A distributed long-connection message push method based on tag-based routing, characterized in that, include: Step S1: Assign a unique instance label to each service instance in the distributed cluster; Step S2: In response to the target user establishing a long connection through the target service instance, create a local session object for the target user and store the mapping relationship between the user identifier of the target user and the instance tag of the target service instance in the global cache; Step S3: In response to receiving a push request for the target user, query the global cache to obtain the instance tag corresponding to the user identifier, and route the message to be pushed to the target service instance according to the instance tag; Step S4: The target service instance pushes the message to be pushed to the target user through the local session object according to the mapping relationship.

2. The distributed long-connection message push method according to claim 1, characterized in that, The long-lived connection includes the WebSocket protocol and the SSE protocol; The distributed long-connection message push method further includes: building a unified push abstraction layer on the service instance side; The unified push abstraction layer is used to shield the interface differences between the WebSocket protocol and the SSE protocol, and to provide a unified session management interface and message push interface for upper-layer services.

3. The distributed long-connection message push method according to claim 1, characterized in that, It also includes a failure retry compensation step, specifically including: When the target service instance fails to push the message to be pushed through the local session object, the message to be pushed and its associated retry information are written into the failure message storage unit. The scheduled task scans for failure messages in the pending retry state based on the retry information, and re-executes the push operation when the target user's local session object is valid.

4. The distributed long-connection message push method according to claim 1, characterized in that, When the target user goes offline, the target service instance destroys the corresponding local session object and deletes the mapping relationship from the global cache; When the target user comes back online, the local session object and mapping relationship are rebuilt through a new service instance, and the offline message storage unit is queried to obtain and push offline messages generated during the target user's offline period.

5. The distributed long-connection message push method according to claim 1, characterized in that, The service instance periodically sends heartbeat information to the global cache. The heartbeat information carries the instance tag of the service instance and has an expiration date. If the global cache does not receive heartbeat information from the service instance within the validity period, the service instance is determined to be in an abnormal state, and the instance failure handling process is triggered.

6. The distributed long-connection message push method according to claim 1, characterized in that, The step of routing the message to be pushed to the target service instance based on the instance tag specifically includes: The message to be pushed is sent to the message queue system, and a message tag corresponding to the instance tag is set for the message; The target service instance consumes the message to be pushed by subscribing to message tags in the message queue system that match its own instance tag.

7. The distributed long-connection message push method according to claim 3, characterized in that, The message records in the failure message storage unit include the number of retries and the next retry time; During the scheduled task scan, only message records are obtained where the number of retries has not exceeded the preset limit and the next retry time is earlier than the current time. For messages that exceed the preset limit on the number of retries, they are marked as final failures and an alarm is triggered.

8. The distributed long-connection message push method according to claim 1, characterized in that, The message to be pushed contains a globally unique message identifier; Before consuming and pushing the message to be pushed, the target service instance also includes: Based on the globally unique message identifier, an idempotency check is performed in the local cache or global cache. If it is determined that the message to be pushed has already been processed, the current push operation is ignored.

9. A system capable of implementing the distributed long-connection message push method according to any one of claims 1-8, characterized in that, include: The service instance management module is used to assign a unique instance tag to each service instance in the distributed cluster. The connection management module, located in the service instance, is used to create a local session object for the target user in response to the target user establishing a long connection through the target service instance. The state synchronization module is used to store the mapping relationship between the user identifier of the target user and the instance tag of the target service instance in the global cache; The message routing module is used to respond to receiving a push request for the target user, query the global cache to obtain the instance tag corresponding to the user identifier, and route the message to be pushed to the target service instance according to the instance tag; The message push module, located in the target service instance, is used to push the message to be pushed to the target user through the local session object according to the mapping relationship.

10. A computer-readable medium having a computer program stored thereon, characterized in that, When the computer program is executed by the processor, it can implement the steps of the distributed long-connection message push method according to any one of claims 1 to 8.