SimpleLeafAgency.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using System;
  2. using System.Threading;
  3. using Vinno.IUS.Common.Network.Leaf;
  4. using Vinno.IUS.Common.Network.Tcp;
  5. using Vinno.IUS.Common.Network.Transfer;
  6. using Vinno.vCloud.Common.Storage.ObjectStorageInfo.Interface;
  7. using Vinno.vCloud.Common.Storage.ObjectStorageInfo.Solid;
  8. namespace Vinno.vCloud.Common.Storage.ObjectStorageInfo.SignatureClient.Connect
  9. {
  10. public class SimpleLeafAgency : ILeafAgency
  11. {
  12. private string _leafUrl = string.Empty;
  13. private ClientLeaf _clientLeaf = null;
  14. /// <summary>
  15. /// 构造LeafAgency
  16. /// </summary>
  17. /// <param name="leafUrl">服务地址</param>
  18. public SimpleLeafAgency(string leafUrl)
  19. {
  20. _leafUrl = leafUrl;
  21. }
  22. /// <summary>
  23. /// 构造LeafAgency
  24. /// </summary>
  25. /// <param name="storageServerUrl">服务地址</param>
  26. public SimpleLeafAgency(ClientLeaf clientLeaf)
  27. {
  28. _clientLeaf = clientLeaf;
  29. }
  30. /// <summary>
  31. /// 请求地址
  32. /// </summary>
  33. public string Url
  34. {
  35. get
  36. {
  37. return _leafUrl;
  38. }
  39. }
  40. /// <summary>
  41. /// 发送消息
  42. /// </summary>
  43. /// <param name="request"></param>
  44. /// <returns></returns>
  45. public Message AgencySend(Message request)
  46. {
  47. return AgencyKeepSend(request);
  48. }
  49. /// <summary>
  50. /// 发送消息如果是网络异常则重发
  51. /// </summary>
  52. /// <param name="request"></param>
  53. /// <param name="tryTime"></param>
  54. /// <returns></returns>
  55. public Message AgencyKeepSend(Message request, int tryTime = 3)
  56. {
  57. var agencyLeaf = new ClientLeaf(new LeafIdContext(), LeafMode.Single, new TcpCreator(_leafUrl));
  58. try
  59. {
  60. if (!agencyLeaf.Online)
  61. {
  62. throw new NetWorkException($"AgencyLeaf is offline");
  63. }
  64. var token = agencyLeaf.ApplyToken();
  65. var result = agencyLeaf.Send(token, request);
  66. return result;
  67. }
  68. catch (Exception exception)
  69. {
  70. switch (exception.GetType().Name)
  71. {
  72. case "NetWorkException":
  73. case "CanNotConnectException":
  74. case "NotConnectedException":
  75. if (tryTime == 0)
  76. {
  77. return null;
  78. }
  79. Thread.Sleep(3000);
  80. return AgencyKeepSend(request, --tryTime);
  81. default:
  82. return null;
  83. }
  84. }
  85. finally
  86. {
  87. agencyLeaf?.Close();
  88. }
  89. }
  90. public void Dispose()
  91. {
  92. }
  93. }
  94. }