跳到主要内容

客户端冗余 Server 切换

客户端一侧的重连选路: 有多个服务端地址时, 当前连不通就换下一个, 换到后重建订阅. 这是客户端的选路, 不是服务器高可用, 也不构成主备冗余的承诺. 用 C# 示例.

配套示例

完整代码​

using DarraOpcUa_Client;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

class FailoverClient : IDisposable
{
private readonly string[] _endpoints;
private readonly IReadOnlyList<string> _tags;
private DarraOpcUa _ua;
private OpcUaSubscription _sub;
private int _currentIdx = -1;
private readonly object _lock = new();

public FailoverClient(IReadOnlyList<string> tags, params string[] endpoints)
{
_tags = tags;
_endpoints = endpoints;
}

public void Connect()
{
lock (_lock)
{
// 从下一个 endpoint 开始尝试 (避免反复连同一个故障点)
for (int tries = 0; tries < _endpoints.Length; tries++)
{
_currentIdx = (_currentIdx + 1) % _endpoints.Length;
var ep = _endpoints[_currentIdx];
try
{
_ua = new DarraOpcUa(ep);
_ua.Events.CommunicationError += OnCommError;
_ua.Connect();
Console.WriteLine($"[OK] 已连接 {ep}");
Resubscribe();
return;
}
catch (OpcUaException ex)
{
Console.WriteLine($" {ep} 连接失败: {ex.StatusCode}");
_ua?.Dispose();
_ua = null;
}
}
throw new Exception("所有 endpoint 都不可达");
}
}

private void Resubscribe()
{
_sub = _ua.CreateSubscription(500);
_sub.DataChanged += (s, e) =>
Console.WriteLine($" {e.NodeId} = {e.ValueString} [{e.Status}]");
_sub.AddMany(_tags);
}

private void OnCommError(object sender, CommunicationErrorEventArgs e)
{
Console.WriteLine($"\n[!!] 通讯异常 {e.StatusCode}, 切换 server...");
Task.Run(() =>
{
try { _sub?.Dispose(); } catch (Exception ex) { Console.WriteLine($"释放订阅失败: {ex.Message}"); }
try { _ua?.Dispose(); } catch (Exception ex) { Console.WriteLine($"释放会话失败: {ex.Message}"); }
Thread.Sleep(2000); // 等故障检测稳定, 避免反复切换抖动
try { Connect(); }
catch (Exception ex) { Console.WriteLine($"切换失败: {ex.Message}, 30 秒后重试"); }
});
}

public void Dispose() { _sub?.Dispose(); _ua?.Dispose(); }
}

class Program
{
static async Task Main()
{
var tags = new[] { "ns=2;s=Boiler1.Temperature", "ns=2;s=Boiler1.Pressure" };

using var client = new FailoverClient(
tags,
"opc.tcp://primary:4840",
"opc.tcp://backup:4840");

client.Connect();

Console.WriteLine("\n运行中. 断开当前 endpoint 的网络测试切换. Ctrl+C 退出.\n");
await Task.Delay(Timeout.Infinite);
}
}

代码要点​

  • CommunicationError 在通讯异常时触发, 客户端不需要自己发探测; 触发后按本例换 endpoint 重连
  • 切换前 Thread.Sleep(2000) backoff 是为了过滤网络瞬断, 不加会来回抖, 生产环境建议改指数退避
  • _currentIdx = (_currentIdx + 1) % _endpoints.Length 从下一个 endpoint 开始尝试, 避免反复连同一故障点
  • 换 endpoint 后旧 Session / Subscription 全部失效, 必须 CreateSubscription + AddMany 重建; TransferSubscriptions 需要目标端能认出原订阅, 多数部署不满足
  • 各 endpoint 的 NamespaceArray 必须一致, 否则 ns=2;... 换过去可能映射到完全不同的节点

注意事项​

  • 各 endpoint 必须同一 NamespaceArray (NodeId 解析一致), 否则切换后 ns=2;... 可能映射到完全不同的节点.
  • 要更快检测通讯异常, 用 Modify(...) 调小 maxKeepAliveCount, 但太小会误判.
  • 长期运行还要处理"下一个 endpoint 也挂了"的连环失败, 上面代码用循环索引 + 异常重试覆盖.

相关链接​