/// <summary>
        /// Function to add a new item to the output cache. If there is already a value in the cache for the
        /// specified key, the provider must return that value and must not store the data passed by using the Add method
        /// parameters. The Add method stores the data if it is not already in the cache and returns the value
        /// read from the cache if it already exists.
        /// </summary>
        /// <param name="key">A unique identifier for entry</param>
        /// <param name="entry">The content to add to the output cache</param>
        /// <param name="utcExpiry">The time and date on which the cached entry expires</param>
        /// <returns>
        /// The value that identifies what was in the cache, or the value that was just added if it was not
        /// </returns>
        public override object Add(
            string key,
            object entry,
            DateTime utcExpiry)
        {
            // Fix the key
            key = SanitizeKey(key);

            // Make sure that the expiration date is flagged as UTC. The client converts the expiration to
            // UTC to calculate the UNIX time and this way we can skip the UTC -> ToLocal -> ToUTC chain
            utcExpiry = DateTime.SpecifyKind(utcExpiry, DateTimeKind.Utc);

            // We should only store the item if it's not in the cache. So try to add it and if it
            // succeeds, return the value we just stored
            if (client.Store(StoreMode.Add, key, entry, utcExpiry))
            {
                return(entry);
            }

            // If it's in the cache we should return it
            var retval = client.Get(key);

            // If the item got evicted between the Add and the Get (very rare) we store it anyway,
            // but this time with Set to make sure it always gets into the cache
            if (retval == null)
            {
                client.Store(StoreMode.Set, key, entry, utcExpiry);
                retval = entry;
            }

            // Return the value read from the cache if it was present
            return(retval);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Get the specified cacheKey, dataRetriever and expiration.
        /// </summary>
        /// <returns>The get.</returns>
        /// <param name="cacheKey">Cache key.</param>
        /// <param name="dataRetriever">Data retriever.</param>
        /// <param name="expiration">Expiration.</param>
        /// <typeparam name="T">The 1st type parameter.</typeparam>
        public CacheValue <T> Get <T>(string cacheKey, Func <T> dataRetriever, TimeSpan expiration) where T : class
        {
            ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey));
            ArgumentCheck.NotNegativeOrZero(expiration, nameof(expiration));

            if (_memcachedClient.Get(this.HandleCacheKey(cacheKey)) is T result)
            {
                if (_options.EnableLogging)
                {
                    _logger?.LogInformation($"Cache Hit : cachekey = {cacheKey}");
                }

                return(new CacheValue <T>(result, true));
            }

            var item = dataRetriever?.Invoke();

            if (item != null)
            {
                this.Set(cacheKey, item, expiration);
                return(new CacheValue <T>(item, true));
            }
            else
            {
                if (_options.EnableLogging)
                {
                    _logger?.LogInformation($"Cache Missed : cachekey = {cacheKey}");
                }

                return(CacheValue <T> .NoValue);
            }
        }
            public ISessionStateItemCollection Get(string id, out int timeout)
            {
                var key   = GetKey(id);
                var entry = _client.Get <SessionEntry>(key);

                ISessionStateItemCollection sessionStateItemCollection = new SessionStateItemCollection();

                if (entry == null)
                {
                    entry = new SessionEntry();
                }
                else
                {
                    foreach (var item in entry.Dictionary)
                    {
                        sessionStateItemCollection[item.Key] = item.Value.Deserialize();
                    }
                }

                timeout = entry.Timeout;

                //更新过期时间。
                _client.Store(StoreMode.Set, key, entry, TimeSpan.FromMinutes(timeout));

                return(sessionStateItemCollection);
            }
Ejemplo n.º 4
0
        public async Task <IActionResult> Add(string key, [FromBody] AddCacheItem item)
        {
            if (item == null)
            {
                return(this.NullValueErrorResult(key, _logger));
            }

            if (!item.Seconds.HasValue)
            {
                item.Seconds = 0;
            }

            var value = _memcachedClient.Get(key);

            if (value == null)
            {
                await _memcachedClient.AddAsync(key, item.Value, item.Seconds.Value);

                value = _memcachedClient.Get(key);
                if (value != null)
                {
                    return(StatusCode(StatusCodes.Status201Created));
                }
                else
                {
                    return(this.ApiErrorResult(_logger));
                }
            }
            else
            {
                var error = new { error = "Key Exists", description = "The key:[" + key + "] already exist." };
                return(StatusCode(StatusCodes.Status400BadRequest, error));
            }
        }
Ejemplo n.º 5
0
        byte[] GetValue(string key)
