关于Memcache使用的工具类

时间:2022-11-18 05:00:47

分布式缓存有它自己的好处 。

下面的 ConstValue.sessionId  是一个常量

public static readonly string sessionId = "sessionId";

过期时间。小于0 的情况下自动为0

public static readonly int sessionExpressMinute = 20;

此处贴出我写的一个工具类。主要实现 类似session 的分布式缓存

这个工具类还用到另外一个工具类。 http://www.cnblogs.com/jixinyu12345/p/4861190.html

需要引用一些程序集,此处我就不多写了,有问题在下面留言就可以了。

类名称 MemcacheHelper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Web.ModelBinding;
using Memcached.ClientLibrary;
using System.Web;

namespace CZBK.ItcastOA.Common
{
  public   class MemcacheHelper
  {
      private static readonly MemcachedClient mc = null;

static MemcacheHelper()
      {
          //连接池
          string[] serverlist = { "127.0.0.1:11211", "10.0.0.132:11211" };

//初始化池
          SockIOPool pool = SockIOPool.GetInstance();
          pool.SetServers(serverlist);

pool.InitConnections = 3;
          pool.MinConnections = 3;
          pool.MaxConnections = 5;

pool.SocketConnectTimeout = 1000;
          pool.SocketTimeout = 3000;

pool.MaintenanceSleep = 30;
          pool.Failover = true;

pool.Nagle = false;
          pool.Initialize();

// 获得客户端实例
          mc = new MemcachedClient();
          mc.EnableCompression = false;
      }
      public static bool Set(string key, object value)
      {
          return mc.Set(key, value);
      }
      public static bool Set(string key, object value, DateTime time)
      {
          return mc.Set(key, value, time);
      }
      /// <summary>
      /// 获取数据
      /// </summary>
      /// <param name="key"></param>
      /// <returns></returns>
      public static object Get(string key)
      {
          return mc.Get(key);
      }
      /// <summary>
      /// 删除
      /// </summary>
      /// <param name="key"></param>
      public static bool Delete(string key)
      {
          if (mc.KeyExists(key))
          {
              return mc.Delete(key);
          }
          return false;
      }

/// <summary>
      /// 模仿session的方式
      /// </summary>
      /// <typeparam name="T">需要反序列化的那个类型</typeparam>
      /// <param name="key">键</param>
      /// <param name="date">相对过期时间,以分钟为准</param>
      /// <returns>返回一个已经反序列化的一个对象,as 就可以直接转变</returns>
      public static object  SessionGet<T>(string  key ,int minute =20)    where T:class , new ()
      {//取回缓存中的值
          if (string.IsNullOrEmpty(key))
          {return null;
          }
          object obj  = mc.Get(key);
          if (obj!= null && mc.Set(key, obj, DateTime.Now.AddMinutes(minute)))
          {
              return SerializeHelper.DeserializeToObject<T>(obj.ToString());
          }
          mc.Delete(key);
          return null;
            ;
      }
      /// <summary>
      /// 判断写入缓存
      /// </summary>
      /// <param name="value">键</param>
      ///  <param name="context">上下文</param>
      /// <param name="minute">过期时间  默认为 20</param>
      /// <returns>  是否成功</returns>
      public static bool  SessionSet(object value,int minute = 20)
      {
          //设置默认过期时间
          if (minute <= 0)
          {
              minute = ConstValue.sessionExpressMinute;
          }
          value = SerializeHelper.SerializeToString(value);
          string key = Guid.NewGuid().ToString();
          if (mc.Set(key, value, minute))
          {
              HttpContext.Current.Response.Cookies[ConstValue.sessionId].Value = key;
              return true;
          }
          return false;
      }
     ///// <summary>
     /////
     ///// </summary>
     ///// <param name="value">传过来一个实体类型</param>
     ///// <param name="response">响应体</param>
     // /// <param name="minute">过期时间  默认为 20</param>
     ///// <returns></returns>
     // public static bool SessionSet(object value,  int minute = 20)
     // {
         
     //     //设置默认过期时间
     //    if (minute <= 0)
     //    {
     //        minute = ConstValue.sessionExpressMinute;
     //    }
     //    value = SerializeHelper.SerializeToString(value);
     //     string key = Guid.NewGuid().ToString();
     //     if (mc.Set(key, value))
     //     {
     //         HttpContext.Current.Response.Cookies[ConstValue.sessionId].Value = key;
     //         return true;
     //     }
     //     return false;
     // }

}
}