Exemple #1
0
        public async Task Tests_cache_invalidation()
        {
            const string url = "http://thecatapi.com/api/images/get?format=html";

            var handler = new InMemoryCacheHandler(new HttpClientHandler(), CacheExpirationProvider.CreateSimple(TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(5)));

            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}.");
                    if (i % 2 == 0)
                    {
                        Debug.WriteLine($"Iteration {i}. Invalidating cache.");
                        handler.InvalidateCache(new Uri(url));
                    }
                }
            }

            StatsResult stats = handler.StatsProvider.GetStatistics();

            stats.Total.CacheHit.Should().Be(2);
            stats.Total.CacheMiss.Should().Be(3);
        }
Exemple #2
0
        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);
        }
 private static DelegatingHandler GetCachingHandler(double successExpiration = 120)
 {
     return(GetCachingHandler(CacheExpirationProvider.CreateSimple(
                                  TimeSpan.FromSeconds(successExpiration),
                                  TimeSpan.FromSeconds(10),
                                  TimeSpan.FromSeconds(5)
                                  )));
 }
        public HttpMessageHandler GetCachedHandler()
        {
            var handler = new HttpClientHandler {
                AllowAutoRedirect = true
            };
            var cacheExpirationPerHttpResponseCode = CacheExpirationProvider.CreateSimple(TimeSpan.FromHours(12), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(60));
            var cacheHandler = new InMemoryCacheHandler(handler, cacheExpirationPerHttpResponseCode);

            return(cacheHandler);
        }
        public void Puts_the_correct_status_codes_into_the_mapping()
        {
            // execute
            var mappings = CacheExpirationProvider.CreateSimple(TimeSpan.FromTicks(1), TimeSpan.FromTicks(2), TimeSpan.FromTicks(3));

            // validate
            mappings.Count.Should().Be(3);
            mappings[HttpStatusCode.OK].Should().Be(TimeSpan.FromTicks(1));
            mappings[HttpStatusCode.BadRequest].Should().Be(TimeSpan.FromTicks(2));
            mappings[HttpStatusCode.InternalServerError].Should().Be(TimeSpan.FromTicks(3));
        }
Exemple #6
0
        public WeatherService(ITracer tracer)
        {
            this.tracer = tracer;

            WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;

            var httpClientHandler = new HttpClientHandler();
            var cacheExpirationPerHttpResponseCode = CacheExpirationProvider.CreateSimple(TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(5));
            var inMemoryCacheHandler = new InMemoryCacheHandler(httpClientHandler, cacheExpirationPerHttpResponseCode);

            this.httpClient = new HttpClient(inMemoryCacheHandler);
        }
Exemple #7
0
        public void Takes_value_from_http_code_category()
        {
            // setup
            var r        = new Random();
            var mappings = CacheExpirationProvider.CreateSimple(TimeSpan.FromTicks(r.Next(0, 100000)), TimeSpan.FromTicks(r.Next(0, 100000)), TimeSpan.FromTicks(r.Next(0, 100000)));

            // execute
            TimeSpan successResult     = HttpStatusCode.Created.GetAbsoluteExpirationRelativeToNow(mappings);
            TimeSpan clientErrorResult = HttpStatusCode.NotFound.GetAbsoluteExpirationRelativeToNow(mappings);
            TimeSpan serverErrorResult = HttpStatusCode.GatewayTimeout.GetAbsoluteExpirationRelativeToNow(mappings);

            // validate
            successResult.Should().Be(mappings[HttpStatusCode.OK]);
            clientErrorResult.Should().Be(mappings[HttpStatusCode.BadRequest]);
            serverErrorResult.Should().Be(mappings[HttpStatusCode.InternalServerError]);
        }
Exemple #8
0
        static void Main(string[] args)
        {
            const string url = "http://worldclockapi.com/api/json/utc/now";

            // HttpClient uses an HttpClientHandler nested into InMemoryCacheHandler in order to handle http get response caching
            var httpClientHandler = new HttpClientHandler();
            var cacheExpirationPerHttpResponseCode = CacheExpirationProvider.CreateSimple(TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(5));
            var handler = new InMemoryCacheHandler(httpClientHandler, cacheExpirationPerHttpResponseCode);

            using (var client = new HttpClient(handler))
            {
                // HttpClient calls the same API endpoint five times:
                // - The first attempt is called against the real API endpoint since no cache is available
                // - Attempts 2 to 5 can be read from cache
                for (var i = 1; i <= 5; i++)
                {
                    Console.Write($"Attempt {i}: HTTP GET {url}...");
                    var stopwatch = Stopwatch.StartNew();
                    var result    = client.GetAsync(url).GetAwaiter().GetResult();

                    // Do something useful with the returned content...
                    var content = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                    Console.WriteLine($" completed in {stopwatch.ElapsedMilliseconds}ms");

                    // Artificial wait time...
                    Thread.Sleep(1000);
                }
            }

            Console.WriteLine();

            StatsResult stats = handler.StatsProvider.GetStatistics();

            Console.WriteLine($"TotalRequests: {stats.Total.TotalRequests}");
            Console.WriteLine($"-> CacheHit: {stats.Total.CacheHit}");
            Console.WriteLine($"-> CacheMiss: {stats.Total.CacheMiss}");
            Console.ReadKey();
        }