Apache ActiveMQ优先级主备切换检测(C# NMS实现)
检测ActiveMQ Failover切换事件的实现方案
针对你使用Apache.NMS.ActiveMQ 1.8.0的场景,完全可以通过监听FailoverTransport的内置事件来捕获服务器切换行为,具体实现步骤如下:
核心思路
FailoverTransport是NMS中负责故障转移的核心组件,它提供了两个关键事件用于监控连接状态变化:
TransportInterrupted:当前连接断开时触发(比如主服务器离线)TransportResumed:成功切换到备用服务器或主服务器恢复重连后触发
结合这两个事件,再通过获取当前连接的Broker地址,就能精准判断服务器切换的发生及目标节点。
代码实现示例
using Apache.NMS; using Apache.NMS.ActiveMQ; using Apache.NMS.ActiveMQ.Transport.Failover; // 初始化连接工厂 var factory = new ConnectionFactory("failover:(tcp://mainServer:61619,tcp://backup1:61619,tcp://backup2:61619)?randomize=false&timeout=10000&backup=true&priorityBackup=true&useExponentialBackOff=true&reconnectDelayExponent=2.0&initialReconnectDelay=5000&initialReconnectDelay=180000&consumerExpiryCheckEnabled=false"); // 创建连接 var connection = factory.CreateConnection(); connection.Start(); // 获取FailoverTransport实例 if (connection is ActiveMQConnection activeMqConn) { var failoverTransport = activeMqConn.Transport as FailoverTransport; if (failoverTransport != null) { string currentBrokerAddress = activeMqConn.RemoteAddress.ToString(); Console.WriteLine($"当前连接Broker: {currentBrokerAddress}"); // 订阅连接断开事件 failoverTransport.TransportInterrupted += (sender, args) => { Console.WriteLine($"连接断开: {currentBrokerAddress}"); }; // 订阅连接恢复/切换事件 failoverTransport.TransportResumed += (sender, args) => { var newBrokerAddress = activeMqConn.RemoteAddress.ToString(); if (newBrokerAddress != currentBrokerAddress) { Console.WriteLine($"已切换至新Broker: {newBrokerAddress}"); currentBrokerAddress = newBrokerAddress; } else { Console.WriteLine($"原Broker连接恢复: {currentBrokerAddress}"); } }; } } // 后续业务逻辑...
注意事项
- 事件线程安全:
TransportInterrupted和TransportResumed事件由后台线程触发,若需要更新UI或操作共享资源,需做好线程同步(比如使用Dispatcher.Invoke在WPF/WinForms中切换到UI线程)。 - 连接状态校验:在
TransportResumed事件中,建议额外校验连接的IsStarted状态,确保连接确实可用。 - 版本兼容性:该方案适配你使用的Apache.NMS.ActiveMQ 1.8.0版本,与Broker 5.16.4无兼容性问题。
内容的提问来源于stack exchange,提问作者Liam
相关产品推荐
相关产品推荐

