| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299 |
- using System;
- using System.Threading;
- using System.Threading.Tasks;
- using BeiJingComService.Infrastructure;
- namespace BeiJingComService.Core
- {
- /// <summary>
- /// 网关宿主:管理 ComGateway 的生命周期(初始化、重启、关闭),
- /// 并提供健康状态供 HTTP /health 与诊断面板使用。
- /// </summary>
- public sealed class GatewayHost
- {
- private static readonly Lazy<GatewayHost> _instance =
- new Lazy<GatewayHost>(() => new GatewayHost());
- public static GatewayHost Instance
- {
- get { return _instance.Value; }
- }
- private readonly object _sync = new object();
- private ComGateway _gateway;
- private ComGateway _gatewaySecondary;
- private string _lastError;
- private long _invokeCount;
- private DateTime? _lastInvokeTime;
- private long _lastElapsedMs;
- /// <summary>初始化失败时触发(参数为错误信息),供托盘与诊断面板提示。</summary>
- public event Action<string> InitializeFailed;
- /// <summary>网关重建完成后触发。</summary>
- public event Action Reinitialized;
- public bool IsInitialized
- {
- get { return _gateway != null && _gateway.IsInitialized; }
- }
- public int PendingCount
- {
- get { return _gateway != null ? _gateway.PendingCount : 0; }
- }
- public bool IsFaulted
- {
- get { return _gateway != null && _gateway.IsFaulted; }
- }
- public string LastError
- {
- get { return _lastError; }
- }
- public long InvokeCount
- {
- get { return Interlocked.Read(ref _invokeCount); }
- }
- public DateTime? LastInvokeTime
- {
- get { return _lastInvokeTime; }
- }
- public long LastElapsedMs
- {
- get { return _lastElapsedMs; }
- }
- public string ProgId
- {
- get { return _gateway != null ? _gateway.ProgId : AppConfig.ComProgId; }
- }
- /// <summary>次要 COM 组件 ProgID(未配置时为空串)。</summary>
- public string ProgIdSecondary
- {
- get { return AppConfig.ComProgIdSecondary; }
- }
- /// <summary>是否配置了次要 COM 组件。</summary>
- public bool IsSecondaryConfigured
- {
- get { return !string.IsNullOrWhiteSpace(AppConfig.ComProgIdSecondary); }
- }
- /// <summary>次要 COM 网关是否已就绪。</summary>
- public bool IsSecondaryInitialized
- {
- get { return _gatewaySecondary != null && _gatewaySecondary.IsInitialized; }
- }
- public void Initialize()
- {
- lock (_sync)
- {
- if (_gateway != null && _gateway.IsInitialized &&
- (!IsSecondaryConfigured || IsSecondaryInitialized)) return;
- DisposeGateway();
- _gateway = new ComGateway();
- _gateway.Initialize();
- InitializeSecondary();
- _lastError = null;
- Logger.Info("GatewayHost 初始化完成");
- }
- }
- /// <summary>按需初始化次要 COM 网关;失败只记录日志,不影响主网关。</summary>
- private void InitializeSecondary()
- {
- if (!IsSecondaryConfigured)
- {
- _gatewaySecondary = null;
- return;
- }
- try
- {
- _gatewaySecondary = new ComGateway(AppConfig.ComProgIdSecondary);
- _gatewaySecondary.Initialize();
- Logger.Info("次要 COM 网关初始化成功: " + AppConfig.ComProgIdSecondary);
- }
- catch (Exception ex)
- {
- _gatewaySecondary = null;
- Logger.Error("次要 COM 组件初始化失败,将不可用: " + AppConfig.ComProgIdSecondary, ex);
- }
- }
- public void Reinitialize()
- {
- lock (_sync)
- {
- Logger.Info("GatewayHost 重建网关开始");
- DisposeGateway();
- _gateway = new ComGateway();
- _gateway.Initialize();
- InitializeSecondary();
- _lastError = null;
- Logger.Info("GatewayHost 重建网关完成");
- }
- var handler = Reinitialized;
- if (handler != null) handler();
- }
- /// <summary>后台初始化,失败时通过事件通知,不抛异常(托盘场景下不能因初始化失败而退出)。</summary>
- public void InitializeInBackground()
- {
- Task.Run(() =>
- {
- try
- {
- Initialize();
- }
- catch (Exception ex)
- {
- _lastError = ex.Message;
- Logger.Error("后台初始化网关失败", ex);
- var handler = InitializeFailed;
- if (handler != null) handler(ex.Message);
- }
- });
- }
- /// <summary>
- /// 单笔调用的唯一入口:所有传输协议(HTTP、诊断面板、后续新增协议)都必须经过这里,
- /// 调用计数、摘要日志与报文日志在此统一处理,避免各处重复埋点。
- /// keepSession=true 表示这一笔之后不空闲关会话(只 Open 一次,测试用),随请求走,不是全局开关。
- /// </summary>
- public Task<ComResult> ExecuteAsync(string func, string[] args, int timeoutMs = 0, bool keepSession = false)
- {
- return ExecuteAsync(func, args, null, timeoutMs, keepSession);
- }
- /// <summary>
- /// 指定 ProgID 的调用入口;progId 为空时使用主组件(MedicareCom.Outpatient)。
- /// </summary>
- public async Task<ComResult> ExecuteAsync(string func, string[] args, string progId,
- int timeoutMs = 0, bool keepSession = false)
- {
- ComGateway gateway = ResolveGateway(progId);
- ComResult result;
- if (gateway == null || !gateway.IsInitialized)
- {
- result = ComResult.Fail(-3, "网关未初始化,请先确认 COM 组件已安装"
- + (string.IsNullOrWhiteSpace(progId) ? "" : "(ProgID=" + progId + ")"));
- }
- else
- {
- try
- {
- result = await gateway.InvokeAsync(func, args, timeoutMs, keepSession).ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- Logger.Error("执行 COM 调用异常", ex);
- result = ComResult.Fail(-1, "调用执行异常: " + ex.Message);
- }
- }
- Interlocked.Increment(ref _invokeCount);
- _lastInvokeTime = DateTime.Now;
- _lastElapsedMs = result.ElapsedMs;
- LogInvoke(func, args, result);
- return result;
- }
- public ComResult Execute(string func, string[] args, int timeoutMs = 0, bool keepSession = false)
- {
- return ExecuteAsync(func, args, timeoutMs, keepSession).GetAwaiter().GetResult();
- }
- /// <summary>
- /// 设置主网关是否在会话空闲后自动关闭。
- ///
- /// 【Round49 起不再是主路径】常规请求请改用 ExecuteAsync / ReadAsync 的 keepSession 参数
- /// (随请求走,不会泄漏到其它入口)。本方法保留给诊断面板做"强制常驻/强制关闭"的兜底开关,
- /// 设置后对之后的所有空闲判定生效,直到再次被设置。
- /// </summary>
- public void SetSessionKeepOpen(bool keepOpen)
- {
- ComGateway gateway = _gateway;
- if (gateway != null) gateway.AllowIdleClose = !keepOpen;
- }
- /// <summary>按 ProgID 选择网关:空=主组件;等于主/次 ProgID 时返回对应网关;未配置返回 null。</summary>
- private ComGateway ResolveGateway(string progId)
- {
- if (string.IsNullOrWhiteSpace(progId)) return _gateway;
- if (string.Equals(progId, AppConfig.ComProgId, StringComparison.OrdinalIgnoreCase)) return _gateway;
- if (IsSecondaryConfigured &&
- string.Equals(progId, AppConfig.ComProgIdSecondary, StringComparison.OrdinalIgnoreCase))
- return _gatewaySecondary;
- Logger.Error("请求了未配置的 COM ProgID: " + progId);
- return null;
- }
- /// <summary>摘要进 *_Gateway.log,调用原文进 *_Trade.log(脱敏后)。</summary>
- private void LogInvoke(string func, string[] args, ComResult result)
- {
- try
- {
- string input = args == null || args.Length == 0 ? "" : string.Join("\n", args);
- Logger.Invoke(func, result.ElapsedMs, result.Success);
- TradeLogger.Write(func, input, result.Output, result.Code, result.Message, result.ElapsedMs, result.Success);
- }
- catch (Exception ex)
- {
- // 日志记录失败绝不能影响调用结果返回
- Logger.Error("记录调用日志失败", ex);
- }
- }
- public void Shutdown()
- {
- lock (_sync)
- {
- DisposeGateway();
- Logger.Info("GatewayHost 已关闭");
- }
- }
- private void DisposeGateway()
- {
- if (_gateway != null)
- {
- try
- {
- _gateway.Dispose();
- }
- catch (Exception ex)
- {
- Logger.Error("释放网关异常", ex);
- }
- _gateway = null;
- }
- if (_gatewaySecondary != null)
- {
- try
- {
- _gatewaySecondary.Dispose();
- }
- catch (Exception ex)
- {
- Logger.Error("释放次要网关异常", ex);
- }
- _gatewaySecondary = null;
- }
- }
- }
- }
|