Exemplo n.º 1
0
 /// <summary>
 /// 添加缓存
 /// </summary>
 /// <param name="key">关键字</param>
 /// <param name="value">缓存值</param>
 public void Add <T>(string key, T value)
 {
     if (this.enable)
     {
         if (cache.Get(key) != null)
         {
             cache.Replace(key, value);
         }
         else
         {
             cache.Add(key, value);
         }
     }
     return;
 }
Exemplo n.º 2
0
    /// <summary>
    /// 覆盖缓存
    /// </summary>
    /// <param name="pKey"></param>
    /// <param name="pObject"></param>
    /// <returns></returns>
    private static bool StoreCache(string pKey, object pObject)
    {
        MemcachedClient mc = new MemcachedClient();

        mc.EnableCompression = true;
        bool _result = false;

        if (IsCache(mc, pKey))
        {
            if (mc.Get(pKey) == null)
            {
                mc.Set(pKey, pObject);//缓存存在,强行覆盖
            }
            else
            {
                mc.Replace(pKey, pObject);//缓存存在,强行覆盖
            }
            _result = true;
        }
        else
        {
            mc.Add(pKey, pObject);//第一次加载缓存
            _result = true;
        }
        return(_result);
    }
Exemplo n.º 3
0
        //13.Replace test
        public void ReplaceTest()
        {
            MemcachedClient cache = MemcachedClient.GetInstance("BeITMemcached");

            cache.Replace("BeIt", "replaced");
            HandleLogs("[Cmd=Replace]BeIt:" + cache.Get("BeIt").ToString());
        }
Exemplo n.º 4
0
        //更多的是存储一个自定义的类的实例对象。这就需要使用到序列化,下面我们来新加一个类MyObject,让其作为可序列化的对象来存储进Memcached中
        public void MemcachedTest(string[] args)
        {
            //初始化池
            SockIOPool sock = SockIOPool.GetInstance();

            sock.SetServers(serverlist.ToArray()); //添加服务器列表
            sock.InitConnections      = 3;         //设置连接池初始数目
            sock.MinConnections       = 3;         //设置最小连接数目
            sock.MaxConnections       = 5;         //设置最大连接数目
            sock.SocketConnectTimeout = 1000;      //设置连接的套接字超时。
            sock.SocketTimeout        = 3000;      //设置套接字超时读取
            sock.MaintenanceSleep     = 30;        //设置维护线程运行的睡眠时间。如果设置为0,那么维护线程将不会启动;

            //获取或设置池的故障标志。
            //如果这个标志被设置为true则socket连接失败,
            //将试图从另一台服务器返回一个套接字如果存在的话。
            //如果设置为false,则得到一个套接字如果存在的话。否则返回NULL,如果它无法连接到请求的服务器。
            sock.Failover = true;            //如果为false,对所有创建的套接字关闭Nagle的算法。
            sock.Nagle    = false;

            sock.Initialize();

            MemcachedClient mc = new MemcachedClient();

            mc.EnableCompression = true; //是否启用压缩数据

            //mc.Set(key,val);//设置 键值
            //mc.KeyExists(key) //键 是否存
            //mc.Get(key)   //获取 一个键值
            //mc.Delete(key);// 删除 键值

            Console.WriteLine("----------------------------Set-----------");
            mc.Set("key1", "value1");
            Console.WriteLine(mc.Get("key1"));
            Console.WriteLine("---------------------------replay---------");
            mc.Replace("key1", "Replay new Key1");
            Console.WriteLine(mc.Get("key1"));
            Console.WriteLine("---------------------------键值是否存在----");
            if (mc.KeyExists("key2"))
            {
                Console.WriteLine("key2存在");
            }
            else
            {
                Console.WriteLine("key2不存在,设置新值");
                mc.Set("key2", "New key2");
            }
            Console.WriteLine("-------------------------删除数据--------");
            mc.Delete("key2");
            Console.WriteLine("删除之后的数据: " + mc.Get("key2"));

            Console.WriteLine("-------------------------数据过期--------");
            mc.Add("key3", "新数据三内容", DateTime.Now.AddMilliseconds(5000));
            Console.WriteLine(mc.Get("key5"));
            System.Threading.Thread.Sleep(6000);
            Console.WriteLine("过期: " + mc.Get("key5"));

            Console.ReadLine();
        }
