要在nuget里引用(安装) EnyimMemcached ,下面是以调用阿里云的ocs(memcached)服务为例
using System;
using Enyim.Caching;
namespace MemcacheTest
{
///
/// MemcachedClient 帮组类 对外提供接口方法
///
public class MemcachedHelper {
///
/// 定义一个静态MemcachedClient客户端,它随类一起加载,所有对象共用
///
private static MemcachedClient mclient;
///
/// 静态构造函数,初始化Memcached客户端
///
static MemcachedHelper()
{
mclient = MemCached.getInstance();
}
///
/// 向Memcached缓存中添加一条数据
///
///返回是否添加成功
public static bool SetValue(string groupName,string key, object value, DateTime expiry)
{
key = groupName + “-” + key;
return mclient.Store(Enyim.Caching.Memcached.StoreMode.Set,key, value, expiry);
}
///
/// 向Memcached缓存中添加一条数据 默认超时24小时
////
public static bool SetValue(string groupName, string key, object value)
{
key = groupName + “-” + key;
eturn mclient.Store(Enyim.Caching.Memcached.StoreMode.Set, key, value, DateTime.Now.AddHours(24));
}
///
/// 通过key 来得到一个对象
///
public static object GetValue(string groupName, string key)
{
key = groupName + “-” + key;
return mclient.Get(key);
}
///
/// 通过key 来得到一个对象(前类型)
///
public static T GetValue(string groupName, string key)
{
key = groupName + “-” + key;
return mclient.Get(key);
}
///
/// 清除指定key的cache
///
public static bool Remove(string groupName, string key)
{
key = groupName + “-” + key;
return mclient.Remove(key);
}
///
/// 清除所有cache
///
public static void RemoveAll()
{
mclient.FlushAll();
}
}
}
usingSystem.Net;
usingEnyim.Caching;
usingEnyim.Caching.Configuration;
usingEnyim.Caching.Memcached;
namespaceMemcacheTest
{
///
///MemcachedClient 配置类
///
publicsealedclassMemCached
{
privatestaticMemcachedClient MemClient;
staticreadonlyobjectpadlock =newobject();
//线程安全的单例模式
publicstaticMemcachedClientgetInstance()
{
if(MemClient ==null)
{
lock(padlock)
{
if(MemClient ==null)
{
MemClientInit();
}
}
}
returnMemClient;
}
staticvoidMemClientInit()
{
//初始化缓存
MemcachedClientConfiguration memConfig =newMemcachedClientConfiguration();
IPAddress newaddress = IPAddress.Parse(Dns.GetHostEntry(“XXXXXXXXXX.m.cnhzalicm10pub001.ocs.aliyuncs.com”).AddressList[0].ToString());//xxxx替换为ocs控制台上的“内网地址”
IPEndPoint ipEndPoint =newIPEndPoint(newaddress,11211);// 配置文件 – ip
memConfig.Servers.Add(ipEndPoint);// 配置文件 – 协议
memConfig.Protocol = MemcachedProtocol.Binary;
// 配置文件-权限,如果使用了免密码功能,则无需设置userName和password
memConfig.Authentication.Type =typeof(PlainTextAuthenticator);
memConfig.Authentication.Parameters[“zone”] =””;
memConfig.Authentication.Parameters[“userName”] =”XXXXXXXXXXXXXXXXX”;
memConfig.Authentication.Parameters[“password”] =”XXXXXXXXXX”;
//下面请根据实例的最大连接数进行设置
memConfig.SocketPool.MinPoolSize =5;
memConfig.SocketPool.MaxPoolSize =200;
MemClient =newMemcachedClient(memConfig);
}
}
}
程序调用
MemcachedHelper.SetValue(groupName,strKey, strValue, DateTime.Now.AddMinutes(5));
varrestr = MemcachedHelper.GetValue(groupName,strKey);
varobj = MemcachedHelper.GetValue(groupName,”p001″);