public async Task Tests_redis_live_connection() { const string url = "http://thecatapi.com/api/images/get?format=html"; RedisCacheOptions options = new RedisCacheOptions { Configuration = "localhost", InstanceName = "example-tests" + Guid.NewGuid() // create a new instance name to ensure a unique key naming to have consistent test results }; var handler = new RedisCacheHandler(new HttpClientHandler(), CacheExpirationProvider.CreateSimple(TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(5)), options); using (var client = new HttpClient(handler)) { for (int i = 0; i < 5; i++) { var sw = Stopwatch.StartNew(); Debug.Write($"Getting data from {url}, iteration #{i + 1}..."); var result = await client.GetAsync(url); var content = await result.Content.ReadAsStringAsync(); Debug.WriteLine($" completed in {sw.ElapsedMilliseconds}ms. Content was {content}."); } } StatsResult stats = handler.StatsProvider.GetStatistics(); stats.Total.CacheHit.Should().Be(4); stats.Total.CacheMiss.Should().Be(1); }
/// <summary> /// Get Ticket available time. /// </summary> /// <param name="ticketId">The identity ticket.</param> /// <returns></returns> public int GetTime(int ticketId) { int result = 0; var transections = RedisCacheHandler.GetValue(ConstantValue.TicketTransectionKey + ticketId.ToString(), () => { return(this.FuncGetValue(ticketId).ToList()); }); foreach (var item in transections) { if (item.Status == ConstantValue.TicketStatusWaiting || item.Status == ConstantValue.TicketStatusClose || item.Status == ConstantValue.TicketStatusGetReq) { continue; } var endTime = DateTime.Now; if (item.EndDate.HasValue) { endTime = item.EndDate.Value; } var diffTime = endTime - item.StartDate.Value; result = Convert.ToInt32(diffTime.TotalMinutes); } return(result); }
static void Main(string[] args) { //Config { //var options = new JsonConfigurationHelper().Get<CacheOptions>("Cache", "", true); //if (options == null) // Console.WriteLine("配置文件错误"); } //MemeoryCache { IMemoryCache memory = new MemoryCache(Options.Create(new MemoryCacheOptions())); ICacheHandler MemoryCahce = new MemoryCacheHandler(memory); MemoryCahce.Set("a", "测试内存缓存"); MemoryCahce.Get("a"); Console.WriteLine(MemoryCahce.Get("a")); } //RedisCache { var Redis = new RedisCacheHelper(); ICacheHandler RedisCache = new RedisCacheHandler(Redis); RedisCache.Set("b", "测试Redis缓存"); RedisCache.Get("b"); Console.WriteLine(RedisCache.Get("b")); } }
public async Task Invalidates_cache_correctly() { // setup var testMessageHandler = new TestMessageHandler(); var cache = new Mock <IDistributedCache>(MockBehavior.Strict); var url = "http://unittest/"; var key = HttpMethod.Get + url; var cacheResult = new CacheData(new byte[0], new HttpResponseMessage(HttpStatusCode.OK), null, null).Serialize(); var nonCacheResult = default(byte[]); var currentResult = nonCacheResult; cache.Setup(c => c.GetAsync(key, It.IsAny <CancellationToken>())).ReturnsAsync(currentResult); cache.Setup(c => c.RemoveAsync(key, It.IsAny <CancellationToken>())).Returns(Task.FromResult(true)).Callback(() => currentResult = nonCacheResult); cache.Setup(c => c.SetAsync(key, It.IsAny <byte[]>(), It.IsAny <DistributedCacheEntryOptions>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(true)) .Callback(() => currentResult = cacheResult); var cacheExpirationPerStatusCode = new Dictionary <HttpStatusCode, TimeSpan> { { (HttpStatusCode)200, TimeSpan.FromHours(1) } }; var handler = new RedisCacheHandler(testMessageHandler, cacheExpirationPerStatusCode, cache.Object); var client = new HttpClient(handler); // execute twice, with cache invalidation in between var uri = new Uri(url); await client.GetAsync(uri); await handler.InvalidateCache(uri, HttpMethod.Get); await client.GetAsync(uri); // validate testMessageHandler.NumberOfCalls.Should().Be(2); }
/// <summary> /// Save refresh token into storage. /// </summary> /// <param name="email">The owner refresh token.</param> /// <param name="refreshToken">The refresh token value.</param> private void SaveRefreshToken(string email, string refreshToken) { var model = new RefreshTokenModel { RefreshToken = refreshToken }; RedisCacheHandler.SetValue(email, model); }
/// <summary> /// Save new ticket to redis cache. /// </summary> /// <param name="data">The ticket information.</param> private void SaveRedisCacheTicket(Ticket data) { var ticketList = RedisCacheHandler.GetValue(ConstantValue.TicketInfoKey, () => { return(this.FuncGetValue().ToList()); }); ticketList.Add(this.InitialTicketViewModel(_mapper.Map <Ticket, TicketViewModel>(data))); RedisCacheHandler.SetValue(ConstantValue.TicketInfoKey, ticketList); }
/// <summary> /// Save new ticket comment to redis cache. /// </summary> /// <param name="data">The ticket information.</param> private void SaveRedisCacheTicketTransection(TicketTransection data) { var ticketList = RedisCacheHandler.GetValue(ConstantValue.TicketTransectionKey + data.TicketId.ToString(), () => { return(this.FuncGetValue(data.TicketId.Value).ToList()); }); ticketList.Add(data); RedisCacheHandler.SetValue(ConstantValue.TicketTransectionKey + data.TicketId.ToString(), ticketList); }
/// <summary> /// Save new ticket comment to redis cache. /// </summary> /// <param name="data">The ticket information.</param> private void SaveRedisCacheTicketComments(TicketComment data) { var ticketList = RedisCacheHandler.GetValue(ConstantValue.TicketCommentKey + data.TicketId.Value.ToString(), () => { return(this.FuncGetValue(data.TicketId.Value).ToList()); }); ticketList.Add(this.InitialTicketCommentViewModel(data)); RedisCacheHandler.SetValue(ConstantValue.TicketCommentKey + data.TicketId.Value.ToString(), ticketList); }
/// <summary> /// Validate refresh token in storage. /// </summary> /// <param name="email">The owner refresh token.</param> /// <param name="refreshToken">The refresh token value.</param> /// <returns></returns> public bool ValidateRefreshToken(string email, string refreshToken) { var userInfo = RedisCacheHandler.GetValue <RefreshTokenModel>(email); if (userInfo != null && userInfo.RefreshToken == refreshToken) { return(true); } return(false); }
/// <summary> /// Get Refresh Token. /// </summary> /// <param name="email">The owner refresh token.</param> /// <returns></returns> public string GetRefreshToken(string email) { string result = string.Empty; var userInfo = RedisCacheHandler.GetValue <RefreshTokenModel>(email); if (userInfo != null) { result = userInfo.RefreshToken; } return(result); }
/// <summary> /// Update ticket to redis cache. /// </summary> /// <param name="data">The ticket information.</param> private void UpdateRedisCacheTicketTransection(TicketTransection model) { var ticketList = RedisCacheHandler.GetValue(ConstantValue.TicketTransectionKey + model.TicketId.ToString(), () => { return(this.FuncGetValue(model.TicketId.Value).ToList()); }); var item = ticketList.FirstOrDefault(x => x.Id == model.Id); item.EndDate = model.EndDate; RedisCacheHandler.SetValue(ConstantValue.TicketTransectionKey + model.TicketId.ToString(), ticketList); }
/// <summary> /// Get Ticket List by company code. /// </summary> /// <returns></returns> public IEnumerable <TicketViewModel> GetCompanyTicket() { var data = RedisCacheHandler.GetValue(ConstantValue.TicketInfoKey, () => { return(this.FuncGetValue().ToList()); }).Where(x => x.CompanyCode == _token.ComCode).OrderByDescending(x => x.Id); foreach (var item in data) { item.OnlineTime = _ticketTransection.GetTime(item.Id); } return(data); }
public bool ClearCache() { RedisCacheHandler _redishCacheHandler = new RedisCacheHandler(); try { _redishCacheHandler.ClearCache(); return(true); } catch (Exception ex) { return(false); } }
/// <summary> /// Save new ticket to redis cache. /// </summary> /// <param name="data">The ticket information.</param> private void UpdateRedisCacheTicket(TicketViewModel model) { var ticketList = RedisCacheHandler.GetValue(ConstantValue.TicketInfoKey, () => { return(this.FuncGetValue().ToList()); }); var item = ticketList.FirstOrDefault(x => x.Id == model.Id); if (model.EstimateTime.HasValue) { item.EstimateTime = model.EstimateTime; } item.Status = model.Status; RedisCacheHandler.SetValue(ConstantValue.TicketInfoKey, ticketList); }
/// <summary> /// Get comment by ticket id. /// </summary> /// <param name="ticketId">The identity ticket.</param> /// <returns></returns> public IEnumerable <TicketCommentViewModel> LoadComment(int ticketId) { var ticketList = RedisCacheHandler.GetValue(ConstantValue.TicketCommentKey + ticketId, () => { return(this.FuncGetValue(ticketId).ToList()); }).OrderBy(y => y.Id); foreach (var item in ticketList) { if (item.CommentBy == _token.Email) { item.IsOwner = true; } } return(ticketList); }
public void Invalidates_cache_per_method() { // setup var testMessageHandler = new TestMessageHandler(); var cache = new Mock <IDistributedCache>(MockBehavior.Strict); var url = "http://unittest/"; var getKey = HttpMethod.Get + url; var headKey = HttpMethod.Head + url; cache.Setup(c => c.RemoveAsync(headKey, default(CancellationToken))).Returns(Task.FromResult(true)); cache.Setup(c => c.RemoveAsync(getKey, default(CancellationToken))).Throws <Exception>(); var cacheExpirationPerStatusCode = new Dictionary <HttpStatusCode, TimeSpan> { { (HttpStatusCode)200, TimeSpan.FromHours(1) } }; var handler = new RedisCacheHandler(testMessageHandler, cacheExpirationPerStatusCode, cache.Object); // execute Func <Task> func = async() => await handler.InvalidateCache(new Uri(url), HttpMethod.Head); // validate func.ShouldNotThrow(); cache.Verify(c => c.RemoveAsync(headKey, default(CancellationToken)), Times.Once); }
public void Compress_WhenNotExplicitlySet_ShouldReturnFalse() { var ch = new RedisCacheHandler(new RedisCacheHandlerConfiguration()); Assert.IsFalse(((RedisCacheHandlerConfiguration)ch.Configuration).Compress); }
//[TestMethod] public async Task TestExcessiveRefresh() { //var memCache = new MemoryCacheHandler(true); var memCache = new RedisCacheHandler("127.0.1:6379,defaultDatabase=7,allowAdmin=true,syncTimeout=4000", true); var key = "TestKey"; var getData = new Func <Task <CacheItem> >(async() => { Debug.WriteLine("In getData"); await Task.Delay(2000); return(await Task.FromResult(new CacheItem() { Key = key })); }); Task.WaitAll(new[] { memCache.Register(key, getData, TimeSpan.FromSeconds(10), 10), memCache.Register(key, getData, TimeSpan.FromSeconds(10), 10), memCache.Register(key, getData, TimeSpan.FromSeconds(10), 10), memCache.Register(key, getData, TimeSpan.FromSeconds(10), 10), memCache.Register(key, getData, TimeSpan.FromSeconds(10), 10), memCache.Register(key, getData, TimeSpan.FromSeconds(10), 10), memCache.Register(key, getData, TimeSpan.FromSeconds(10), 10), memCache.Register(key, getData, TimeSpan.FromSeconds(10), 10), memCache.Register(key, getData, TimeSpan.FromSeconds(10), 10), memCache.Register(key, getData, TimeSpan.FromSeconds(10), 10), memCache.Register(key, getData, TimeSpan.FromSeconds(10), 10), memCache.Register(key, getData, TimeSpan.FromSeconds(10), 10), memCache.Register(key, getData, TimeSpan.FromSeconds(10), 10) }); await Task.Delay(TimeSpan.FromSeconds(30)); Task.WaitAll(new[] { memCache.Register(key, getData, TimeSpan.FromSeconds(10), 10), Task.Run(() => memCache.Remove(key)), memCache.Register(key, getData, TimeSpan.FromSeconds(10), 10), Task.Run(() => memCache.Remove(key)), memCache.Register(key, getData, TimeSpan.FromSeconds(10), 10) }); await Task.Delay(TimeSpan.FromSeconds(30)); Task.WaitAll(new[] { Task.Run(() => memCache.Replace(key, getData())), Task.Run(() => memCache.Remove(key)), memCache.Register(key, getData, TimeSpan.FromSeconds(10), 10), Task.Run(() => memCache.Remove(key)), memCache.Register(key, getData, TimeSpan.FromSeconds(10), 10), Task.Run(() => memCache.Replace(key, getData())), }); await memCache.Register(key, getData, TimeSpan.FromSeconds(10), 10); await Task.Delay(TimeSpan.FromSeconds(30)); await Task.Delay(TimeSpan.FromSeconds(30)); await Task.Delay(TimeSpan.FromSeconds(30)); await Task.Delay(TimeSpan.FromSeconds(30)); await Task.Delay(TimeSpan.FromSeconds(30)); await Task.Delay(TimeSpan.FromSeconds(30)); }