夏末秋初 发表于 2015-8-31 13:31:20

Asp.Net使用Memcached以解决Cache的不稳定性

  首先具备的条件就是你能够使用Memcached:
  1,你有一台缓存服务器能够配置linux+Memcached。
  2,你需要保存的数据量不是很大单机配置windows版的Memcached。点击下载
  其次你要找一个.net调用Memcached的api类:
  Memcached的主站有推荐,我现在用的是Memcached.ClientLibrary.dll。点击下载
  然后你找篇配置文件配起来就可以测试使用了。
  如果想使用我的类,具体方法参照我以前一篇文章,不过我已经将MyCache类扩展可以使用Memcached。
  自己设计的Cache自控制的简单方法
  配置文件需要增加几个参数
  <add key="default_buffminutes" value="45"/>
<add key="Memcached" value="true"/>
<add key="MemServer" value="192.168.1.160:11211"/>
  MyCache.cs是操作类,DelegateLists是委托方法函数,跟你需要的函数来定义。

MyCache.cs
using System;
using System.Web;
using System.Data;
using System.Web.Caching;
using System.Collections;
using Memcached.ClientLibrary;

/**//// <summary>
/// 搜集编写者losingrose
/// QQ:303864496
/// MSN:losingrose@21cn.com
/// http://losingrose.cnblogs.com
/// Cache操作类
/// </summary>
public static class MyCache
{
    /**//*
      DelegateLists.string_2fill del = new DelegateLists.string_2fill(bll.TopDormCo_Str);
      object[] prams = new object;
      prams = "Products.aspx";
      prams = "15";
      dorms.Text = MyCache.Cache_Select("Dorms" + MySecurity.QueryString("coid"), 0, del, prams).ToString();
    */
    static Cache cache = HttpContext.Current.Cache;
    public static bool Memcached = bool.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings["Memcached"]);
    static MemcachedClient mc = new MemcachedClient();
    static double default_buffminutes = Convert.ToDouble(System.Web.Configuration.WebConfigurationManager.AppSettings["default_buffminutes"]);
    //static double default_buffminutes = 5;

    static MyCache()
    {
      //判断是否启动Memcached
      if (Memcached)
      {
            string server = System.Web.Configuration.WebConfigurationManager.AppSettings["MemServer"];
            String[] serverlist ={ server };
            // initialize the pool for memcache servers
            SockIOPool pool = SockIOPool.GetInstance("shenghuohui");
            pool.SetServers(serverlist);
            pool.Initialize();

            mc = new MemcachedClient();
            mc.PoolName = "shenghuohui";
            mc.EnableCompression = false;
      }
    }

    /**//// <summary>
    /// 取得目前Cache列表
    /// </summary>
    /// <returns></returns>
    public static string[] Cache_List()
    {
      string[] str = new string;
      int i = 0;
      foreach (DictionaryEntry item in cache)
      {
            str = item.Key.ToString();
            i++;
      }
      return str;
    }
    /**//// <summary>
    /// 添加一个新的Cache对象
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="value">待保存的值</param>
    /// <param name="buffminutes">缓存时间(按分钟计),为0则读取配置文件设定的时间</param>
    public static void Cache_Insert(string key, object value, double buffminutes)
    {
      if (Memcached)
      {
            if (buffminutes == 0)
                buffminutes = default_buffminutes;
            mc.Set(key, value,DateTime.Now.AddMinutes(buffminutes));
      }
      else
      {
            if (buffminutes == 0)
                buffminutes = default_buffminutes;
            cache.Insert(key, value, null, DateTime.Now.AddMinutes(buffminutes), TimeSpan.Zero);
      }
    }
    /**//// <summary>
    /// 移出一个Cache对象
    /// </summary>
    /// <param name="key">键名</param>
    public static void Cache_Remove(string key)
    {
      if (Memcached)
      {
            mc.Delete(key);
      }
      else
      {
            cache.Remove(key);
      }
    }
    /**//// <summary>
    /// 获取Cache对象,如果对象不存在,则调用相关事件委托填充并返回Cache的值。
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="buffminutes">缓存时间(按分钟计),为0则读取配置文件设定的时间</param>
    /// <param name="method">填充的方法委托</param>
    /// <param name="parms">方法所需要的参数列表</param>
    /// <returns>返回Cache的值</returns>
    public static object Cache_Select(string key, double buffminutes, Delegate method, params object[] parms)
    {
      object x;
      if (Memcached)
      {
            x=mc.Get(key);
            if(x==null)
            {
                if (buffminutes == 0)
                  buffminutes = default_buffminutes;
                object o = method.DynamicInvoke(parms);
                if (o != null)
                {
                  Cache_Insert(key, o, buffminutes);
                  x = o;
                }
                else
                  return method.DynamicInvoke(parms);
            }
      }
      else
      {
            x = cache.Get(key);
            if (x == null)
            {
                if (buffminutes == 0)
                  buffminutes = default_buffminutes;
                object o = method.DynamicInvoke(parms);
                if (o != null)
                {
                  Cache_Insert(key, o, buffminutes);
                  x = o;
                }
                else
                  return method.DynamicInvoke(parms);
            }
      }
      return x;
    }
    /**//// <summary>
    /// 直接获取Cache
    /// </summary>
    /// <param name="key">键名</param>
    /// <returns></returns>
    public static object Cache_Select(string key)
    {
      if (Memcached)
            return mc.Get(key);
      else
            return cache.Get(key);
    }
    /**//// <summary>
    /// 清楚所有Cache对象
    /// </summary>
    public static void Cache_Clear()
    {
      if (Memcached)
            mc.FlushAll();
      else
      {
            foreach (DictionaryEntry item in cache)
            {
                cache.Remove(item.Key.ToString());
            }
      }
    }
}
  

DelegateLists.cs
using System;
using System.Web;
using System.Data;
using System.Collections;

/**//// <summary>
/// 搜集编写者losingrose
/// QQ:303864496
/// MSN:losingrose@21cn.com
/// http://losingrose.cnblogs.com
/// 委托方法定义
/// </summary>
public class DelegateLists
{
    public delegate DataTable dataset_0fill();
    public delegate DataTable dataset_1fill(string a);
    public delegate DataTable dataset_2fill(string a, string b);
    public delegate DataTable dataset_3fill(string a, string b, string c);
    public delegate DataTable dataset_4fill(string a, string b, string c, string d);
    public delegate string string_0fill();
    public delegate string string_1fill(string a);
    public delegate string string_2fill(string a, string b);
    public delegate string string_3fill(string a, string b, string c);
    public delegate string string_4fill(string a, string b, string c, string d);
    public delegate object alluser(int userType, int userId);
    User Methods#region User Methods
    public delegate UserInfo userinfo(int userid);
    public delegate ShopInfo shopinfo(int shopid);
    #endregion
    Shop Methods#region Shop Methods
    public delegate DataTable GetAllReCommendKind();
    #endregion
}
  
页: [1]
查看完整版本: Asp.Net使用Memcached以解决Cache的不稳定性