设为首页 收藏本站
查看: 1434|回复: 0

[经验分享] #Memcached系列#(6)使用Enyim.Caching访问Memcached的一个C#控制台程序

[复制链接]

尚未签到

发表于 2018-12-25 12:38:12 | 显示全部楼层 |阅读模式
  这篇文章主要是通过Enyim.Caching来完成访问Memcached。
  

  这篇文章标为“原创”,其实,是从多个地方整合过来的内容;但觉得“转载”也不合适,也并不是完全照搬别人的东西。
  参考网址(不过,感觉它的配置写的乱糟糟的):http://www.cnblogs.com/luyinghuai/archive/2008/08/28/1278200.html
  

  

  (1)首先下载EnyimMemcached(文件名:EnyimMemcached-master.zip)。
  进入网址https://github.com/enyim ,可以看到如下界面,并选择“EnyimMemcached”

  进入如下页面,或者直接访问:https://github.com/enyim/EnyimMemcached,点击右侧的“Download ZIP”,得到文件“EnyimMemcached-master.zip”

  

  (2)将“EnyimMemcached-master.zip”解压出来,如下图
  注:我们可以用“*.dll”进行搜索一下,发现并没有Enyim.Caching.dll,所以需要我们自己生成。
  

  用Visual Studio 2010打开“Enyim.Caching.sln”文件

  在打开的过程中,我遇到了(好几次)下面的提示,以我目前的水平,还不能确切的明白 “这个提示到底会发生什么事情”,所以我将它忽略了,如果有明白的朋友,可以告诉我啊

  

  直接,我们按一下F6(生成解决方案),会发现如下错误


  针对上面的问题,我们可以查看右侧的“解决方案资源管理器”内各个项目的引用信息,发现
  -->Enyim.Caching.Log4NetAdaper项目中log4net的引用丢失
  -->MemcachedTest项目中nuit.framework、nuit.mocks的引用丢失

  

  对于这个问题,我们可以Nuget来解决一下

  

  再看一下,发现错误更多,如下图,发现原来是“NUit的命名空间没有找到”


  再用Nuget解决一下这个NUnit的问题,搜索nunit.mocks,安装一下,再按F6(生成解决方案),发现成功了。


  

  (3)生成Enyim.Caching.dll的Release版本,在Enyim.Caching的Bin\Release目录下找到Enyim.Caching.dll文件


Enyim.Caching\bin\Release

  (4)新建一个“控制台应用程序”,将Enyim.Caching.dll放到项目的bin目录下

LearningEnyimMemcached\bin

  

  添加Enyim.Caching的引用

  (5)添加一个“应用程序配置文件”,文件名是App.config

  

  App.config中的配置如下



  
   
      
   
  
  
   
      
        
        
        
      
      
      
   
  
  (6)Program.cs文件中的代码
  如下

using System;
using Enyim.Caching;
using Enyim.Caching.Memcached;
namespace LearningEnyimMemcached
{
    class Program
    {
        static void Main(string[] args)
        {
            // create a MemcachedClient in your application
            // you can cache the client in a static variable or just recreate it every time
            MemcachedClient mc = new MemcachedClient();
            // store a string in the cache
            mc.Store(StoreMode.Set, "MyKey", "Hello");
            // retrieve the item from the cache
            Console.WriteLine(mc.Get("MyKey"));
            // store some other items
            mc.Store(StoreMode.Set, "D1", 1234L);
            mc.Store(StoreMode.Set, "D2", DateTime.Now);
            mc.Store(StoreMode.Set, "D3", true);
            mc.Store(StoreMode.Set, "D4", new Product());
            mc.Store(StoreMode.Set, "D5", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
            Console.WriteLine("D1: {0}", mc.Get("D1"));
            Console.WriteLine("D2: {0}", mc.Get("D2"));
            Console.WriteLine("D3: {0}", mc.Get("D3"));
            Console.WriteLine("D4: {0}", mc.Get("D4"));
            byte[] tmp = mc.Get("D5");
            // delete them from the cache
            mc.Remove("D1");
            mc.Remove("D2");
            mc.Remove("D3");
            mc.Remove("D4");
            // add an item which is valid for 10 mins
            mc.Store(StoreMode.Set, "D4", new Product(), new TimeSpan(0, 10, 0));
            Console.WriteLine("D4: {0}", mc.Get("D4"));
            Console.ReadLine();
        }
        // objects must be serializable to be able to store them in the cache
        [Serializable]
        class Product
        {
            public double Price = 1.24;
            public string Name = "Mineral Water";
            public override string ToString()
            {
                return String.Format("Product {{{0}: {1}}}", this.Name, this.Price);
            }
        }
    }
}  

