Exemplo n.º 1
2
 public void NullCache() {
     using (MemcachedClient client = new MemcachedClient("enyim.com/memcached")) {
         String key = Guid.NewGuid().ToString("n");
         Object value = null;
         client.Store(StoreMode.Set, key, value);
         var exist = client.TryGet(key, out value);
         Assert.IsTrue(exist);
         Assert.IsNull(value);
     }
 }
        /// <summary>
        /// 查询用户信息.
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public TestData GetTestDataByUserName(string userName)
        {
            // 尝试从 MemCached 中获取数据.
            TestData result = client.Get <TestData>(userName);

            if (result != null)
            {
                logger.InfoFormat("从 MemCahced 中,通过关键字 {0}, 查询到数据 {1}", userName, result);
            }


            if (result == null)
            {
                // MemCached 中没有数据, 尝试 加载.
                result = realService.GetTestDataByUserName(userName);

                if (result != null)
                {
                    // MemCached 中没有,数据库中有, 尝试加入MemCached.
                    // 过期时间.
                    DateTime absoluteExpiration = DateTime.Now.AddMinutes(30);

                    // 指定过期方式。 加入 Memcache.
                    client.Store(StoreMode.Add, userName, result, absoluteExpiration);
                }
            }

            // 返回.
            return(result);
        }
