C# 操作Memcached
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# 操作Memcached相关的知识,希望对你有一定的参考价值。
参考技术A 要在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");
memcached c#
1.下载Memcached For Windows
URL:http://code.jellycan.com/files/memcached-1.2.6-win32-bin.zip
2.管理员身份运行cmd
3.在Windows中安装Memcached服务:memcached.exe -d install(那么,对应卸载命令为:memcached.exe -d uninstall)
4.启动 net start "Memcached Server"
5.停止服务 net stop "Memcached Server"
6.
下载文件:http://pan.baidu.com/s/1w9Q8I
memcached clientlib项目地址:http://sourceforge.net/projects/memcacheddotnet/
解压该包,里面有1.1和2.0两个版本的,这里我们使用2.0版本的。(在压缩包中的目录地址为:\memcacheddotnet_clientlib-1.1.5\memcacheddotnet\trunk\clientlib\src\clientlib\bin\2.0\Release)
7.创建控制台项目
8.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Memcached.ClientLibrary; namespace testMemcached1 { class Program { static void Main(string[] args) { // Memcached服务器列表 // 如果有多台服务器,则以逗号分隔,例如:"192.168.80.10:11211","192.168.80.11:11211" string[] serverList = { "192.168.1.116:11211" }; // 初始化SocketIO池 string poolName = "MyPool"; SockIOPool sockIOPool = SockIOPool.GetInstance(poolName); // 添加服务器列表 sockIOPool.SetServers(serverList); // 设置连接池初始数目 sockIOPool.InitConnections = 3; // 设置连接池最小连接数目 sockIOPool.MinConnections = 3; // 设置连接池最大连接数目 sockIOPool.MaxConnections = 5; // 设置连接的套接字超时时间(单位:毫秒) sockIOPool.SocketConnectTimeout = 1000; // 设置套接字超时时间(单位:毫秒) sockIOPool.SocketTimeout = 3000; // 设置维护线程运行的睡眠时间:如果设置为0,那么维护线程将不会启动 sockIOPool.MaintenanceSleep = 30; // 设置SockIO池的故障标志 sockIOPool.Failover = true; // 是否用nagle算法启动 sockIOPool.Nagle = false; // 正式初始化容器 sockIOPool.Initialize(); // 获取Memcached客户端实例 MemcachedClient memClient = new MemcachedClient(); // 指定客户端访问的SockIO池 memClient.PoolName = poolName; // 是否启用压缩数据:如果启用了压缩,数据压缩长于门槛的数据将被储存在压缩的形式 memClient.EnableCompression = false; Console.WriteLine("----------------------------测试开始----------------------------"); //// 01.简单的添加与读取操作 //memClient.Set("test1", "chm1"); //Console.WriteLine("test1:{0}", memClient.Get("test1")); //// 02.先添加后修改再读取操作 //memClient.Set("test2", "chm2"); //Console.WriteLine("test2:{0}", memClient.Get("test2")); //memClient.Set("test2", "chm22"); //Console.WriteLine("test2:{0}", memClient.Get("test2")); //memClient.Replace("test2", "chm222"); //Console.WriteLine("test2:{0}", memClient.Get("test2")); //// 03.判断Key值是否存在 //if (memClient.KeyExists("test2")) //{ // Console.WriteLine("Key:test2 存在"); //} //// 04.删除指定Key值的数据 //memClient.Add("test3", "chm3"); //Console.WriteLine("test3:{0}", memClient.Get("test3")); //memClient.Delete("test3"); //if (!memClient.KeyExists("test3")) //{ // Console.WriteLine("Key:test3 不存在"); //} //// 05.设置数据过期时间:5秒后过期 //memClient.Add("test4", "chm4", DateTime.Now.AddSeconds(5)); //Console.WriteLine("test4:{0}", memClient.Get("test4")); //Console.WriteLine("请等待3秒钟"); //System.Threading.Thread.Sleep(3000); //Console.WriteLine("test4:{0}", memClient.Get("test4")); //System.Threading.Thread.Sleep(2000); //Console.WriteLine("请等待2秒钟"); //if (!memClient.KeyExists("test4")) //{ // Console.WriteLine("test4 过期了"); //} //06 测试存储对象 UserInfoEntity uie = new UserInfoEntity() { UserId = 1, UserName = "wt1", UserBirthday = Convert.ToDateTime("1988-09-28") }; memClient.Set("wt", uie); var obj= memClient.Get("wt"); UserInfoEntity uieGet = obj as UserInfoEntity; Console.WriteLine(uie.ToString()); Console.WriteLine("----------------------------测试完成----------------------------"); // 关闭SockIO池 sockIOPool.Shutdown(); Console.ReadKey(); } } }
以上是关于C# 操作Memcached的主要内容,如果未能解决你的问题,请参考以下文章
Python操作 RabbitMQRedisMemcacheSQLAlchemy
Python操作 RabbitMQRedisMemcacheSQLAlchemy