C#调用EnyimMemcached

最近有个项目需要调用EnyimMemcached。

首先下载了驱动的DLL(Enyim.Caching.2.12) 。

下载地址:https://files.cnblogs.com/QQ544952425/Enyim.Caching.2.12.zip

首先就是添加引用咯,然后引用命名空间。

using Enyim.Caching.Configuration;
using Enyim.Caching.Memcached;
using Enyim.Caching;


按照Demo写好了代码,进行测试

        [STAThread]
        private void button1_Click(object sender, EventArgs e)
        {
            string setstring = textBox1.Text;
            MemcachedClientConfiguration config = new MemcachedClientConfiguration();
            config.Servers.Add(new System.Net.IPEndPoint(IPAddress.Parse("10.10.10.21"), 11211));
            config.Protocol = MemcachedProtocol.Binary;
            config.Authentication.Type = typeof(PlainTextAuthenticator);
            config.Authentication.Parameters["userName"] = "memcache";
            config.Authentication.Parameters["password"] = "password";
            var mac = new MemcachedClient(config);
            //mac.Store(StoreMode.Add, "textbox1", setstring);
            mac.Store(StoreMode.Set, "textbox1", setstring);
            string str = mac.Get("textbox1") as string;
            MessageBox.Show(str);
        }

但是总是抛出异常:给定的关键字不在字典中。也就是KeyNotFountException。图如下:

看过了各个配置与节点。发现是服务器没有添加用户鉴权的参数。就注释掉了用户鉴权的部分,把代码修改如下:

        private void button1_Click(object sender, EventArgs e)
        {
            string setstring = textBox1.Text;
            MemcachedClientConfiguration config = new MemcachedClientConfiguration();//创建配置参数
            config.Servers.Add(new System.Net.IPEndPoint(IPAddress.Parse("10.10.141.21"), 11211));//增加服务节点
            config.Protocol = MemcachedProtocol.Binary;
            //config.Authentication.Type = typeof(PlainTextAuthenticator);//设置验证模式
            //config.Authentication.Parameters["userName"] = "memcache";//用户名参数
            //config.Authentication.Parameters["password"] = "password";//密码参数
            var mac = new MemcachedClient(config);//创建连接
            mac.Store(StoreMode.Add, "textbox1", setstring);//写入
            mac.Store(StoreMode.Set, "textbox1", setstring);//更新
            string str = mac.Get("textbox1") as string;//获取信息
            MessageBox.Show(str);//打印信息
        }

这样就顺利的向EnyimMemcached写入数据了^_^。

当然,缓存都是有有效时间的,虽然不知道默认的有效时间是多久,但是可以在写入的时候设置有效时间。

代码如下:

            mac.Store(StoreMode.Set, key, str, new TimeSpan(24, 0, 0));
            mac.Store(StoreMode.Add, key, str, new TimeSpan(24, 24, 24));

ok这样就完成数据的有效时间配置了。

原文地址:https://www.cnblogs.com/QQ544952425/p/3088494.html