C#调用EnyimMemcached

本文详细介绍了如何使用EnyimMemcached库进行数据写入,并配置缓存有效期。通过调整服务器配置和验证模式,成功解决了KeyNotFoundException问题。同时,演示了如何设置缓存项的有效时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

下载地址:http://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/archive/2013/05/20/3088494.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值