SyncCache.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Web;
  8. using CB.Config;
  9. namespace CB.Cache.WebCache
  10. {
  11. /// <summary>
  12. /// 同步缓存类
  13. /// </summary>
  14. public class SyncCache
  15. {
  16. /// <summary>
  17. /// 除本站之外的负载均衡站点列表
  18. /// </summary>
  19. static List<string> syncCacheUrlList = null;
  20. static BaseConfigInfo baseConfigInfo = BaseConfigs.GetConfig();
  21. static SyncCache()
  22. {
  23. syncCacheUrlList = new List<string>();
  24. if (string.IsNullOrEmpty(baseConfigInfo.SyncCacheServer))
  25. { return; }
  26. syncCacheUrlList.AddRange(baseConfigInfo.SyncCacheServer.Split(','));
  27. }
  28. /// <summary>
  29. /// 同步远程缓存信息
  30. /// </summary>
  31. /// <param name="cacheKey"></param>
  32. public static void SyncRemoteCache(string cacheKey)
  33. {
  34. foreach (string webSite in syncCacheUrlList)
  35. {
  36. var src = new ThreadSyncRemoteCache(string.Format("{0}?cacheKey={1}&passKey={2}",
  37. webSite, cacheKey, HttpUtility.UrlEncode(CB.Common.XXTEA.Encode(cacheKey))));
  38. new Thread(new ThreadStart(src.Send)).Start();
  39. }
  40. }
  41. }
  42. /// <summary>
  43. /// 多线程更新远程缓存
  44. /// </summary>
  45. public class ThreadSyncRemoteCache
  46. {
  47. public string _url { get; set; }
  48. public ThreadSyncRemoteCache(string url)
  49. {
  50. _url = url;
  51. }
  52. public void Send()
  53. {
  54. try
  55. {
  56. //设置循环三次,如果某一次更新成功("OK"),则跳出循环
  57. for (int count = 0; count < 3; count++)
  58. {
  59. if (this.SendWebRequest() == "OK")
  60. break;
  61. else
  62. Thread.Sleep(5000);//如果更新不成功,则暂停5秒后再次更新
  63. }
  64. }
  65. catch { }
  66. finally
  67. {
  68. if (Thread.CurrentThread.IsAlive)
  69. Thread.CurrentThread.Abort();
  70. }
  71. }
  72. /// <summary>
  73. /// 发送web请求
  74. /// </summary>
  75. /// <param name="url"></param>
  76. /// <returns></returns>
  77. public string SendWebRequest()
  78. {
  79. var builder = new StringBuilder();
  80. try
  81. {
  82. WebRequest request = WebRequest.Create(new Uri(_url));
  83. request.Method = "GET";
  84. request.Timeout = 10000;
  85. request.ContentType = "Text/XML";
  86. using (WebResponse response = request.GetResponse())
  87. {
  88. using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
  89. {
  90. builder.Append(reader.ReadToEnd());
  91. }
  92. }
  93. }
  94. catch
  95. {
  96. builder.Append("Process Failed!");
  97. }
  98. return builder.ToString();
  99. }
  100. }
  101. }