复制 Commons.dll、ICSharpCode.SharpZipLib.dll、log4net.dll、Memcached.ClientLibrary.dll 到项目目录下,并添加其引用。
MemcachedHelper.cs:
using Memcached.ClientLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyWeb.Common
{
public class MemcachedHelper
{
private static readonly MemcachedClient mc = null;
//静态的构造方法
static MemcacheHelper()
{
//最好放在配置文件中
string[] serverlist = { "127.0.0.1:11211", "10.0.0.132:11211" }; //memcached服务器的IP地址和端口号。分布式memcached服务器集群。
//初始化池
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();
// 获得客户端实例。memcached客户端就是Web服务器(部署网站的服务器)。
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); //绝对过期时间,最多30天。可以通过 每使用一次就重新设置一次来模拟滑动过期时间。
}
//获取数据
public static object Get(string key)
{
return mc.Get(key);
}
//删除
public static bool Delete(string key)
{
if (mc.KeyExists(key))
{
return mc.Delete(key);
}
return false;
}
}
}