123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Net;
- using System.Text;
- using System.Threading;
- using System.Web;
- using CB.Config;
- namespace CB.Cache.WebCache
- {
- /// <summary>
- /// 同步缓存类
- /// </summary>
- public class SyncCache
- {
- /// <summary>
- /// 除本站之外的负载均衡站点列表
- /// </summary>
- static List<string> syncCacheUrlList = null;
- static BaseConfigInfo baseConfigInfo = BaseConfigs.GetConfig();
- static SyncCache()
- {
- syncCacheUrlList = new List<string>();
- if (string.IsNullOrEmpty(baseConfigInfo.SyncCacheServer))
- { return; }
- syncCacheUrlList.AddRange(baseConfigInfo.SyncCacheServer.Split(','));
- }
- /// <summary>
- /// 同步远程缓存信息
- /// </summary>
- /// <param name="cacheKey"></param>
- public static void SyncRemoteCache(string cacheKey)
- {
- foreach (string webSite in syncCacheUrlList)
- {
- var src = new ThreadSyncRemoteCache(string.Format("{0}?cacheKey={1}&passKey={2}",
- webSite, cacheKey, HttpUtility.UrlEncode(CB.Common.XXTEA.Encode(cacheKey))));
- new Thread(new ThreadStart(src.Send)).Start();
- }
- }
- }
- /// <summary>
- /// 多线程更新远程缓存
- /// </summary>
- public class ThreadSyncRemoteCache
- {
- public string _url { get; set; }
- public ThreadSyncRemoteCache(string url)
- {
- _url = url;
- }
- public void Send()
- {
- try
- {
- //设置循环三次,如果某一次更新成功("OK"),则跳出循环
- for (int count = 0; count < 3; count++)
- {
- if (this.SendWebRequest() == "OK")
- break;
- else
- Thread.Sleep(5000);//如果更新不成功,则暂停5秒后再次更新
- }
- }
- catch { }
- finally
- {
- if (Thread.CurrentThread.IsAlive)
- Thread.CurrentThread.Abort();
- }
- }
- /// <summary>
- /// 发送web请求
- /// </summary>
- /// <param name="url"></param>
- /// <returns></returns>
- public string SendWebRequest()
- {
- var builder = new StringBuilder();
- try
- {
- WebRequest request = WebRequest.Create(new Uri(_url));
- request.Method = "GET";
- request.Timeout = 10000;
- request.ContentType = "Text/XML";
- using (WebResponse response = request.GetResponse())
- {
- using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
- {
- builder.Append(reader.ReadToEnd());
- }
- }
- }
- catch
- {
- builder.Append("Process Failed!");
- }
- return builder.ToString();
- }
- }
- }
|