使用Enyim.Caching访问阿里云的OCS

Posted 深蓝医生

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Enyim.Caching访问阿里云的OCS相关的知识,希望对你有一定的参考价值。

阿里云的开放式分布式缓存(OCS)简化了缓存的运维管理,使用起来很方便,官方推荐的.NET访问客户端类库为 Enyim.Caching,下面对此做一个封装。

首先引用最新版本 Enyim.Caching ,比如2.13.2.0 版本。

先按照阿里云的示例代码,封装一个基础的 MemCached访问类:

 public sealed class MemCached
    {
        private static MemcachedClient MemClient;
        static readonly object padlock = new object();
        //线程安全的单例模式
        public static MemcachedClient getInstance()
        {
            if (MemClient == null)
            {
                lock (padlock)
                {
                    if (MemClient == null)
                    {
                        MemClientInit();
                    }
                }
            }
            return MemClient;
        }

        static void MemClientInit()
        {
         
             //初始化缓存
             string host = System.Configuration.ConfigurationManager.AppSettings["MemoryCacheServer"];
             MemcachedClientConfiguration memConfig = new MemcachedClientConfiguration();
             IPAddress newaddress = IPAddress.Parse(Dns.GetHostEntry (host).AddressList[0].ToString());//your_ocs_host替换为OCS内网地址 
             IPEndPoint ipEndPoint = new IPEndPoint(newaddress, 11211);

               // 配置文件 - ip
             memConfig.Servers.Add(ipEndPoint);
             // 配置文件 - 协议
             memConfig.Protocol = MemcachedProtocol.Binary;
             // 配置文件-权限
             memConfig.Authentication.Type = typeof(PlainTextAuthenticator);
             memConfig.Authentication.Parameters["zone"] = "";
             memConfig.Authentication.Parameters["userName"] =  System.Configuration.ConfigurationManager.AppSettings["CacheServerUID"];
             memConfig.Authentication.Parameters["password"] =  System.Configuration.ConfigurationManager.AppSettings["CacheServerPWD"];
             //下面请根据实例的最大连接数进行设置
             memConfig.SocketPool.MinPoolSize = 5;
             memConfig.SocketPool.MaxPoolSize = 200;
             MemClient=new MemcachedClient(memConfig);
           
            //如果采用配置文件,可以注释上面代码,直接下面一行代码:
            //MemClient = new MemcachedClient();
        }
    }

 再定义一个缓存访问接口:

public interface ICacheManager
    {
        /// <summary>
        /// 是否启用缓存
        /// </summary>
        bool IsEnabled { get; }

        /// <summary>
        /// 根据key取缓存对象
        /// </summary>
        T Get<T>(string key);

        object Get(string key);

        /// <summary>
        /// 放入缓存
        /// </summary>
        bool Set(string key, object data, int cacheTime);

        /// <summary>
        /// 是否在缓存中
        /// </summary>
        bool IsSet(string key);

        /// <summary>
        /// 从缓存删除
        /// </summary>
        void Remove(string key);

        /// <summary>
        /// 根据规则删除
        /// </summary>
        void RemoveByPattern(string pattern);

        /// <summary>
        /// 清空所有缓存
        /// </summary>
        void Clear();
    }

最后封装 OCSManager:

public class OCSManager : ICacheManager
    {
        private static readonly MemcachedClient cache;
        private static readonly OCSManager instance;

        private OCSManager()
        {

        }

        static OCSManager()
        {
            cache = MemCached.getInstance();
            instance = new OCSManager();
            
        }

      

        private static bool isServerConnected = true;



        public static ICacheManager Instance
        {
            get { return instance; }
        }

        #region ICacheManager 成员

        public bool IsEnabled
        {
            get { return cache != null && isServerConnected; }
        }

        public T Get<T>(string key)
        {
            //var result = cache.ExecuteGet<T>(key);
            //return result.Value;
            return cache.Get<T>(key);
        }

        public object Get(string key)
        {
            return cache.Get(key);
        }

        public bool Set(string key, object data, int cacheTime)
        {
            if (data == null)
                return false;
           
            //var result= cache.ExecuteStore (Enyim.Caching.Memcached.StoreMode.Add,key,data,DateTime.Now + TimeSpan.FromMinutes(cacheTime));
            //return result.Success;

            return  cache.Store(Enyim.Caching.Memcached.StoreMode.Set, key, data, DateTime.Now + TimeSpan.FromMinutes(cacheTime));
        }

        public bool IsSet(string key)
        {
            object obj;
            return cache.TryGet(key, out obj);
        }

        public void Remove(string key)
        {
            cache.Remove(key);
        }

        public void RemoveByPattern(string pattern)
        {
            //throw new NotImplementedException();
        }

        public void Clear()
        {
            cache.FlushAll();
        }

      
        #endregion
    }

 最后,在应用程序配置文件,增加上如下的配置节点:

   <configSections>
    <sectionGroup name="enyim.com">
      <section name="memcached" type="Enyim.Caching.Configuration.MemcachedClientSection, Enyim.Caching" />
    </sectionGroup>
  </configSections>

  <enyim.com>
    <memcached protocol="Binary">
      <servers>
        <add address="192.168.70.1" port="11211" />
      </servers>
      <socketPool minPoolSize="20" maxPoolSize="500" connectionTimeout="00:00:01" deadTimeout="00:00:01" receiveTimeout="00:00:01" />
      <authentication type="Enyim.Caching.Memcached.PlainTextAuthenticator,Enyim.Caching" zone="" userName="" password="" />
    </memcached>
  </enyim.com> 

 注意:OCS使用的时候,会分配指定的用户名和密码, userName="" password="" ,请在实际使用之前做好这个配置。

以上是关于使用Enyim.Caching访问阿里云的OCS的主要内容,如果未能解决你的问题,请参考以下文章

Enyim.Caching 客户端配置及示例

java怎么操作阿里云的oss

使用阿里云的k8s部署访问环境

阿里云的访问控制

使用阿里云的 docker 加速器

使用LVS或者阿里云的SLB后如何获取访客真实的IP地址