GatewayHost.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using BeiJingComService.Infrastructure;
  5. namespace BeiJingComService.Core
  6. {
  7. /// <summary>
  8. /// 网关宿主:管理 ComGateway 的生命周期(初始化、重启、关闭),
  9. /// 并提供健康状态供 HTTP /health 与诊断面板使用。
  10. /// </summary>
  11. public sealed class GatewayHost
  12. {
  13. private static readonly Lazy<GatewayHost> _instance =
  14. new Lazy<GatewayHost>(() => new GatewayHost());
  15. public static GatewayHost Instance
  16. {
  17. get { return _instance.Value; }
  18. }
  19. private readonly object _sync = new object();
  20. private ComGateway _gateway;
  21. private ComGateway _gatewaySecondary;
  22. private string _lastError;
  23. private long _invokeCount;
  24. private DateTime? _lastInvokeTime;
  25. private long _lastElapsedMs;
  26. /// <summary>初始化失败时触发(参数为错误信息),供托盘与诊断面板提示。</summary>
  27. public event Action<string> InitializeFailed;
  28. /// <summary>网关重建完成后触发。</summary>
  29. public event Action Reinitialized;
  30. public bool IsInitialized
  31. {
  32. get { return _gateway != null && _gateway.IsInitialized; }
  33. }
  34. public int PendingCount
  35. {
  36. get { return _gateway != null ? _gateway.PendingCount : 0; }
  37. }
  38. public bool IsFaulted
  39. {
  40. get { return _gateway != null && _gateway.IsFaulted; }
  41. }
  42. public string LastError
  43. {
  44. get { return _lastError; }
  45. }
  46. public long InvokeCount
  47. {
  48. get { return Interlocked.Read(ref _invokeCount); }
  49. }
  50. public DateTime? LastInvokeTime
  51. {
  52. get { return _lastInvokeTime; }
  53. }
  54. public long LastElapsedMs
  55. {
  56. get { return _lastElapsedMs; }
  57. }
  58. public string ProgId
  59. {
  60. get { return _gateway != null ? _gateway.ProgId : AppConfig.ComProgId; }
  61. }
  62. /// <summary>次要 COM 组件 ProgID(未配置时为空串)。</summary>
  63. public string ProgIdSecondary
  64. {
  65. get { return AppConfig.ComProgIdSecondary; }
  66. }
  67. /// <summary>是否配置了次要 COM 组件。</summary>
  68. public bool IsSecondaryConfigured
  69. {
  70. get { return !string.IsNullOrWhiteSpace(AppConfig.ComProgIdSecondary); }
  71. }
  72. /// <summary>次要 COM 网关是否已就绪。</summary>
  73. public bool IsSecondaryInitialized
  74. {
  75. get { return _gatewaySecondary != null && _gatewaySecondary.IsInitialized; }
  76. }
  77. public void Initialize()
  78. {
  79. lock (_sync)
  80. {
  81. if (_gateway != null && _gateway.IsInitialized &&
  82. (!IsSecondaryConfigured || IsSecondaryInitialized)) return;
  83. DisposeGateway();
  84. _gateway = new ComGateway();
  85. _gateway.Initialize();
  86. InitializeSecondary();
  87. _lastError = null;
  88. Logger.Info("GatewayHost 初始化完成");
  89. }
  90. }
  91. /// <summary>按需初始化次要 COM 网关;失败只记录日志,不影响主网关。</summary>
  92. private void InitializeSecondary()
  93. {
  94. if (!IsSecondaryConfigured)
  95. {
  96. _gatewaySecondary = null;
  97. return;
  98. }
  99. try
  100. {
  101. _gatewaySecondary = new ComGateway(AppConfig.ComProgIdSecondary);
  102. _gatewaySecondary.Initialize();
  103. Logger.Info("次要 COM 网关初始化成功: " + AppConfig.ComProgIdSecondary);
  104. }
  105. catch (Exception ex)
  106. {
  107. _gatewaySecondary = null;
  108. Logger.Error("次要 COM 组件初始化失败,将不可用: " + AppConfig.ComProgIdSecondary, ex);
  109. }
  110. }
  111. public void Reinitialize()
  112. {
  113. lock (_sync)
  114. {
  115. Logger.Info("GatewayHost 重建网关开始");
  116. DisposeGateway();
  117. _gateway = new ComGateway();
  118. _gateway.Initialize();
  119. InitializeSecondary();
  120. _lastError = null;
  121. Logger.Info("GatewayHost 重建网关完成");
  122. }
  123. var handler = Reinitialized;
  124. if (handler != null) handler();
  125. }
  126. /// <summary>后台初始化,失败时通过事件通知,不抛异常(托盘场景下不能因初始化失败而退出)。</summary>
  127. public void InitializeInBackground()
  128. {
  129. Task.Run(() =>
  130. {
  131. try
  132. {
  133. Initialize();
  134. }
  135. catch (Exception ex)
  136. {
  137. _lastError = ex.Message;
  138. Logger.Error("后台初始化网关失败", ex);
  139. var handler = InitializeFailed;
  140. if (handler != null) handler(ex.Message);
  141. }
  142. });
  143. }
  144. /// <summary>
  145. /// 单笔调用的唯一入口:所有传输协议(HTTP、诊断面板、后续新增协议)都必须经过这里,
  146. /// 调用计数、摘要日志与报文日志在此统一处理,避免各处重复埋点。
  147. /// keepSession=true 表示这一笔之后不空闲关会话(只 Open 一次,测试用),随请求走,不是全局开关。
  148. /// </summary>
  149. public Task<ComResult> ExecuteAsync(string func, string[] args, int timeoutMs = 0, bool keepSession = false)
  150. {
  151. return ExecuteAsync(func, args, null, timeoutMs, keepSession);
  152. }
  153. /// <summary>
  154. /// 指定 ProgID 的调用入口;progId 为空时使用主组件(MedicareCom.Outpatient)。
  155. /// </summary>
  156. public async Task<ComResult> ExecuteAsync(string func, string[] args, string progId,
  157. int timeoutMs = 0, bool keepSession = false)
  158. {
  159. ComGateway gateway = ResolveGateway(progId);
  160. ComResult result;
  161. if (gateway == null || !gateway.IsInitialized)
  162. {
  163. result = ComResult.Fail(-3, "网关未初始化,请先确认 COM 组件已安装"
  164. + (string.IsNullOrWhiteSpace(progId) ? "" : "(ProgID=" + progId + ")"));
  165. }
  166. else
  167. {
  168. try
  169. {
  170. result = await gateway.InvokeAsync(func, args, timeoutMs, keepSession).ConfigureAwait(false);
  171. }
  172. catch (Exception ex)
  173. {
  174. Logger.Error("执行 COM 调用异常", ex);
  175. result = ComResult.Fail(-1, "调用执行异常: " + ex.Message);
  176. }
  177. }
  178. Interlocked.Increment(ref _invokeCount);
  179. _lastInvokeTime = DateTime.Now;
  180. _lastElapsedMs = result.ElapsedMs;
  181. LogInvoke(func, args, result);
  182. return result;
  183. }
  184. public ComResult Execute(string func, string[] args, int timeoutMs = 0, bool keepSession = false)
  185. {
  186. return ExecuteAsync(func, args, timeoutMs, keepSession).GetAwaiter().GetResult();
  187. }
  188. /// <summary>
  189. /// 设置主网关是否在会话空闲后自动关闭。
  190. ///
  191. /// 【Round49 起不再是主路径】常规请求请改用 ExecuteAsync / ReadAsync 的 keepSession 参数
  192. /// (随请求走,不会泄漏到其它入口)。本方法保留给诊断面板做"强制常驻/强制关闭"的兜底开关,
  193. /// 设置后对之后的所有空闲判定生效,直到再次被设置。
  194. /// </summary>
  195. public void SetSessionKeepOpen(bool keepOpen)
  196. {
  197. ComGateway gateway = _gateway;
  198. if (gateway != null) gateway.AllowIdleClose = !keepOpen;
  199. }
  200. /// <summary>按 ProgID 选择网关:空=主组件;等于主/次 ProgID 时返回对应网关;未配置返回 null。</summary>
  201. private ComGateway ResolveGateway(string progId)
  202. {
  203. if (string.IsNullOrWhiteSpace(progId)) return _gateway;
  204. if (string.Equals(progId, AppConfig.ComProgId, StringComparison.OrdinalIgnoreCase)) return _gateway;
  205. if (IsSecondaryConfigured &&
  206. string.Equals(progId, AppConfig.ComProgIdSecondary, StringComparison.OrdinalIgnoreCase))
  207. return _gatewaySecondary;
  208. Logger.Error("请求了未配置的 COM ProgID: " + progId);
  209. return null;
  210. }
  211. /// <summary>摘要进 *_Gateway.log,调用原文进 *_Trade.log(脱敏后)。</summary>
  212. private void LogInvoke(string func, string[] args, ComResult result)
  213. {
  214. try
  215. {
  216. string input = args == null || args.Length == 0 ? "" : string.Join("\n", args);
  217. Logger.Invoke(func, result.ElapsedMs, result.Success);
  218. TradeLogger.Write(func, input, result.Output, result.Code, result.Message, result.ElapsedMs, result.Success);
  219. }
  220. catch (Exception ex)
  221. {
  222. // 日志记录失败绝不能影响调用结果返回
  223. Logger.Error("记录调用日志失败", ex);
  224. }
  225. }
  226. public void Shutdown()
  227. {
  228. lock (_sync)
  229. {
  230. DisposeGateway();
  231. Logger.Info("GatewayHost 已关闭");
  232. }
  233. }
  234. private void DisposeGateway()
  235. {
  236. if (_gateway != null)
  237. {
  238. try
  239. {
  240. _gateway.Dispose();
  241. }
  242. catch (Exception ex)
  243. {
  244. Logger.Error("释放网关异常", ex);
  245. }
  246. _gateway = null;
  247. }
  248. if (_gatewaySecondary != null)
  249. {
  250. try
  251. {
  252. _gatewaySecondary.Dispose();
  253. }
  254. catch (Exception ex)
  255. {
  256. Logger.Error("释放次要网关异常", ex);
  257. }
  258. _gatewaySecondary = null;
  259. }
  260. }
  261. }
  262. }