#endif
        {
            string subsegmentName = memCacheConfigNode ?? "local";

            if (AwsUtilityMethods.IsRunningOnAWS)
            {
                BeginSubsegment("GET");
            }

            try
            {
#if UseJsonSerialization
                return(Client.Get <string>(key));
#else
                return(Client.Get <byte[]>(key));
#endif
            }
            catch (Exception ex)
            {
                if (AwsUtilityMethods.IsRunningOnAWS)
                {
                    AWSXRayRecorder.Instance.AddException(ex);
                }
                logger.ErrorFormat("Network: Memcache Get Error. '{0}'", ex.Message);
                throw;
            }
            finally
            {
                if (AwsUtilityMethods.IsRunningOnAWS)
                {
                    AWSXRayRecorder.Instance.EndSubsegment();
                }
            }
        }
        public void ReleaseItem(System.Web.HttpContext context, string id, object lockId)
        {
            var session = client.Get <MemcachedSessionDo>(id);

            if (session != null)
            {
                session.Locked = false;
                client.Store(StoreMode.Set, id, session, DateTime.Now.AddMinutes(sessionStateSection.Timeout.TotalMinutes));
            }
        }
Ejemplo n.º 7
0
        public bool Exist(string contextKey, string dataKey)
        {
            var key = GeneralContextKey(contextKey + dataKey);

            var result = _client.Get(key);

            if (result == null)
            {
                return(false);
            }
            return(true);
        }
        public override object Add(string key, object entry, DateTime utcExpiry)
        {
            var item = _client.Get(key);

            if (item != null)
            {
                return(item);
            }

            _client.Store(StoreMode.Add, key, entry, utcExpiry);
            return(entry);
        }
 public override object Add(string key, object entry, DateTime utcExpiry)
 {
     if (client.Get(key) != null)
     {
         return(client.Get(key));
     }
     else
     {
         //var objString = entry.ToString();
         bool result = client.Store(StoreMode.Set, key, entry);
         return(result.ToString());
     }
 }
        public void AssertGetSetIntValue(IMemcachedClient cacheClient)
        {
            cacheClient.Set("test:intkey1", 1);
            var value = cacheClient.Get("test:intkey1");

            Assert.That(value, Is.EqualTo(1));
        }
Ejemplo n.º 11
0
        static async Task RunSync(int cnt)
        {
            await TrySingle();

            var sw     = Stopwatch.StartNew();
            var errCnt = 0;
            var tasks  = Enumerable.Range(0, cnt)
                         .Select(i => Task.Run(() =>
            {
                try
                {
                    var foo = _memcachedClient.Get <Foo>(_cacheKey);
                    if (foo == null)
                    {
                        Interlocked.Increment(ref errCnt);
                    }
                }
                catch (Exception e)
                {
                    Interlocked.Increment(ref errCnt);
                }
            }));
            await Task.WhenAll(tasks);

            sw.Stop();

            Thread.Sleep(TimeSpan.FromSeconds(3));
            await TrySingle();

            Console.WriteLine("Use Get");
            Console.WriteLine($"Time: {sw.ElapsedMilliseconds}ms");
            Console.WriteLine($"Failures: {errCnt}");
            Console.WriteLine($"Avg: {Convert.ToDouble(sw.ElapsedMilliseconds) / Convert.ToDouble(cnt)}ms");
        }
        public override object Add(string key, object entry, DateTime utcExpiry)
        {
            // make sure that the expiration date is flagges as utc.
            // the client converts the expiration to utc to calculate the unix time
            // and this way we can skip the utc -> ToLocal -> ToUtc chain
            utcExpiry = DateTime.SpecifyKind(utcExpiry, DateTimeKind.Utc);

            // we should only store the item if it's not in the cache
            if (this.client.Store(StoreMode.Add, key, entry, utcExpiry))
            {
                return(null);
            }

            // if it's in the cache we should return it
            var retval = client.Get(key);

            // the item got evicted between the Add and the Get (very rare)
            // so we store it anyway, but this time with Set to make sure it gets into the cache
            if (retval == null)
            {
                this.client.Store(StoreMode.Set, key, entry, utcExpiry);
            }

            return(retval);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="cacheKey">缓存类型</param>
        /// <returns></returns>
        public CacheValue <T> Get <T>(string cacheKey)
        {
            Check.NotNullOrEmpty(cacheKey, nameof(cacheKey));

            if (_memcachedClient.Get(this.HandleCacheKey(cacheKey)) is T result)
            {
                WriteLog($"缓存击中 : cacheKey = {cacheKey}");
                CacheStatsInfo.OnHit();
                return(new CacheValue <T>(result, true));
            }

            CacheStatsInfo.OnMiss();
            WriteLog($"缓存穿透 : cacheKey = {cacheKey}");

            return(CacheValue <T> .NoValue);
        }
Ejemplo n.º 14
0
        public Task <V> GetAsync(string key)
        {
            string cachekey = GetMemcacheKey(key);
            var    item     = client.Get <V>(cachekey);

            return(Task.FromResult(item));
        }
        public async Task <object> GetAsync(string cacheKey, Type type)
        {
            if (!(await Task.FromResult(_cache.Get(cacheKey)) is JObject result))
            {
                return(null);
            }

            return(result.ToObject(type));
        }
Ejemplo n.º 16
0
        public object Get(string key)
        {
            object value = null;

            IMemcachedClient client = this.GetMemcachedClient();

            value = client.Get(key);

            return(value);
        }
Ejemplo n.º 17
0
        public static T GetJson <T>(this IMemcachedClient client, string key) where T : class
        {
            T   obj        = default(T);
            var jsonString = client.Get <string>(key);

            if (!string.IsNullOrWhiteSpace(jsonString))
            {
                obj = JsonConvert.DeserializeObject <T>(jsonString);
            }

            return(obj);
        }
        /// <summary>
        /// Get the specified cacheKey, dataRetriever and expiration.
        /// </summary>
        /// <returns>The get.</returns>
        /// <param name="cacheKey">Cache key.</param>
        /// <param name="dataRetriever">Data retriever.</param>
        /// <param name="expiration">Expiration.</param>
        /// <typeparam name="T">The 1st type parameter.</typeparam>
        public CacheValue <T> Get <T>(string cacheKey, Func <T> dataRetriever, TimeSpan expiration) where T : class
        {
            ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey));
            ArgumentCheck.NotNegativeOrZero(expiration, nameof(expiration));

            if (_memcachedClient.Get(this.HandleCacheKey(cacheKey)) is T result)
            {
                return(new CacheValue <T>(result, true));
            }

            var item = dataRetriever?.Invoke();

            if (item != null)
            {
                this.Set(cacheKey, item, expiration);
                return(new CacheValue <T>(item, true));
            }
            else
            {
                return(CacheValue <T> .NoValue);
            }
        }