Exemplo n.º 3
0
        public static bool Add(string key, object value, CacheItemPolicy policy)
        {
            if (defaultCache != null)
            {
                key = key.Replace(' ', '_');

                // if (policy.AbsoluteExpiration != null
                if (policy.SlidingExpiration.Ticks == 0)
                {
                    if (defaultCache.Store(Enyim.Caching.Memcached.StoreMode.Set, key, value, policy.AbsoluteExpiration.DateTime))
                    {
                        return(true);
                    }
                }
                else
                {
                    if (defaultCache.Store(Enyim.Caching.Memcached.StoreMode.Set, key, value, policy.SlidingExpiration))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Exemplo n.º 4
0
        public static BlackTable Load()
        {
            var version = GetVersion();
            var service = ServiceFactory.GetService <ICurrencyService>();
            var lst     = service.GetBlacklist();
            var table   = new BlackTable();

            table.Version          = version;
            table.CurrenciesNumber = new List <byte[]>();
            foreach (var item in lst)
            {
                var val = GetCurrencyNumberBytes(item);
                table.CurrenciesNumber.Add(val);
            }
            string key = "BlackTable";

            var result = _client.Store(Enyim.Caching.Memcached.StoreMode.Add, key, table);

            if (!result)
            {
                result = _client.Store(Enyim.Caching.Memcached.StoreMode.Replace, key, table);
            }

            logger.Info("black table information updated.");
            return(table);
        }
Exemplo n.º 5
0
        public void ExpirationTest()
        {
            MemcachedClient mc = new MemcachedClient();

            mc.Store(StoreMode.Set, "ExpirationTest:TimeSpan", "ExpirationTest:TimeSpan", new TimeSpan(0, 0, 5));

            Assert.AreEqual("ExpirationTest:TimeSpan", mc.Get("ExpirationTest:TimeSpan"), "Expires:Timespan store failed");

            Thread.Sleep(8000);
            Assert.IsNull(mc.Get("ExpirationTest:TimeSpan"), "ExpirationTest:TimeSpan item did not expire");

            DateTime expiresAt = DateTime.Now.AddSeconds(5);

            mc.Store(StoreMode.Set, "Expires:DateTime", "Expires:DateTime", expiresAt);

            Assert.AreEqual("Expires:DateTime", mc.Get("Expires:DateTime"), "Expires:DateTime store failed");

            expiresAt = expiresAt.AddSeconds(4); // wait more than the expiration

            while (DateTime.Now < expiresAt)
            {
                Thread.Sleep(100);
            }

            object o = mc.Get("Expires:DateTime");

            Assert.IsNull(o, "Expires:DateTime item did not expire");
        }
Exemplo n.º 6
0
        // TODO: !!! routePattern implementation needs to be changed to Cas
        public void AddOrUpdate(CacheKey key, TimedEntityTagHeaderValue eTag)
        {
            // add item
            _memcachedClient.Store(StoreMode.Set, key.HashBase64, eTag.ToString());

            // add route pattern if not there
            string keyForRoutePattern  = GetKeyForRoutePattern(key.RoutePattern);
            string keyForResourceUri   = GetKeyForResourceUri(key.ResourceUri);
            var    routePatternEntries = GetRoutePatternEntries(key.RoutePattern);
            var    resourceUriEntries  = GetResourceUriEntries(key.ResourceUri);


            if (!routePatternEntries.Contains(key.HashBase64))
            {
                var bytes = new List <byte>();
                foreach (var routePatternEntry in routePatternEntries)
                {
                    bytes.AddRange(new LengthedPrefixedString(routePatternEntry).ToByteArray());
                }
                bytes.AddRange(new LengthedPrefixedString(key.HashBase64).ToByteArray());
                _memcachedClient.Store(StoreMode.Set, keyForRoutePattern, bytes.ToArray());
            }
            if (!resourceUriEntries.Contains(key.HashBase64))
            {
                var bytes = new List <byte>();
                foreach (var entry in resourceUriEntries)
                {
                    bytes.AddRange(new LengthedPrefixedString(entry).ToByteArray());
                }
                bytes.AddRange(new LengthedPrefixedString(key.HashBase64).ToByteArray());
                _memcachedClient.Store(StoreMode.Set, keyForResourceUri, bytes.ToArray());
            }
        }
Exemplo n.º 7
0
        public void StoreWithProtoTranscoder()
        {
            var config = GetConfig();
            var transcoder = new ProtoBuf.Caching.Enyim.NetTranscoder();
            config.Transcoder =  transcoder;
            SomeType obj = new SomeType { Id = 1, Name = "abc" }, clone;
            string cloneString;
            Assert.AreEqual(0, transcoder.Deserialized);
            Assert.AreEqual(0, transcoder.Serialized);
            using (var client = new MemcachedClient(config))
            {
                client.Store(StoreMode.Set, "raw1", obj);
                client.Store(StoreMode.Set, "raw2", "def");
            }
            Assert.AreEqual(0, transcoder.Deserialized);
            Assert.AreEqual(1, transcoder.Serialized);
            using (var client = new MemcachedClient(config))
            {
                clone = (SomeType)client.Get("raw1");
                cloneString = (string)client.Get("raw2");
            }
            Assert.AreEqual(1, transcoder.Deserialized);
            Assert.AreEqual(1, transcoder.Serialized);

            Assert.AreEqual(1, clone.Id);
            Assert.AreEqual("abc", clone.Name);
            Assert.AreEqual("def", cloneString);
        }
Exemplo n.º 8
0
        public void StoreWithProtoTranscoder()
        {
            var config     = GetConfig();
            var transcoder = new AqlaSerializer.Caching.Enyim.NetTranscoder();

            config.Transcoder = transcoder;
            SomeType obj = new SomeType {
                Id = 1, Name = "abc"
            }, clone;
            string cloneString;

            Assert.AreEqual(0, transcoder.Deserialized);
            Assert.AreEqual(0, transcoder.Serialized);
            using (var client = new MemcachedClient(config))
            {
                client.Store(StoreMode.Set, "raw1", obj);
                client.Store(StoreMode.Set, "raw2", "def");
            }
            Assert.AreEqual(0, transcoder.Deserialized);
            Assert.AreEqual(1, transcoder.Serialized);
            using (var client = new MemcachedClient(config))
            {
                clone       = (SomeType)client.Get("raw1");
                cloneString = (string)client.Get("raw2");
            }
            Assert.AreEqual(1, transcoder.Deserialized);
            Assert.AreEqual(1, transcoder.Serialized);

            Assert.AreEqual(1, clone.Id);
            Assert.AreEqual("abc", clone.Name);
            Assert.AreEqual("def", cloneString);
        }
Exemplo n.º 9
0
        public void Set(string key, object value, CacheSetting itemInfo)
        {
            lock (thisLock)
            {
                DateTime expiredtime = DateTime.Now;

                switch (itemInfo.ExpirationMode)
                {
                case CacheExpirationMode.Absolute:
                    expiredtime = itemInfo.AbsoluteExpiration;
                    break;

                case CacheExpirationMode.Sliding:
                    expiredtime = expiredtime.Add(itemInfo.SlidingExpiration);
                    break;

                case CacheExpirationMode.Never:
                    client.Store(StoreMode.Set, key, value);
                    return;

                default:
                    break;
                }

                client.Store(StoreMode.Set, key, value, expiredtime);
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Inserts an item into the cache with a cache key to reference its location.
        /// </summary>
        /// <typeparam name="T">Dependency object to be find child from.</typeparam>
        /// <param name="key">The key used to reference the item.</param>
        /// <param name="value">The object to be inserted into the cache.</param>
        /// <param name="expiration">The expiration time of the cached object</param>
        ///
        public void Put <T>(string key, T value, TimeSpan expiration) where T : class
        {
            this.CheckParamKey(key);
            this.CheckParamValue(value);

            _mc.Store(StoreMode.Set, key, value, expiration);
        }
 public IHttpActionResult Init()
 {
     memcache.Store(StoreMode.Set, "matrix_multiplication", benchmarkingService.GetMatrixMultiplicationData());
     memcache.Store(StoreMode.Set, "sieve_of_atkin", benchmarkingService.GetSieveOfAtkinData());
     memcache.Store(StoreMode.Set, "quicksort", benchmarkingService.GetQuicksortData());
     return(Ok());
 }
Exemplo n.º 12
0
        public virtual void Init()
        {
            var state = _client.Get <int>(Prefix + "g");

            if (state > 0)
            {
                return;
            }
            var items = LoadItems();

            foreach (var item in items)
            {
                var key    = Prefix + GetItemKey(item);
                var result = _client.Store(Enyim.Caching.Memcached.StoreMode.Add, key, item);
                if (!result)
                {
                    result = _client.Store(Enyim.Caching.Memcached.StoreMode.Replace, key, item);
                    if (!result)
                    {
                        throw new InvalidOperationException("memecached store failed");
                    }
                }
            }
            _client.Store(Enyim.Caching.Memcached.StoreMode.Add, Prefix + "g", 1);
        }
Exemplo n.º 13
0
 public static bool Set(string key, object value, StoreMode mode = StoreMode.Set)
 {
     if (string.IsNullOrEmpty(key))
     {
         key = GetUniqueKey();
     }
     return(client.Store(mode, key, value));
 }
Exemplo n.º 14
0
 public void add(String player)
 {
     if (memcachedClient.Get <string>(player) == null)
     {
         memcachedClient.Store(StoreMode.Add, player, 0);
     }
     memcachedClient.Store(StoreMode.Replace, player, (int.Parse(memcachedClient.Get <string>(player)) + 1));
 }
Exemplo n.º 15
0
        public static void Store(this MemcachedClient client, string key, object item)
        {
            var result = client.Store(Enyim.Caching.Memcached.StoreMode.Add, key, item);

            if (!result)
            {
                client.Store(Enyim.Caching.Memcached.StoreMode.Replace, key, item);
            }
        }
Exemplo n.º 16
0
        private static void Set(Guid eTag, string key)
        {
            //wrap the guid in double-quotes so the ETag is stored in client header format:
            var value = Wrap(eTag);

            _Cache.Store(StoreMode.Set, key, value);
            //store the URL against the ETag so we can do a reverse-lookup for updates:
            _Cache.Store(StoreMode.Set, value, key);
        }
Exemplo n.º 17
0
 public bool Set(string key, object value, double minute = 10d, string regionName = null)
 {
     if (minute <= 0)
     {
         throw new ArgumentException("缓存过期时间必须大于0");
     }
     return(value != null &&
            memClient.Store(StoreMode.Set, GetCacheKey(key, regionName), value, TimeSpan.FromMinutes(minute)));
 }
        public Stream CreateRequestStream(string requestId)
        {
            _logger?.Verbose("Creating stream for storing request body. request-id={RequestId}", requestId);

            var ms = new NotifyingMemoryStream();

            ms.Disposing += (s, e) => _memcachedClient.Store(StoreMode.Set, requestId, (s as NotifyingMemoryStream)?.ToArray(), _storagePeriod);
            return(ms);
        }
Exemplo n.º 19
0
        /// <summary>
        /// 写入缓存
        /// </summary>
        /// <param name="key">缓存键</param>
        /// <param name="value">缓存值json格式</param>
        public static bool Set(string key, string value)
        {
            try
            {
                int mb = 1024 * 1024;
                //json字符串的大小小于1M的时候直接写入缓存
                if (System.Text.Encoding.Default.GetByteCount(value) < mb)
                {
                    return(Client.Store(Enyim.Caching.Memcached.StoreMode.Set, key, value));
                }
                else
                {
                    //缓存大于1M,分块存储,返回结果,
                    int  chunkSize = mb / 2;
                    bool flag      = true;
                    //存缓存块对应的缓存键值
                    var subKeys = new List <string>();
                    for (int i = 0; i *chunkSize < value.Length; i++)
                    {
                        //分割字符串存到缓存的键值
                        string subKey = key + "_" + i;
                        //指定长度截取值
                        string subValue = (i + 1) * chunkSize < value.Length ? value.Substring(i * chunkSize, chunkSize) : value.Substring(i * chunkSize);

                        //分块写入缓存
                        if (Client.Store(Enyim.Caching.Memcached.StoreMode.Set, subKey, subValue))
                        {
                            subKeys.Add(subKey);
                        }
                        else
                        {
                            flag = false;
                            break;
                        }
                    }
                    if (!flag)
                    {
                        // 保存失败,将成功的子键缓存也清空
                        foreach (string subkey in subKeys)
                        {
                            Client.Remove(subkey);
                        }
                    }
                    else
                    {
                        //子键都保存成功,保存主键
                        flag = Client.Store(Enyim.Caching.Memcached.StoreMode.Set, key, subKeys);
                    }
                    return(flag);
                }
            }
            catch (Exception ex)
            {
                throw new MemberExecption(ex.Message);
            }
        }
Exemplo n.º 20
0
        public static bool AddOrReplace(this MemcachedClient client, string key, object item)
        {
            var result = client.Store(StoreMode.Add, key, item);

            if (!result)
            {
                result = client.Store(StoreMode.Replace, key, item);
            }

            return(result);
        }
Exemplo n.º 21
0
 public void Set(string key, object data, int cacheTime)
 {
     try
     {
         MemClient.Store(StoreMode.Set, key, data, DateTime.Now.AddSeconds(cacheTime));
     }
     catch (Exception)
     {
         //igore
     }
 }
Exemplo n.º 22
0
 public bool AddItem(System.Runtime.Caching.CacheItem item, int seconds = -1)
 {
     if (seconds > 0)
     {
         TimeSpan ts = new TimeSpan(seconds * 1000);
         return(client.Store(StoreMode.Add, item.Key, item.Value, ts));
     }
     else
     {
         return(client.Store(StoreMode.Add, item.Key, item.Value));
     }
 }
        public void InsertToCache(string key, object value)//TODO:添加Timeout参数
        {
            if (string.IsNullOrEmpty(key) || value == null)
            {
                return;
            }

            var cacheKey = GetFinalKey(key);

            //TODO:加了绝对过期时间就会立即失效(再次获取后为null),memcache低版本的bug
            _cache.Store(StoreMode.Set, cacheKey, value, DateTime.Now.AddDays(1));
        }
Exemplo n.º 24
0
 /// <summary>
 /// 使用Add模式添加缓存,如果同名Key已存在返回false
 /// </summary>
 public static bool AddCacheExplicit(string key, object value, int minutes = 10)
 {
     if (!IsUsedCache)
     {
         return(false);
     }
     if (minutes <= 0)
     {
         return(Mc.Store(StoreMode.Add, key, value));
     }
     return(Mc.Store(StoreMode.Add, key, value, TimeSpan.FromMinutes(minutes)));
 }
Exemplo n.º 25
0
        public void RunProgram()
        {
            const string key = "testkey";
            var cacheClient = new MemcachedClient(ConfigurationManager.GetSection("enyim.com/memcached") as IMemcachedClientConfiguration);
            cacheClient.Store(StoreMode.Add, key, "testvalue");
            var item = cacheClient.Get(key);
            Console.WriteLine(item);

            cacheClient.Store(StoreMode.Set, key, "something else");
            item = cacheClient.Get(key);
            Console.WriteLine(item);
        }
Exemplo n.º 26
0
 public override void Save(string key, object value, int seconds)
 {
     if (seconds > 0)
     {
         var date = DateTime.Now;
         date.AddSeconds(seconds);
         Instance.Store(StoreMode.Set, key, value, date);
     }
     else
     {
         Instance.Store(Enyim.Caching.Memcached.StoreMode.Set, key, value);
     }
 }
Exemplo n.º 27
0
        public int Create(string name)
        {
            var keys   = GetProductKeys();
            var newKey = keys.GetNextKey();

            client.Store(StoreMode.Add, newKey.ToString(), new Product {
                Id = newKey, Name = name
            });

            UpdateProductKeys(keys);

            return(newKey);
        }
Exemplo n.º 28
0
        public void SetDemo()
        {
            Person person = new Person {
                UserId = 1, UserName = "******"
            };
            //不带过期时间的存储,Memcached将根据LRU来决定过期策略
            bool success = client.Store(StoreMode.Add, person.UserName, person);

            Console.WriteLine("存储[{0}]的结果:{1}", person.UserName, success);
            //带过期时间的缓存
            success = client.Store(StoreMode.Add, person.UserName, person, DateTime.Now.AddMinutes(10));
            Console.WriteLine("存储[{0}]的结果:{1}", person.UserName, success);
        }
Exemplo n.º 29
0
        /// <summary>
        /// 插入指定值
        /// </summary>
        /// <param name="key">缓存名称 </param>
        /// <param name="value">缓存值</param>
        /// <returns>返回是否成功</returns>
        public bool Insert(string key, string value)
        {
            MemcachedClient mc   = getInstance();
            var             data = mc.Get(key);

            if (data == null)
            {
                return(mc.Store(StoreMode.Add, MemPrefix + key, value));
            }
            else
            {
                return(mc.Store(StoreMode.Replace, MemPrefix + key, value));
            }
        }
Exemplo n.º 30
0
        public void RunProgram()
        {
            const string key         = "testkey";
            var          cacheClient = new MemcachedClient(ConfigurationManager.GetSection("enyim.com/memcached") as IMemcachedClientConfiguration);

            cacheClient.Store(StoreMode.Add, key, "testvalue");
            var item = cacheClient.Get(key);

            Console.WriteLine(item);

            cacheClient.Store(StoreMode.Set, key, "something else");
            item = cacheClient.Get(key);
            Console.WriteLine(item);
        }
        public void Add_Study()
        {
            using (var client = new MemcachedClient())
            {
                var result1 = client.Store(StoreMode.Add, "userid", "123456");
                Assert.True(result1);

                // 不可以多次调用
                var result2 = client.Store(StoreMode.Add, "userid", "123456");
                Assert.False(result2);

                client.FlushAll();
            }
        }
Exemplo n.º 32
0
        /// <summary>
        /// 插入指定值
        /// </summary>
        /// <param name="key">缓存名称 </param>
        /// <param name="value">缓存值</param>
        /// <param name="dateTime">过期时间</param>
        /// <returns>返回是否成功</returns>
//        public static bool Set(string key, string value, int minutes = 10080)
        public static bool Set(string key, string value, DateTime dateTime)
        {
            MemcachedClient mc   = getInstance();
            var             data = mc.Get(key);

            if (data == null)
            {
                return(mc.Store(StoreMode.Add, key, value, dateTime));
            }
            else
            {
                return(mc.Store(StoreMode.Replace, key, value, dateTime));
            }
        }
Exemplo n.º 33
0
        //配置&存入&读取&删除
        public static void Test1()
        {
            #region 说明
            //NuGet:PM> Install-Package EnyimMemcached
            //关于MemCached的程序包有很多,EnyimMemcached只是其一
            //Memcache 存入数据的 3 中模式 Set、Replace、Add,根据名字就能猜出来:
            //Set:存在则覆盖,不存在则新增
            //Replace:如果存在则覆盖,并且返回 true;如果不存在则不处理,并且返回 false;(Replace,为替换,能替换的意义就是先存在)
            //Add:如果不存在则新增,并且返回 true;如果存在则不处理,并且返回 false(Add,为新增,能新增的前提是之前不存在)
            //常用的就是Set方式

            //注意数据是存放在MemCached服务器中的,你重启程序依旧在服务器中存在你存入的数据
            //但是你一旦重启memcached服务器,则数据就消失了
            #endregion

            //创建配置对象
            MemcachedClientConfiguration memConfig = new MemcachedClientConfiguration();
            memConfig.AddServer("127.0.0.1:11211");
            //若是Memcached集群,此处可以同时添加多个服务器ip地址,然后客户端根据自己的算法决定把数据写入哪个 Memcached 实例

            //创建MemcachedClient对象
            using (MemcachedClient memClient = new MemcachedClient(memConfig))
            {
                //写入MemCached中
                memClient.Store(Enyim.Caching.Memcached.StoreMode.Set, "Name", "shanzm");
                memClient.Store(Enyim.Caching.Memcached.StoreMode.Set, "Age", "100");

                //读取数据
                // string name = (string)memClient.Get("Name");//Get<T>()是一个泛型方法,你可直接使用Get()函数得到一个Object类型的对象,或提供泛型类型
                string name = memClient.Get <string>("Name");
                if (name == null)
                {
                    Console.WriteLine("无缓存");
                }
                else
                {
                    Console.WriteLine(name);
                }

                //删除数据
                Console.WriteLine(memClient.Get <string>("Age"));
                memClient.Remove("Age");
                if (null == memClient.Get <string>("Age"))
                {
                    Console.WriteLine("已经将Key为Age的数据从MemCached服务器中清除");
                }
                Console.ReadKey();
            }
        }
Exemplo n.º 34
0
 public bool Set <T>(string key, T value)
 {
     try
     {
         if (mc == null)
         {
             return(false);
         }
         return(mc.Store(StoreMode.Set, key, value));
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        public void Replace_Study()
        {
            using (var client = new MemcachedClient())
            {
                // 没有键,不能替换。
                var result1 = client.Store(StoreMode.Replace, "userid", "123456");
                Assert.False(result1);

                // 有的话,就可以。
                client.Store(StoreMode.Add, "userid", "123456");
                var result2 = client.Store(StoreMode.Replace, "userid", "123456");
                Assert.True(result2);

                client.FlushAll();
            }
        }
Exemplo n.º 36
0
 /// <summary>
 /// 添加缓存(键不存在则添加,存在则替换)
 /// </summary>
 /// <param name="key">键</param>
 /// <param name="value">值</param>
 /// <param name="minutes">缓存时间(分钟)</param>
 /// <returns></returns>
 public static bool AddCache(string key, object value, int minutes)
 {
     using (MemcachedClient mc = new MemcachedClient())
     {
         return mc.Store(StoreMode.Set, key, value, DateTime.Now.AddMinutes(minutes));
     }
 }
Exemplo n.º 37
0
        public void TestThem(List<string> servers)
        {
            var mbc = new MemcachedClientConfiguration();
            foreach (var server in servers)
            {
                IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(server), 11211);
                mbc.Servers.Add(endPoint);
            }

            _couchbaseClient = new MemcachedClient(mbc);

            _couchbaseClient.Store(StoreMode.Set, Key, Value);
            Debug.Assert((string)_couchbaseClient.Get(Key) == Value);

            List<Thread> workers = new List<Thread>();

            for (int s = 0; s < NumThreads; s++)
            {
                Thread workerThread = new Thread(Run);
                workerThread.Start();
                workers.Add(workerThread);
            }

            foreach (var thread in workers)
            {
                while (thread.IsAlive)
                {
                    Thread.Sleep(1);
                }

                thread.Join();
            }
        }
Exemplo n.º 38
0
        static void testMemcachedProviders()  
        {
            MemcachedClient client = new MemcachedClient("enyim.com/memcached");
            //存值  --不带过期时间的存储,Memcached将根据LRU来决定过期策略  
            bool result = client.Store(Enyim.Caching.Memcached.StoreMode.Add, "name", "dinglang");
            
            //带过期时间的缓存    
            //bool success = client.Store(StoreMode.Add, person.UserName, person, DateTime.Now.AddMinutes(10));   
            if (result)
            {
                Console.Write("成功存入缓存");

                //取值    
                object name = client.Get("name");
                if (name != null)
                {
                    Console.Write("取出的值为:" + name);
                }
                else
                {
                    Console.Write("取值失败");
                }
            }
            else
            {
                Console.Write("存入缓存失败");
            }
        }    
Exemplo n.º 39
0
 /// <summary>
 /// 添加缓存(键不存在则添加,存在则替换)
 /// </summary>
 /// <param name="key">键</param>
 /// <param name="value">值</param>
 /// <returns></returns>
 public static bool AddCache(string key, object value)
 {
     using (MemcachedClient mc = new MemcachedClient())
     {
         return mc.Store(StoreMode.Set, key, value);
     }
 }
        public void DecrementTest()
        {
            MemcachedClient mc = new MemcachedClient();
            mc.Store(StoreMode.Set, "VALUE", "100");

            Assert.AreEqual(98L, mc.Decrement("VALUE", 2));
            Assert.AreEqual(88L, mc.Decrement("VALUE", 10));
        }
Exemplo n.º 41
0
        public void CanCacheString()
        {
            var client = new MemcachedClient();

            client.Store(StoreMode.Add, "a", "b");
            var result = client.Get<string>("a");

            Assert.AreEqual("b", result);
        }
Exemplo n.º 42
0
        public void CanCacheList()
        {
            var client = new MemcachedClient();
            var list = new List<string> { "a", "b" };

            client.Store(StoreMode.Set, "d", list);

            var result = client.Get<List<string>>("d");
            Assert.AreEqual(2, result.Count);
            Assert.AreEqual("a", result[0]);
            Assert.AreEqual("b", result[1]);
        }
        static MemcachedContainerStrategy()
        {
            // //初始化memcache服务器池
            //SockIOPool pool = SockIOPool.GetInstance();
            ////设置Memcache池连接点服务器端。
            //pool.SetServers(serverlist);
            ////其他参数根据需要进行配置

            //pool.InitConnections = 3;
            //pool.MinConnections = 3;
            //pool.MaxConnections = 5;

            //pool.SocketConnectTimeout = 1000;
            //pool.SocketTimeout = 3000;

            //pool.MaintenanceSleep = 30;
            //pool.Failover = true;

            //pool.Nagle = false;
            //pool.Initialize();

            //cache = new MemcachedClient();
            //cache.EnableCompression = false;
            try
            {
                //config.Authentication.Type = typeof(PlainTextAuthenticator);
                //config.Authentication.Parameters["userName"] = "******";
                //config.Authentication.Parameters["password"] = "******";
                //config.Authentication.Parameters["zone"] = "zone";//domain?   ——Jeffrey 2015.10.20
                DateTime dt1 = DateTime.Now;
                var config = GetMemcachedClientConfiguration();
                var cache = new MemcachedClient(config);

                var testKey = Guid.NewGuid().ToString();
                var testValue = Guid.NewGuid().ToString();
                cache.Store(StoreMode.Set, testKey, testValue);
                var storeValue = cache.Get(testKey);
                if (storeValue as string != testValue)
                {
                    throw new Exception("MemcachedStrategy失效,没有计入缓存!");
                }
                cache.Remove(testKey);
                DateTime dt2 = DateTime.Now;

                WeixinTrace.Log(string.Format("MemcachedStrategy正常启用,启动及测试耗时:{0}ms", (dt2 - dt1).TotalMilliseconds));
            }
            catch (Exception ex)
            {
                //TODO:记录是同日志
                WeixinTrace.Log(string.Format("MemcachedStrategy静态构造函数异常:{0}", ex.Message));
            }
        }
        public void AddSetReplaceTest()
        {
            MemcachedClient mc = new MemcachedClient();
            mc.Store(StoreMode.Set, "VALUE", "1");

            Assert.AreEqual("1", mc.Get("VALUE"), "Store failed");

            mc.Store(StoreMode.Add, "VALUE", "2");
            Assert.AreEqual("1", mc.Get("VALUE"), "Item should not have been Added");

            mc.Store(StoreMode.Replace, "VALUE", "4");
            Assert.AreEqual("4", mc.Get("VALUE"), "Replace failed");

            mc.Remove("VALUE");

            mc.Store(StoreMode.Replace, "VALUE", "8");
            Assert.IsNull(mc.Get("VALUE"), "Item should not have been Replaced");

            mc.Remove("VALUE");

            mc.Store(StoreMode.Add, "VALUE", "16");
            Assert.AreEqual("16", mc.Get("VALUE"), "Add failed");
        }
Exemplo n.º 45
0
        public void CanCacheDTO()
        {
            var client = new MemcachedClient();
            var obj = new Dto
            {
                Name = "b",
                Title = "c"
            };

            client.Store(StoreMode.Set, "c", obj);
            var result = client.Get<Dto>("c");

            Assert.AreEqual("b", result.Name);
            Assert.AreEqual("c", result.Title);
        }
        public void Get_Study()
        {
            using (var client = new MemcachedClient())
            {
                // 没有键,返回null。
                var result1 = client.Get("userid");
                Assert.Null(result1);

                client.Store(StoreMode.Set, "userid", "123456");
                var result2 = client.Get("userid");
                Assert.AreEqual("123456", result2);

                client.FlushAll();
            }
        }
Exemplo n.º 47
0
 public void StoreWithDefaultTranscoder()
 {
     var config = GetConfig();
     SomeType obj = new SomeType { Id = 1, Name = "abc" }, clone;
     using (var client = new MemcachedClient(config))
     {
         client.Store(StoreMode.Set, "raw1", obj);
     }
     using (var client = new MemcachedClient(config))
     {
         clone = (SomeType) client.Get("raw1");
     }
     Assert.AreEqual(1, clone.Id);
     Assert.AreEqual("abc", clone.Name);
 }
Exemplo n.º 48
0
        private static void StressTest(MemcachedClient client, string keyPrefix)
        {
            var i = 0;
            var last = true;

            var progress = @"-\|/".ToCharArray();
            Console.CursorVisible = false;
            Dictionary<bool, int> counters = new Dictionary<bool, int>() { { true, 0 }, { false, 0 } };

            while (true)
            {
                var key = keyPrefix + i;
                var state = client.Store(StoreMode.Set, key, i) & client.Get<int>(key) == i;

                Action updateTitle = () => Console.Title = "Success: " + counters[true] + " Fail: " + counters[false];

                if (state != last)
                {
                    Console.ForegroundColor = state ? ConsoleColor.White : ConsoleColor.Red;
                    Console.Write(".");

                    counters[state] = 0;
                    last = state;

                    updateTitle();
                }
                else if (i % 200 == 0)
                {
                    //Console.ForegroundColor = state ? ConsoleColor.White : ConsoleColor.Red;

                    //Console.Write(progress[(i / 200) % 4]);
                    //if (Console.CursorLeft == 0)
                    //{
                    //    Console.CursorLeft = Console.WindowWidth - 1;
                    //    Console.CursorTop -= 1;
                    //}
                    //else
                    //{
                    //    Console.CursorLeft -= 1;
                    //}

                    updateTitle();
                }

                i++;
                counters[state] = counters[state] + 1;
            }
        }
Exemplo n.º 49
0
        public void CanConnectToMemcached()
        {
            var config = GetConfig();
            string s1 = Guid.NewGuid().ToString();
            string s2 = Guid.NewGuid().ToString();
            Assert.AreNotEqual(s1, s2);
            using (var client1 = new MemcachedClient(config))
            using (var client2 = new MemcachedClient(config))
            {
                client1.Store(StoreMode.Set, "key1", s1);
                client2.Store(StoreMode.Set, "key2", s2);

                Assert.AreEqual(s2, client1.Get("key2"), "client1.key2");
                Assert.AreEqual(s1, client2.Get("key1"), "client2.key1");
            }
        }
Exemplo n.º 50
0
 public void ShouldBeAbleToCacheContractTypes()
 {
     ContractType original = new ContractType { Id = 123, Name = "abc" }, clone;
     using (var client = new MemcachedClient())
     {
         client.Store(StoreMode.Set, "ShouldBeAbleToCacheBasicTypes", original);
     }
     using (var client = new MemcachedClient())
     {
         clone = client.Get<ContractType>("ShouldBeAbleToCacheBasicTypes");
     }
     Assert.IsNotNull(clone);
     Assert.AreNotSame(original, clone);
     Assert.AreEqual(original.Id, clone.Id);
     Assert.AreEqual(original.Name, clone.Name);
 }
Exemplo n.º 51
0
        public void Compatibility() {
            using (MemcachedClient client = new MemcachedClient("enyim.com/memcached")) {
                var array = new List<Object>();
                array.Add(new Object());
                array.Add(Guid.NewGuid().GetHashCode());
                array.Add(1.1m);
                array.Add(Guid.NewGuid());
                array.Add(Guid.NewGuid().GetHashCode().ToString());
                array.Add(new[] { 1, 2 });
                array.Add(new[] { Guid.NewGuid().ToString() });
                array.Add(new Person {
                    Id = 2,
                    Name = "Rattz",
                    Address = new Address {
                        Line1 = "Haidin Shuzhoujie",
                        Line2 = "Beijing China"
                    }
                });

                var transcoderProp = typeof(MemcachedClient).GetField("transcoder", BindingFlags.Instance | BindingFlags.NonPublic);
                var region = Guid.NewGuid().ToString("n");
                region = "Compatibility";
                for (var i = 0; i < array.Count; i++) {
                    if ((Guid.NewGuid().GetHashCode() % 2) == 1) {
                        transcoderProp.SetValue(client, new NewtonsoftJsonTranscoder());
                    }
                    else {
                        transcoderProp.SetValue(client, new DefaultTranscoder());
                    }

                    var key = region + "_" + i;
                    client.Store(StoreMode.Set, key, array[i]);

                    transcoderProp.SetValue(client, new NewtonsoftJsonTranscoder());
                    Object cache;
                    Assert.IsTrue(client.TryGet(key, out cache));
                    //Assert.AreEqual(array[i].GetType(), cache.GetType());

                    Assert.AreEqual(JsonConvert.SerializeObject(array[i]),
                        JsonConvert.SerializeObject(cache));
                }
            }
        }
Exemplo n.º 52
0
        public void Online() {
            using (MemcachedClient client = new MemcachedClient("enyim.com/memcached")) {
                String key = Guid.NewGuid().ToString("n");
                Object value = client.Get(key);
                Assert.IsNull(value);

                var exist = client.TryGet(key, out value);
                Assert.IsFalse(exist);
                Assert.IsNull(value);

                value = new Person {
                    Id = 2,
                    Name = "Rattz",
                    Address = new Address {
                        Line1 = "Haidin Shuzhoujie",
                        Line2 = "Beijing China"
                    }
                };
                client.Store(StoreMode.Set, key, value);
                exist = client.TryGet(key, out value);
                Assert.IsTrue(exist);
                Assert.IsNotNull(value);
            }
        }
Exemplo n.º 53
0
 public MemcachedCache()
 {
     Cache = new MemcachedClient();
     List<string> keys = new List<string>();
     Cache.Store(StoreMode.Add, "keys", keys);
 }
Exemplo n.º 54
0
		public void StoreArrayTest()
		{
			byte[] bigBuffer = new byte[200 * 1024];

			for (int i = 0; i < bigBuffer.Length / 256; i++)
			{
				for (int j = 0; j < 256; j++)
				{
					bigBuffer[i * 256 + j] = (byte)j;
				}
			}

			MemcachedClient mc = new MemcachedClient();

			mc.Store(StoreMode.Set, "BigBuffer", bigBuffer);

			byte[] bigBuffer2 = mc.Get<byte[]>("BigBuffer");

			for (int i = 0; i < bigBuffer.Length / 256; i++)
			{
				for (int j = 0; j < 256; j++)
				{
					if (bigBuffer2[i * 256 + j] != (byte)j)
					{
						Assert.AreEqual(j, bigBuffer[i * 256 + j], "Data should be {0} but its {1}");
						break;
					}
				}
			}
		}
Exemplo n.º 55
0
		public void ExpirationTest()
		{
			MemcachedClient mc = new MemcachedClient();

			mc.Store(StoreMode.Set, "ExpirationTest:TimeSpan", "ExpirationTest:TimeSpan", new TimeSpan(0, 0, 5));

			Assert.AreEqual("ExpirationTest:TimeSpan", mc.Get("ExpirationTest:TimeSpan"), "Expires:Timespan store failed");

			Thread.Sleep(8000);
			Assert.IsNull(mc.Get("ExpirationTest:TimeSpan"), "ExpirationTest:TimeSpan item did not expire");

			DateTime expiresAt = DateTime.Now.AddSeconds(5);

			mc.Store(StoreMode.Set, "Expires:DateTime", "Expires:DateTime", expiresAt);

			Assert.AreEqual("Expires:DateTime", mc.Get("Expires:DateTime"), "Expires:DateTime store failed");

			expiresAt = expiresAt.AddSeconds(4); // wait more than the expiration

			while (DateTime.Now < expiresAt)
			{
				Thread.Sleep(100);
			}

			object o = mc.Get("Expires:DateTime");

			Assert.IsNull(o, "Expires:DateTime item did not expire");
		}
Exemplo n.º 56
0
		public void MultiGetTest()
		{
			// note, this test will fail, if memcached version is < 1.2.4
			MemcachedClient mc = new MemcachedClient();

			List<string> keys = new List<string>();

			for (int i = 0; i < 100; i++)
			{
				string k = "multi_get_test_" + i;
				keys.Add(k);

				mc.Store(StoreMode.Set, k, i);
			}

			IDictionary<string, ulong> cas;
			IDictionary<string, object> retvals = mc.Get(keys, out cas);

			Assert.AreEqual<int>(100, retvals.Count, "MultiGet should have returned 100 items.");

			object value;

			for (int i = 0; i < retvals.Count; i++)
			{
				string key = "multi_get_test_" + i;

				Assert.IsTrue(retvals.TryGetValue(key, out value), "missing key: " + key);
				Assert.AreEqual(value, i, "Invalid value returned: " + value);
			}
		}
Exemplo n.º 57
0
		public void FlushTest()
		{
			MemcachedClient mc = new MemcachedClient();
			mc.Store(StoreMode.Set, "qwer", "1");
			mc.Store(StoreMode.Set, "tyui", "1");
			mc.Store(StoreMode.Set, "polk", "1");
			mc.Store(StoreMode.Set, "mnbv", "1");
			mc.Store(StoreMode.Set, "zxcv", "1");
			mc.Store(StoreMode.Set, "gfsd", "1");

			Assert.AreEqual("1", mc.Get("mnbv"), "Setup for FlushAll() failed");

			mc.FlushAll();

			Assert.IsNull(mc.Get("qwer"), "FlushAll() failed.");
			Assert.IsNull(mc.Get("tyui"), "FlushAll() failed.");
			Assert.IsNull(mc.Get("polk"), "FlushAll() failed.");
			Assert.IsNull(mc.Get("mnbv"), "FlushAll() failed.");
			Assert.IsNull(mc.Get("zxcv"), "FlushAll() failed.");
			Assert.IsNull(mc.Get("gfsd"), "FlushAll() failed.");
		}
Exemplo n.º 58
0
        private ErrorTypes AddToMCWithCas(string sKey, TaskResultData oTast, ulong cas)
        {
            ErrorTypes oError = ErrorTypes.NoError;
            try
            {
                using (MemcachedClient oMc = new MemcachedClient(m_oMcConfig))
                {
                    string sDataToStore = null;

                    XmlSerializer oXmlSerializer = new XmlSerializer(typeof(TaskResultData));
                    using (StringWriter oStringWriter = new StringWriter())
                    {
                        oXmlSerializer.Serialize(oStringWriter, oTast);
                        sDataToStore = oStringWriter.ToString();
                    }

                    if (cas != 0)
                        oMc.Cas(StoreMode.Set, sKey, sDataToStore, m_oTtl, cas);
                    else
                        oMc.Store(StoreMode.Set, sKey, sDataToStore, m_oTtl);
                }
            }
            catch
            {
                oError = ErrorTypes.TaskResult;
            }
                
            return oError;
        }
Exemplo n.º 59
0
        private static long TestMemcachedWrite(int length)
        {
            var client = new MemcachedClient();

            var sw = Stopwatch.StartNew();

            for (int i = 0; i < length; i++)
            {
                client.Store(StoreMode.Set, "asdfasdf" + i.ToString(), stringToTest);
            }

            sw.Stop();
            client.Dispose();
            return sw.ElapsedMilliseconds;
        }
Exemplo n.º 60
0
		public void StoreLongTest()
		{
			MemcachedClient mc = new MemcachedClient();
			mc.Store(StoreMode.Set, "TestLong", 65432123456L);

			Assert.AreEqual(65432123456L, mc.Get<long>("TestLong"));
		}