  再按一下F6,发现有11个错误,说是“未能找到Enyim的命名空间”,可是,我已经添加了Enyim.Caching的引用了。

  针对这个问题,打开项目的属性,将项目的“目标框架”(由原来的.NET Framework 4 Client Profile)改成“.NET Framework 4”,再按F6(生成解决方案),就成功了。

  

  按F5(启动调试),看到如下结果

  

  (7)上面的代码确实能够运行,但是如果对自己要求更高一些,应该这样写
            using(MemcachedClient client = new MemcachedClient())
            {
                // Store the record
                client.Store(StoreMode.Set, "currentTime", DateTime.Now.ToString());
                // Retrieve the value
                string value = client.Get("currentTime");
            }  因为MemcachedClient类实现了IDisposable接口
  参考网址:http://deanhume.com/home/blogpost/memcached-for-c----a-walkthrough/62
  

  同样,在这篇文章中,作者也写了一个CacheLayer.cs文件,对MemcachedClient进行了封装(a little wrapper),但是有一个问题需要注意:作者的写的这个CacheLayer.cs类只能够在Northscale的1.4.5版本的Memcached下正常运行。
  

  CacheLayer.cs的代码如下
namespace MemcacheExample.Cache
{
    using System;
    using Enyim.Caching;
    using Enyim.Caching.Memcached;
    public class CacheLayer
    {
        private static readonly MemcachedClient Cache = new MemcachedClient();
        ///
        /// Retrieve cached item
        ///
        /// Type of cached item
        /// Name of cached item
        /// Cached item as type
        public static T Get(string key) where T : class
        {
            try
            {
                return (T) Cache.Get(key);
            }
            catch
            {
                return null;
            }
        }
        ///
        /// Insert value into the cache using
        /// appropriate name/value pairs
        ///
        /// Type of cached item
        /// Item to be cached
        /// Name of item
        /// Duration of the cache.
        public static void Add(T objectToCache, string key, int cacheDuration) where T : class
        {
            Cache.Store(StoreMode.Set, key, objectToCache, DateTime.Now.AddMinutes(cacheDuration));
        }
        ///
        /// Insert value into the cache using
        /// appropriate name/value pairs
        ///
        /// Item to be cached
        /// Name of item
        /// Duration of the cache.
        public static void Add(object objectToCache, string key, int cacheDuration)
        {
            Cache.Store(StoreMode.Set, key, objectToCache, DateTime.Now.AddMinutes(cacheDuration));
        }
        ///
        /// Remove item from cache
        ///
        /// Name of cached item
        public static void Remove(string key)
        {
            Cache.Remove(key);
        }
        ///
        /// Clears all stored objects from memory.
        ///
        public static void ClearAll()
        {
            Cache.FlushAll();
        }
        ///
        /// Check for item in cache
        ///
        /// Name of cached item
        /// A boolean if the object exists
        public static bool Exists(string key)
        {
            return Cache.Get(key) != null;
        }
    }
}  

  

  

  

  

  



附件:http://down.运维网.com/data/2367369


运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-655702-1-1.html 上篇帖子: 缓存服务器之Memcached 下篇帖子: 高性能内存对象缓存Memcached安装及数据库操作与管理
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表