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
{
///
/// 同步缓存类
///
public class SyncCache
{
///
/// 除本站之外的负载均衡站点列表
///
static List syncCacheUrlList = null;
static BaseConfigInfo baseConfigInfo = BaseConfigs.GetConfig();
static SyncCache()
{
syncCacheUrlList = new List();
if (string.IsNullOrEmpty(baseConfigInfo.SyncCacheServer))
{ return; }
syncCacheUrlList.AddRange(baseConfigInfo.SyncCacheServer.Split(','));
}
///
/// 同步远程缓存信息
///
///
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();
}
}
}
///
/// 多线程更新远程缓存
///
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();
}
}
///
/// 发送web请求
///
///
///
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();
}
}
}