Ejemplo n.º 19
0
        public virtual T Get <T>(string key)
        {
            var data = memcachedClient.Get <T>(key);

            if (data == null)
            {
                return(default(T));
            }
            else
            {
                return(data);
            }
        }
Ejemplo n.º 20
0
        public T Get <T>(string cacheKey) where T : class
        {
            try
            {
                var sanitisedKey = SanitiseCacheKey(cacheKey);
                // try per request cache first, but only if in a web context
                var requestCacheData = _requestCacheHelper.TryGetItemFromPerRequestCache <T>(cacheKey);
                if (requestCacheData != null)
                {
                    return(requestCacheData);
                }

                return(_client.Get <T>(sanitisedKey));
            }
            catch (Exception ex)
            {
                _logger.WriteException(ex);
            }
            return(null);
        }
        public bool TryGetAccessToken(out UserAccessToken accessToken)
        {
            if (CurrentAccessToken != null)
            {
                accessToken = CurrentAccessToken;
                return(true);
            }

            string hash;

            if (TryGetHashFromCookie(out hash))
            {
                accessToken        = _memcachedClient.Get <UserAccessToken>(hash);
                CurrentAccessToken = accessToken;
                return(accessToken != null);
            }

            accessToken = null;
            return(false);
        }
Ejemplo n.º 22
0
        public static double SetAndGetEnyim(int numberOfOperations, IMemcachedClient cli)
        {
            var start = DateTime.Now;

            //enyim is synchronous so no need to handle callbacks
            for (var i = 0; i < numberOfOperations; i++)
            {
                var key = "ey" + i;
                var value = key + " value";
                cli.Store(StoreMode.Set, key, value);
            }

            for (var i = 0; i < numberOfOperations; i++)
            {
                var key = "ey" + i;
                var value = cli.Get(key);
            }

            return (DateTime.Now - start).TotalSeconds;
        }
Ejemplo n.º 23
0
 public object Get(string key)
 {
     return(_memcachedClient.Get(key));
 }
Ejemplo n.º 24
0
 public T Get <T>(string key)
 {
     return(_client.Get <T>(key));
 }
 public override T Get <T>(string key)
 {
     return(_memcachedClient.Get <T>(key));
 }
 public void AssertGetSetIntValue(IMemcachedClient cacheClient)
 {
     cacheClient.Set("test:intkey1", 1);
     var value = cacheClient.Get("test:intkey1");
     Assert.That(value, Is.EqualTo(1));
 }
 /// <summary>
 ///
 /// </summary>
 /// <param name="key"></param>
 /// <returns></returns>
 public override object Get(string key)
 {
     return(client.Get(GetCacheKey(key)));
 }
Ejemplo n.º 28
0
 public bool GermPlasmProcessed(string reportName, int reportId, long germPlasmId)
 {
     return(memcachedClient.Get($"{reportName}_{germPlasmId}") != null);
 }
Ejemplo n.º 29
0
 public T Get <T>(string key)
 {
     return(mc.Get <T>(key));
 }
Ejemplo n.º 30
0
 public T Get <T>(string key) where T : class
 {
     return(_memcachedClient.Get <T>(key));
 }
Ejemplo n.º 31
0
 public string Get(string key)
 {
     return(_client.Get <string>(key));
 }
Ejemplo n.º 32
0
 /// <summary>
 /// Check for item in cache
 /// </summary>
 /// <param name="key">Name of cached item</param>
 /// <returns>A boolean if the object exists</returns>
 public static bool Exists(string key)
 {
     return(Cache.Get(key) != null);
 }