본문으로 건너뛰기

클라이언트 중복 서버 전환

클라이언트 측의 재연결 경로 선택: 서버 주소가 여러 개인 경우, 현재 연결이 되지 않으면 다음 주소로 전환하고, 전환 후 구독을 다시 설정합니다. 이는 클라이언트 측의 경로 선택이며, 서버의 고가용성을 보장하는 것이 아니며, 주-백업 중복 구성을 약속하는 것도 아닙니다. ~를 사용하여 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)
{
// 다음 엔드포인트부터 시도하기 (동일한 오류 지점에 반복적으로 연결되는 것을 방지하기 위해)
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 통신 오류가 발생했을 때 트리거되며, 클라이언트가 직접 탐지 요청을 보낼 필요가 없습니다. 트리거된 후에는 이 예시와 같이 엔드포인트를 변경하여 재연결합니다.
  • 전환 전, Thread.Sleep(2000) 백오프는 네트워크 일시적 단절을 필터링하기 위한 것으로, 이를 적용하지 않으면 신호가 불안정해집니다. 운영 환경에서는 지수 백오프를 적용하는 것이 좋습니다.
  • _currentIdx = (_currentIdx + 1) % _endpoints.Length 다음 엔드포인트부터 시도하여, 동일한 오류 지점에 반복적으로 연결되는 것을 피하십시오.
  • 엔드포인트를 변경하면 기존 세션/구독이 모두 무효화되므로, 반드시 CreateSubscription + AddMany 재설정해야 합니다. 대상 측에서 기존 구독을 인식할 수 TransferSubscriptions 있어야 하는데, 대부분의 배포 환경에서는 이 조건을 충족하지 못합니다.
  • 각 엔드포인트의 NamespaceArray 는 일치해야 하며, 그렇지 않으면 ns=2;... 로 전환했을 때 완전히 다른 노드로 매핑될 수 있습니다.

주의사항​

  • 각 엔드포인트는 반드시동일한 NamespaceArray (NodeId 일관성), 그렇지 않으면 전환 후 완전히 다른 노드로 매핑될 ns=2;... 수 있습니다.
  • 통신 이상을 더 빨리 감지하려면 값을 Modify(...) 줄이세요 maxKeepAliveCount. 하지만 너무 작게 설정하면 오탐이 발생할 수 있습니다.
  • 장기간 운영 시 "다음 엔드포인트도 다운되었다"는 연쇄적인 오류를 처리해야 하는데, 위 코드에서는 루프 인덱싱과 예외 재시도를 통해 이를 해결하고 있습니다.

관련 링크​