Exemplo n.º 5
0
        /// <summary>
        /// 设置缓存数据
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="coverType">覆盖类型</param>
        public void Set(string key, object value, CoverType coverType = CoverType.set)
        {
            switch (coverType)
            {
            case CoverType.set:
                _mcClient.Set(key, value);
                break;

            case CoverType.add:
                _mcClient.Add(key, value);
                break;

            case CoverType.replace:
                _mcClient.Replace(key, value);
                break;
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// 更新缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        private void UpdateCache(string key, object value)
        {
            SockIOPool pool = GetPool();

            memcache.PoolName          = poolName;
            memcache.EnableCompression = false;//是否压缩
            memcache.Replace(key, value, DateTime.Now.AddMinutes(expires));
        }
Exemplo n.º 7
0
 public virtual void Update(string key, object value, int seconds)
 {
     if (null != _client)
     {
         _client.Replace(key, value, DateTime.Now.AddSeconds(seconds));
     }
     if (null != _logger)
     {
         _logger.Error("the distribute client is null.");
     }
 }
Exemplo n.º 8
0
        public void Set(string key, object data, int expire)
        {
            string json = data.ToJsonString();

            if (MemClient.KeyExists(key))
            {
                MemClient.Replace(key, json, DateTime.Now.AddMinutes(expire));
            }
            else
            {
                MemClient.Set(key, json, DateTime.Now.AddMinutes(expire));
            }
        }
Exemplo n.º 9
0
        //修改
        protected void Button3_Click(object sender, EventArgs e)
        {
            GetDb(out MemcachedClient MClient);
            bool s = MClient.Replace("key1", "replace你好");

            if (s == true)
            {
                Response.Write("<script>alert('修改成功!')</script>");
                Response.Write(MClient.Get("key1"));
            }
            else
            {
                Response.Write("<script>alert('修改失败!')</script>");
            }
        }
Exemplo n.º 10
0
        public void Set(string key, object obj, DateTime expiry)
        {
            if (mCacheClient.KeyExists(key))
            {
                mCacheClient.Replace(key, obj, expiry);
            }
            else
            {
                mCacheClient.Set(key, obj, expiry);
            }
            List <string> result = GetRelation(key);

            for (int i = 0; i < result.Count; i++)
            {
                Delete(result[i]);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// 将数据以键值对的方式,缓存到Memcached
        /// </summary>
        /// <param name="key">缓存键</param>
        /// <param name="obj">缓存值</param>
        /// <param name="expiry">有效期(服务器当前时间+expiry)</param>
        public void Store(string key, object obj, TimeSpan expiry)
        {
            DateTime timeout = DateTime.Now.Add(expiry);

            if (Exists(key))
            {
                if (Get(key) == null)
                {
                    memcachedClient.Set(key, obj, timeout);//缓存存在(且对象为null),强行覆盖
                }
                else
                {
                    memcachedClient.Replace(key, obj, timeout);//缓存存在,强行覆盖
                }
            }
            else
            {
                memcachedClient.Add(key, obj, timeout);//第一次加载缓存
            }
        }
Exemplo n.º 12
0
 /// <seealso cref="Z.Caching.ICacheManager.Replace"/>
 public bool Replace(string key, object value, DateTime expiry)
 {
     return(defaultClient.Replace(key, value, expiry));
 }
Exemplo n.º 13
0
        public static bool LoadQueryInMemCached(MemcachedLoaderConfig Config, CachedQuery QueryToLoad, out string ErrorMessage)
        {
            bool LoadedQuery = false;
            ErrorMessage = string.Empty;

            ResponseCode response = ResponseCode.UnknownCommand;

            Dictionary<string, Dictionary<string, string>> MemoryDict;

            try
            {
                /*
                 * Connect to memcached server
                 */
                ServerConnectionCollection MemCachedServers = new ServerConnectionCollection();

                /*
                 * Add Server from Config Settings
                 */
                MemCachedServers.Add(Config.MemcachedConnectionSettings.Server, port: Config.MemcachedConnectionSettings.Port);

                /*
                 * Create the client
                 */
                IConnectionProvider provider = new ConnectionProvider(MemCachedServers);
                MemcachedClient client = new MemcachedClient(provider);

                /*
                 * Retrieve Query Data from MySql
                 */
                DataTable QueryDataTable = GetDataTable(Config.DBConnectionSettings, QueryToLoad);

                /*
                 * Determine whether to permanently persist kvp cached object in Redis
                 */
                bool PersistCachedObject = (Config.MemcachedConnectionSettings.CacheObjectSeconds <= 0);

                /*
                 * Cache each row from the data table as a JSON serialized dictionary
                 */
                if (QueryDataTable != null && QueryDataTable.Rows.Count > 0)
                {
                    //Define a dictionary to store the data table to be serialized into a JSON object
                    MemoryDict = null;
                    string ErrMsg = string.Empty;

                    /*
                     * Convert DataTable / MySQL Query ResultSet in Dictionary<string,Dictionary<string,string>> object
                     */
                    bool Success = Utils.GetQueryCacheDictionaryFromDataTable(Config.DBConnectionSettings, QueryToLoad, QueryDataTable, out MemoryDict, out ErrMsg);

                    /*
                     * Table Data Dictionary was successfully created - Cached each row in Memcached as a JSON dictionary
                     */
                    if (Success)
                    {
                        foreach (KeyValuePair<string, Dictionary<string, string>> TableDictionaryKvp in MemoryDict)
                        {
                            string Key = TableDictionaryKvp.Key;
                            string JsonStoreValue = JsonConvert.SerializeObject(TableDictionaryKvp.Value, new KeyValuePairConverter());

                            /*
                             * Determine right expiration Datetime value
                             */
                            DateTime ExpireDate = (PersistCachedObject) ? DateTime.MaxValue : DateTime.Now.AddSeconds(Config.MemcachedConnectionSettings.CacheObjectSeconds);


                            /*
                             * Load Kvp in Memcached
                             */
                            response = client.Set(Key, JsonStoreValue, ExpireDate);

                            /*
                             * If key already exists replace it
                             */
                            if (response == ResponseCode.KeyExists)
                            {
                                response = client.Replace(Key, JsonStoreValue, ExpireDate);
                            }
                        }
                    }
                    
                }

                /*
                 * Success
                 */
                LoadedQuery = (response == ResponseCode.NoError);
                Utils.GetEventLog().WriteEntry(string.Format("[MemcachedLoaderService.Memcached] Successfully loaded table [{0}] in the memory cache.", QueryToLoad.KeyPrefix));

            }
            catch (Exception ex)
            {
                ErrorMessage = string.Format("[MemcachedLoaderService.Memcached] Can't load query into Cache. Memcached Error Message [{0}].", ex.Message);
                Utils.GetEventLog().WriteEntry(ErrorMessage);
            }

            /*
             * Results
             */
            return LoadedQuery;
        }
Exemplo n.º 14
0
 /// <summary>
 /// 更新缓存,缓存键必须已存在
 /// </summary>
 /// <param name="strKey">缓存键</param>
 /// <param name="objValue">缓存值</param>
 /// <returns></returns>
 public static bool Replace(string strKey, object objValue)
 {
     return(cache.Replace(strKey, objValue));
 }
Exemplo n.º 15
0
 /// <summary>
 /// 修改缓存的值
 /// 使用:MemcacheHelper.GetInstance().Update(key,value)
 /// </summary>
 /// <param name="key">需要修改的键</param>
 /// <param name="value">需要修改的值</param>
 public void Update(string key, object value)
 {
     _client.Replace(key, value);
 }
Exemplo n.º 16
0
 /// <summary>
 /// 替换更新数据缓存
 /// </summary>
 /// <param name="key">键</param>
 /// <param name="value">值</param>
 /// <param name="hashCode">哈希码</param>
 public static void ReplaceFrom(string server, string key, object value, int hashCode)
 {
     MemcachedClient client = GetClient(server);
     client.PoolName = server;
     client.Replace(key, value, hashCode);
 }
Exemplo n.º 17
0
 public bool UpdateObject(string key, object value, DateTime dt)
 {
     return(mc.Replace(key, value, dt));
 }
Exemplo n.º 18
0
 /// <summary>
 /// 替换更新数据缓存
 /// </summary>
 /// <param name="key">键</param>
 /// <param name="value">值</param>
 /// <param name="expiry">过期时间</param>
 public static void ReplaceFrom(string server, string key, object value, DateTime expiry)
 {
     MemcachedClient client = GetClient(server);
     client.PoolName = server;
     client.Replace(key, value, expiry);
 }
Exemplo n.º 19
0
        /// <summary>
        /// 替换更新数据缓存
        /// </summary>
        /// <param name="server"></param>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="expiry">过期时间</param>
        /// <param name="hashCode"></param>
        public static void ReplaceFrom(string server, string key, object value, DateTime expiry, int hashCode)
        {
            MemcachedClient client = GetClient(server);

            client.Replace(key, value, expiry, hashCode);
        }
Exemplo n.º 20
0
        /// <summary>
        /// 替换更新数据缓存
        /// </summary>
        /// <param name="server"></param>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public static void ReplaceFrom(string server, string key, object value)
        {
            MemcachedClient client = GetClient(server);

            client.Replace(key, value);
        }
Exemplo n.º 21
0
 /// <summary>
 /// 替换更新数据缓存
 /// </summary>
 /// <param name="key">键</param>
 /// <param name="value">值</param>
 public static void Replace(string key, object value)
 {
     mc.Replace(key, value);
 }
Exemplo n.º 22
0
 public bool Replace(string key, object value)
 {
     return(m_memcachedClientIns.Replace(key, value));
 }
Exemplo n.º 23
0
        public bool Put(string key, object entity)
        {
            var cacheEntity = _Instance.Get(key);

            return((cacheEntity != null) ? _Instance.Replace(key, entity) : _Instance.Add(key, entity));
        }
Exemplo n.º 24
0
        static void Main(string[] args)
        {
            // Memcached服务器列表
            // 如果有多台服务器,则以逗号分隔,例如:"192.168.80.10:11211","192.168.80.11:11211"
            string[] serverList = { "192.168.0.103: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", "edisonchou");
            Console.WriteLine("test1:{0}", memClient.Get("test1"));
            // 02.先添加后修改再读取操作
            memClient.Set("test2", "jacky");
            Console.WriteLine("test2:{0}", memClient.Get("test2"));
            memClient.Set("test2", "edwin");
            Console.WriteLine("test2:{0}", memClient.Get("test2"));
            memClient.Replace("test2", "lousie");
            Console.WriteLine("test2:{0}", memClient.Get("test2"));
            // 03.判断Key值是否存在
            if (memClient.KeyExists("test2"))
            {
                Console.WriteLine("Key:test2 is existed");
            }
            // 04.删除指定Key值的数据
            memClient.Add("test3", "memcached");
            Console.WriteLine("test3:{0}", memClient.Get("test3"));
            memClient.Delete("test3");
            if (!memClient.KeyExists("test3"))
            {
                Console.WriteLine("Key:test3 is not existed");
            }
            // 05.设置数据过期时间:5秒后过期
            memClient.Add("test4", "expired", DateTime.Now.AddSeconds(5));
            Console.WriteLine("test4:{0}", memClient.Get("test4"));
            Console.WriteLine("Please waiting the sleeping time");
            System.Threading.Thread.Sleep(6000);
            if (!memClient.KeyExists("test4"))
            {
                Console.WriteLine("test4 is expired");
            }
            Console.WriteLine("----------------------------测试完成----------------------------");

            // 关闭SockIO池
            sockIOPool.Shutdown();

            Console.ReadKey();
        }
Exemplo n.º 25
0
 /// <summary>
 /// 替换缓存
 /// </summary>
 /// <param name="key">The key</param>
 /// <param name="value">The value</param>
 /// <param name="expiredTime">The expiredTime</param>
 /// <returns>
 /// The Boolean
 /// </returns>
 /// 创建者:孟祺宙
 /// 创建日期:2014/8/15 11:20
 /// 修改者:
 /// 修改时间:
 /// ----------------------------------------------------------------------------------------
 public bool Replace(string key, object value, DateTime expiredTime)
 {
     return(_memcachedClient.Replace(GetKey(key), value, expiredTime));
 }