Example #1
0
        public void Should_execute_oncachemiss_but_not_oncacheput_if_cache_does_not_hold_value_and_returned_value_not_worth_caching()
        {
            const string valueToReturn = null;

            const string executionKey           = "SomeExecutionKey";
            string       keyPassedToOnCacheMiss = null;
            string       keyPassedToOnCachePut  = null;

            Context contextToExecute           = new Context(executionKey);
            Context contextPassedToOnCacheMiss = null;
            Context contextPassedToOnCachePut  = null;

            Action <Context, string, Exception> noErrorHandling = (_, __, ___) => { };
            Action <Context, string>            emptyDelegate   = (_, __) => { };
            Action <Context, string>            onCacheMiss     = (ctx, key) => { contextPassedToOnCacheMiss = ctx; keyPassedToOnCacheMiss = key; };
            Action <Context, string>            onCachePut      = (ctx, key) => { contextPassedToOnCachePut = ctx; keyPassedToOnCachePut = key; };

            ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
            CachePolicy        cache             = Policy.Cache(stubCacheProvider, new RelativeTtl(TimeSpan.MaxValue), DefaultCacheKeyStrategy.Instance, emptyDelegate, onCacheMiss, onCachePut, noErrorHandling, noErrorHandling);

            stubCacheProvider.Get(executionKey).Should().BeNull();
            cache.Execute(() => { return(valueToReturn); }, contextToExecute).Should().Be(valueToReturn);

            contextPassedToOnCacheMiss.Should().BeSameAs(contextToExecute);
            keyPassedToOnCacheMiss.Should().Be(executionKey);

            contextPassedToOnCachePut.Should().BeNull();
            keyPassedToOnCachePut.Should().BeNull();
        }
Example #2
0
        public void Should_execute_oncachemiss_but_not_oncacheput_if_cache_does_not_hold_value_and_returned_value_not_worth_caching()
        {
            const string valueToReturn = "valueToReturn";

            const string operationKey           = "SomeOperationKey";
            string       keyPassedToOnCacheMiss = null;
            string       keyPassedToOnCachePut  = null;

            Context contextToExecute           = new Context(operationKey);
            Context contextPassedToOnCacheMiss = null;
            Context contextPassedToOnCachePut  = null;

            Action <Context, string, Exception> noErrorHandling = (_, _, _) => { };
            Action <Context, string>            emptyDelegate   = (_, _) => { };
            Action <Context, string>            onCacheMiss     = (ctx, key) => { contextPassedToOnCacheMiss = ctx; keyPassedToOnCacheMiss = key; };
            Action <Context, string>            onCachePut      = (ctx, key) => { contextPassedToOnCachePut = ctx; keyPassedToOnCachePut = key; };

            ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
            CachePolicy        cache             = Policy.Cache(stubCacheProvider, new RelativeTtl(TimeSpan.Zero), DefaultCacheKeyStrategy.Instance, emptyDelegate, onCacheMiss, onCachePut, noErrorHandling, noErrorHandling);

            (bool cacheHit, object fromCache) = stubCacheProvider.TryGet(operationKey);
            cacheHit.Should().BeFalse();
            fromCache.Should().BeNull();

            cache.Execute(_ => valueToReturn, contextToExecute).Should().Be(valueToReturn);

            contextPassedToOnCacheMiss.Should().BeSameAs(contextToExecute);
            keyPassedToOnCacheMiss.Should().Be(operationKey);

            contextPassedToOnCachePut.Should().BeNull();
            keyPassedToOnCachePut.Should().BeNull();
        }
Example #3
0
        public void Should_execute_oncacheget_after_got_from_cache()
        {
            const string valueToReturnFromCache     = "valueToReturnFromCache";
            const string valueToReturnFromExecution = "valueToReturnFromExecution";

            const string executionKey        = "SomeExecutionKey";
            string       keyPassedToDelegate = null;

            Context contextToExecute        = new Context(executionKey);
            Context contextPassedToDelegate = null;

            Action <Context, string, Exception> noErrorHandling = (_, __, ___) => { };
            Action <Context, string>            emptyDelegate   = (_, __) => { };
            Action <Context, string>            onCacheAction   = (ctx, key) => { contextPassedToDelegate = ctx; keyPassedToDelegate = key; };

            ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
            CachePolicy        cache             = Policy.Cache(stubCacheProvider, new RelativeTtl(TimeSpan.MaxValue), DefaultCacheKeyStrategy.Instance, onCacheAction, emptyDelegate, emptyDelegate, noErrorHandling, noErrorHandling);

            stubCacheProvider.Put(executionKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue));

            bool delegateExecuted = false;

            cache.Execute(() =>
            {
                delegateExecuted = true;
                return(valueToReturnFromExecution);
            }, contextToExecute)
            .Should().Be(valueToReturnFromCache);
            delegateExecuted.Should().BeFalse();

            contextPassedToDelegate.Should().BeSameAs(contextToExecute);
            keyPassedToDelegate.Should().Be(executionKey);
        }
Example #4
0
        public void Should_call_onError_delegate_if_cache_put_errors()
        {
            Exception          ex = new Exception();
            ISyncCacheProvider stubCacheProvider = new StubErroringCacheProvider(getException: null, putException: ex);

            Exception exceptionFromCacheProvider = null;

            const string valueToReturn = "valueToReturn";
            const string operationKey  = "SomeOperationKey";

            Action <Context, string, Exception> onError = (ctx, key, exc) => { exceptionFromCacheProvider = exc; };

            CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, onError);

            (bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey);
            cacheHit1.Should().BeFalse();
            fromCache1.Should().BeNull();

            cache.Execute(ctx => valueToReturn, new Context(operationKey)).Should().Be(valueToReturn);

            //  error should be captured by onError delegate.
            exceptionFromCacheProvider.Should().Be(ex);

            // failed to put it in the cache
            (bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey);
            cacheHit2.Should().BeFalse();
            fromCache2.Should().BeNull();
        }
Example #5
0
        private static void _06_緩存()
        {
            var memoryCache         = new MemoryCache(new MemoryCacheOptions());
            var memoryCacheProvider = new MemoryCacheProvider(memoryCache);

            if (s_cachePolicy == null)
            {
                s_cachePolicy = Policy.Cache(memoryCacheProvider, TimeSpan.FromSeconds(5));
            }

            var result = s_cachePolicy.Execute(context =>
            {
                Console.WriteLine("快取過期,更新快取內容");
                var names  = new List <string>();
                var number = FakeData.NumberData.GetNumber(1, 10);
                for (var i = 0; i < number; i++)
                {
                    names.Add(FakeData.NameData.GetFullName());
                }

                return(names);
            }, new Context("datakey"));
            var json = JsonConvert.SerializeObject(result);

            Console.WriteLine($"取得資料:{json}");
            Console.WriteLine("隔離策略,完成");
        }
Example #6
0
        public void Should_honour_cancellation_even_if_prior_execution_has_cached()
        {
            const string valueToReturn = "valueToReturn";
            const string operationKey  = "SomeOperationKey";

            CachePolicy cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue);

            CancellationTokenSource tokenSource = new CancellationTokenSource();

            int delegateInvocations = 0;
            Func <Context, CancellationToken, string> func = (ctx, ct) =>
            {
                // delegate does not observe cancellation token; test is whether CacheEngine does.
                delegateInvocations++;
                return(valueToReturn);
            };

            cache.Execute(func, new Context(operationKey), tokenSource.Token).Should().Be(valueToReturn);
            delegateInvocations.Should().Be(1);

            tokenSource.Cancel();

            cache.Invoking(policy => policy.Execute(func, new Context(operationKey), tokenSource.Token))
            .ShouldThrow <OperationCanceledException>();
            delegateInvocations.Should().Be(1);
        }
Example #7
0
        public void Should_call_onError_delegate_if_cache_get_errors()
        {
            Exception          ex = new Exception();
            ISyncCacheProvider stubCacheProvider = new StubErroringCacheProvider(getException: ex, putException: null);

            Exception exceptionFromCacheProvider = null;

            const string valueToReturnFromCache     = "valueToReturnFromCache";
            const string valueToReturnFromExecution = "valueToReturnFromExecution";
            const string operationKey = "SomeOperationKey";

            Action <Context, string, Exception> onError = (ctx, key, exc) => { exceptionFromCacheProvider = exc; };

            CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, onError);

            stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue));

            bool delegateExecuted = false;


            // Even though value is in cache, get will error; so value is returned from execution.
            cache.Execute(ctx =>
            {
                delegateExecuted = true;
                return(valueToReturnFromExecution);
            }, new Context(operationKey))
            .Should().Be(valueToReturnFromExecution);
            delegateExecuted.Should().BeTrue();

            // And error should be captured by onError delegate.
            exceptionFromCacheProvider.Should().Be(ex);
        }
Example #8
0
        public void Should_execute_delegate_and_put_value_in_cache_but_when_it_expires_execute_delegate_again()
        {
            const string valueToReturn = "valueToReturn";
            const string operationKey  = "SomeOperationKey";

            ISyncCacheProvider   stubCacheProvider = new StubCacheProvider();
            TimeSpan             ttl   = TimeSpan.FromMinutes(30);
            CachePolicy <string> cache = Policy.Cache <string>(stubCacheProvider, ttl);

            (bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey);
            cacheHit1.Should().BeFalse();
            fromCache1.Should().BeNull();

            int delegateInvocations     = 0;
            Func <Context, string> func = _ =>
            {
                delegateInvocations++;
                return(valueToReturn);
            };

            DateTimeOffset fixedTime = SystemClock.DateTimeOffsetUtcNow();

            SystemClock.DateTimeOffsetUtcNow = () => fixedTime;

            // First execution should execute delegate and put result in the cache.
            cache.Execute(func, new Context(operationKey)).Should().Be(valueToReturn);
            delegateInvocations.Should().Be(1);

            (bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey);
            cacheHit2.Should().BeTrue();
            fromCache2.Should().Be(valueToReturn);

            // Second execution (before cache expires) should get it from the cache - no further delegate execution.
            // (Manipulate time so just prior cache expiry).
            SystemClock.DateTimeOffsetUtcNow = () => fixedTime.Add(ttl).AddSeconds(-1);
            cache.Execute(func, new Context(operationKey)).Should().Be(valueToReturn);
            delegateInvocations.Should().Be(1);

            // Manipulate time to force cache expiry.
            SystemClock.DateTimeOffsetUtcNow = () => fixedTime.Add(ttl).AddSeconds(1);

            // Third execution (cache expired) should not get it from the cache - should cause further delegate execution.
            cache.Execute(func, new Context(operationKey)).Should().Be(valueToReturn);
            delegateInvocations.Should().Be(2);
        }
Example #9
0
        public void Should_always_execute_delegate_if_execution_key_not_set()
        {
            string valueToReturn = Guid.NewGuid().ToString();

            CachePolicy <string> cache = Policy.Cache <string>(new StubCacheProvider(), TimeSpan.MaxValue);

            int           delegateInvocations = 0;
            Func <string> func = () =>
            {
                delegateInvocations++;
                return(valueToReturn);
            };

            cache.Execute(func /*, no execution key */).Should().Be(valueToReturn);
            delegateInvocations.Should().Be(1);

            cache.Execute(func /*, no execution key */).Should().Be(valueToReturn);
            delegateInvocations.Should().Be(2);
        }
        /// <summary>
        /// Compiles the input linqExpression into a Linq expression tree
        /// </summary>
        /// <param name="linqExpression">The linqExpression.</param>
        /// <returns></returns>
        public Action <object, object> CompileAction(LinqExpressionToRun linqExpression)
        {
            if (linqExpression.Unique) //don't bother caching
            {
                _counterActionCacheUnique.Increment();
                return(_handler.CompileAction(linqExpression));
            }

            var key = GenerateKey(linqExpression);

            return(_cacheActions.Execute(context => _handler.CompileAction(linqExpression), new Context(key)));
        }
Example #11
0
        public void Should_allow_custom_FuncCacheKeyStrategy()
        {
            ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
            CachePolicy        cache             = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, context => context.ExecutionKey + context["id"]);

            object person1 = new object();

            stubCacheProvider.Put("person1", person1, new Ttl(TimeSpan.MaxValue));
            object person2 = new object();

            stubCacheProvider.Put("person2", person2, new Ttl(TimeSpan.MaxValue));

            bool          funcExecuted = false;
            Func <object> func         = () => { funcExecuted = true; return(new object()); };

            cache.Execute(func, new Context("person", new { id = "1" }.AsDictionary())).Should().BeSameAs(person1);
            funcExecuted.Should().BeFalse();

            cache.Execute(func, new Context("person", new { id = "2" }.AsDictionary())).Should().BeSameAs(person2);
            funcExecuted.Should().BeFalse();
        }
Example #12
0
        public void Should_allow_custom_FuncICacheKeyStrategy()
        {
            ISyncCacheProvider        stubCacheProvider = new StubCacheProvider();
            CachePolicy <ResultClass> cache             = Policy.Cache <ResultClass>(stubCacheProvider, TimeSpan.MaxValue, context => context.ExecutionKey + context["id"]);

            object person1 = new ResultClass(ResultPrimitive.Good, "person1");

            stubCacheProvider.Put("person1", person1, new Ttl(TimeSpan.MaxValue));
            object person2 = new ResultClass(ResultPrimitive.Good, "person2");

            stubCacheProvider.Put("person2", person2, new Ttl(TimeSpan.MaxValue));

            bool funcExecuted       = false;
            Func <ResultClass> func = () => { funcExecuted = true; return(new ResultClass(ResultPrimitive.Fault, "should never return this one")); };

            cache.Execute(func, new Context("person", new { id = "1" }.AsDictionary())).Should().BeSameAs(person1);
            funcExecuted.Should().BeFalse();

            cache.Execute(func, new Context("person", new { id = "2" }.AsDictionary())).Should().BeSameAs(person2);
            funcExecuted.Should().BeFalse();
        }
        /// <inheritdoc />
        public IReceivedMessageInternal GetNextMessage(List <string> routes)
        {
            if (routes != null && routes.Count > 0)
            {
                throw new NotSupportedException("The in-memory transport does not support routes");
            }

            if (!Queues[_connectionInformation].TryDequeue(out var id))
            {
                return(null);
            }
            if (!QueueData[_connectionInformation].TryRemove(id, out var item))
            {
                return(null);
            }

            var hasError = false;

            try
            {
                var newMessage = _messageFactory.Create(item.Body, item.Headers);

                if (!string.IsNullOrEmpty(item.JobName))
                {
                    var key = GenerateKey(item.JobName);

                    //add it to the cache
                    JobLastEventCache.Execute(context => item.JobEventTime, new Context(key));
                }

                Interlocked.Increment(ref DequeueCounts[_connectionInformation].ProcessedCount);

                return(_receivedMessageFactory.Create(newMessage,
                                                      new MessageQueueId(id),
                                                      new MessageCorrelationId(item.CorrelationId)));
            }
            catch (Exception error)
            {
                hasError = true;
                //at this point, the record has been de-queued, but it can't be processed.
                throw new PoisonMessageException(
                          "An error has occurred trying to re-assemble a message", error,
                          new MessageQueueId(id), null, null, null);
            }
            finally
            {
                if (!hasError)
                {
                    QueueWorking[_connectionInformation].TryAdd(item.Id, item);
                }
            }
        }
        public void Should_execute_delegate_and_put_value_in_cache_for_non_nullable_types_if_cache_does_not_hold_value()
        {
            const ResultPrimitive valueToReturn = ResultPrimitive.Substitute;
            const string          operationKey  = "SomeOperationKey";

            ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
            CachePolicy        cache             = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue);

            stubCacheProvider.Get(operationKey).Should().BeNull();

            cache.Execute(ctx => { return(valueToReturn); }, new Context(operationKey)).Should().Be(valueToReturn);

            stubCacheProvider.Get(operationKey).Should().Be(valueToReturn);
        }
Example #15
0
        public void Should_execute_delegate_but_not_put_value_in_cache_if_cache_does_not_hold_value_but_ttl_indicates_not_worth_caching()
        {
            const string valueToReturn = "valueToReturn";
            const string executionKey  = "SomeExecutionKey";

            ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
            CachePolicy        cache             = Policy.Cache(stubCacheProvider, TimeSpan.Zero);

            stubCacheProvider.Get(executionKey).Should().BeNull();

            cache.Execute(() => { return(valueToReturn); }, new Context(executionKey)).Should().Be(valueToReturn);

            stubCacheProvider.Get(executionKey).Should().Be(null);
        }
Example #16
0
        public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hold_value()
        {
            const string valueToReturn = "valueToReturn";
            const string executionKey  = "SomeExecutionKey";

            ISyncCacheProvider   stubCacheProvider = new StubCacheProvider();
            CachePolicy <string> cache             = Policy.Cache <string>(stubCacheProvider, TimeSpan.MaxValue);

            stubCacheProvider.Get(executionKey).Should().BeNull();

            cache.Execute(() => { return(valueToReturn); }, new Context(executionKey)).Should().Be(valueToReturn);

            stubCacheProvider.Get(executionKey).Should().Be(valueToReturn);
        }
Example #17
0
        public void Should_return_value_from_cache_and_not_execute_delegate_if_prior_execution_has_cached()
        {
            const string valueToReturn = "valueToReturn";
            const string executionKey  = "SomeExecutionKey";

            CachePolicy <string> cache = Policy.Cache <string>(new StubCacheProvider(), TimeSpan.MaxValue);

            int           delegateInvocations = 0;
            Func <string> func = () =>
            {
                delegateInvocations++;
                return(valueToReturn);
            };

            cache.Execute(func, new Context(executionKey)).Should().Be(valueToReturn);
            delegateInvocations.Should().Be(1);

            cache.Execute(func, new Context(executionKey)).Should().Be(valueToReturn);
            delegateInvocations.Should().Be(1);

            cache.Execute(func, new Context(executionKey)).Should().Be(valueToReturn);
            delegateInvocations.Should().Be(1);
        }
        public void Should_not_error_for_executions_on_non_nullable_types_if_cache_does_not_hold_value()
        {
            const string operationKey = "SomeOperationKey";

            bool onErrorCalled = false;
            Action <Context, string, Exception> onError = (ctx, key, exc) => { onErrorCalled = true; };

            ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
            CachePolicy        cache             = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, onError);

            stubCacheProvider.Get(operationKey).Should().BeNull();
            ResultPrimitive result = cache.Execute(ctx => ResultPrimitive.Substitute, new Context(operationKey));

            onErrorCalled.Should().BeFalse();
        }
Example #19
0
        public void Should_not_execute_oncachemiss_if_dont_query_cache_because_cache_key_not_set()
        {
            string valueToReturn = Guid.NewGuid().ToString();

            Action <Context, string, Exception> noErrorHandling = (_, __, ___) => { };
            Action <Context, string>            emptyDelegate   = (_, __) => { };

            bool onCacheMissExecuted             = false;
            Action <Context, string> onCacheMiss = (ctx, key) => { onCacheMissExecuted = true; };

            CachePolicy cache = Policy.Cache(new StubCacheProvider(), new RelativeTtl(TimeSpan.MaxValue), DefaultCacheKeyStrategy.Instance, emptyDelegate, onCacheMiss, emptyDelegate, noErrorHandling, noErrorHandling);

            cache.Execute(() => valueToReturn /*, no execution key */).Should().Be(valueToReturn);

            onCacheMissExecuted.Should().BeFalse();
        }
Example #20
0
        public void Should_execute_delegate_but_not_put_value_in_cache_if_cache_does_not_hold_value_but_ttl_indicates_not_worth_caching()
        {
            const string valueToReturn = "valueToReturn";
            const string operationKey  = "SomeOperationKey";

            ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
            CachePolicy        cache             = Policy.Cache(stubCacheProvider, TimeSpan.Zero);

            (bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey);
            cacheHit1.Should().BeFalse();
            fromCache1.Should().BeNull();

            cache.Execute(ctx => { return(valueToReturn); }, new Context(operationKey)).Should().Be(valueToReturn);

            (bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey);
            cacheHit2.Should().BeFalse();
            fromCache2.Should().BeNull();
        }
Example #21
0
        public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hold_value__default_for_value_type()
        {
            ResultPrimitive valueToReturn = default(ResultPrimitive);
            const string    operationKey  = "SomeOperationKey";

            ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
            CachePolicy        cache             = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue);

            (bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey);
            cacheHit1.Should().BeFalse();
            fromCache1.Should().BeNull();

            cache.Execute(ctx => { return(valueToReturn); }, new Context(operationKey)).Should().Be(valueToReturn);

            (bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey);
            cacheHit2.Should().BeTrue();
            fromCache2.Should().Be(valueToReturn);
        }
Example #22
0
        public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hold_value()
        {
            const string valueToReturn = "valueToReturn";
            const string operationKey  = "SomeOperationKey";

            ISyncCacheProvider   stubCacheProvider = new StubCacheProvider();
            CachePolicy <string> cache             = Policy.Cache <string>(stubCacheProvider, TimeSpan.MaxValue);

            (bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey);
            cacheHit1.Should().BeFalse();
            fromCache1.Should().BeNull();

            cache.Execute(_ => valueToReturn, new Context(operationKey)).Should().Be(valueToReturn);

            (bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey);
            cacheHit2.Should().BeTrue();
            fromCache2.Should().Be(valueToReturn);
        }
Example #23
0
        public async Task <IActionResult> Get()
        {
            // HttpClient clnt = new HttpClient();
            // var response = clnt.GetAsync("http://localhost:7637/api/values").Result;

            //Specify the name of the Response. If the method is taking parameter, we can append the actual parameter to cache unique responses separately
            Context policyExecutionContext = new Context($"GetUsers");

            var response = _cachePolicy.Execute(() => _resilientClient.Get("http://localhost:7637/api/values"), policyExecutionContext);

            if (response.IsSuccessStatusCode)
            {
                var result = response.Content.ReadAsStringAsync();
                return(Ok(result));
            }

            return(StatusCode((int)response.StatusCode, response.Content.ReadAsStringAsync()));
        }
Example #24
0
        public static void Caching()
        {
            ErrorProneCode errorProneCode      = new ErrorProneCode();
            var            memoryCache         = new MemoryCache(new MemoryCacheOptions());
            var            memoryCacheProvider = new MemoryCacheProvider(memoryCache);

            #region caching
            CachePolicy <int> cachePolicy =
                Policy.Cache <int>(memoryCacheProvider, TimeSpan.FromSeconds(1.5));

            for (int loop = 1; loop <= 10; loop++)
            {
                int result = cachePolicy.Execute(context => errorProneCode.GetSomeNumberThatMightBeCacheable(), new Context("ContextKey"));

                Console.WriteLine($"result={result}. cachePolicy executed {loop} time(s). GetSomeNumberThatMightBeCacheable method really called {result} time(s).");
                Thread.Sleep(500);
            }

            #endregion
        }
Example #25
0
        public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value()
        {
            const string valueToReturnFromCache     = "valueToReturnFromCache";
            const string valueToReturnFromExecution = "valueToReturnFromExecution";
            const string executionKey = "SomeExecutionKey";

            ISyncCacheProvider   stubCacheProvider = new StubCacheProvider();
            CachePolicy <string> cache             = Policy.Cache <string>(stubCacheProvider, TimeSpan.MaxValue);

            stubCacheProvider.Put(executionKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue));

            bool delegateExecuted = false;

            cache.Execute(() =>
            {
                delegateExecuted = true;
                return(valueToReturnFromExecution);
            }, new Context(executionKey))
            .Should().Be(valueToReturnFromCache);

            delegateExecuted.Should().BeFalse();
        }
Example #26
0
        public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value__default_for_reference_type()
        {
            ResultClass  valueToReturnFromCache     = default;
            ResultClass  valueToReturnFromExecution = new ResultClass(ResultPrimitive.Good);
            const string operationKey = "SomeOperationKey";

            ISyncCacheProvider        stubCacheProvider = new StubCacheProvider();
            CachePolicy <ResultClass> cache             = Policy.Cache <ResultClass>(stubCacheProvider, TimeSpan.MaxValue);

            stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue));

            bool delegateExecuted = false;

            cache.Execute(_ =>
            {
                delegateExecuted = true;
                return(valueToReturnFromExecution);
            }, new Context(operationKey))
            .Should().Be(valueToReturnFromCache);

            delegateExecuted.Should().BeFalse();
        }
Example #27
0
        private static void Demo5()
        {
            // Polly5.9.0 和  Polly6.0.1差异
            IMemoryCache       memoryCache         = new MemoryCache(new MemoryCacheOptions());
            ISyncCacheProvider memoryCacheProvider = new Polly.Caching.MemoryCache.MemoryCacheProvider(memoryCache);

            CachePolicy policy = Policy.Cache(memoryCacheProvider, TimeSpan.FromSeconds(5));
            Random      rand   = new Random();

            while (true)
            {
                int i = rand.Next(5);
                Console.WriteLine("产生" + i);
                var context = new Context("doublecache" + i);
                int result  = policy.Execute(ctx =>
                {
                    Console.WriteLine("Execute计算" + i);
                    return(i * 2);
                }, context);
                Console.WriteLine("计算结果:" + result);
                Thread.Sleep(500);
            }
        }
Example #28
0
        /// <summary>
        /// 缓存
        /// </summary>
        private static void Caching()
        {
            //Install-Package Microsoft.Extensions.Caching.Memory
            Microsoft.Extensions.Caching.Memory.IMemoryCache memoryCache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new Microsoft.Extensions.Caching.Memory.MemoryCacheOptions());
            //Install-Package Polly.Caching.MemoryCache
            Polly.Caching.MemoryCache.MemoryCacheProvider memoryCacheProvider = new Polly.Caching.MemoryCache.MemoryCacheProvider(memoryCache);

            CachePolicy policy = Policy.Cache(memoryCacheProvider, TimeSpan.FromSeconds(5));
            Random      rand   = new Random();

            while (true)
            {
                int i = rand.Next(5);
                Console.WriteLine("产生" + i);
                var context = new Context("doublecache" + i);
                int result  = policy.Execute(ctx =>
                {
                    Console.WriteLine("Execute计算" + i);
                    return(i * 2);
                }, context);
                Console.WriteLine("计算结果:" + result);
                Thread.Sleep(500);
            }
        }
Example #29
0
        public void Should_call_onError_delegate_if_cache_put_errors()
        {
            Exception          ex = new Exception();
            ISyncCacheProvider stubCacheProvider = new StubErroringCacheProvider(getException: null, putException: ex);

            Exception exceptionFromCacheProvider = null;

            const string valueToReturn = "valueToReturn";
            const string executionKey  = "SomeExecutionKey";

            Action <Context, string, Exception> onError = (ctx, key, exc) => { exceptionFromCacheProvider = exc; };

            CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, onError);

            stubCacheProvider.Get(executionKey).Should().BeNull();

            cache.Execute(() => { return(valueToReturn); }, new Context(executionKey)).Should().Be(valueToReturn);

            //  error should be captured by onError delegate.
            exceptionFromCacheProvider.Should().Be(ex);

            // failed to put it in the cache
            stubCacheProvider.Get(executionKey).Should().BeNull();
        }
Example #30
0
        /// <inheritdoc />
        public IReceivedMessageInternal GetNextMessage(List <string> routes, TimeSpan timeout)
        {
            if (_complete)
            {
                return(null);
            }

            if (routes != null && routes.Count > 0)
            {
                throw new NotSupportedException("The in-memory transport does not support routes");
            }

            using (CancellationTokenSource linkedCts =
                       CancellationTokenSource.CreateLinkedTokenSource(_cancelToken.CancelWorkToken,
                                                                       _cancelToken.StopWorkToken))
            {
                Guid id = Guid.Empty;
                try
                {
                    if (!Queues[_connectionInformation].TryTake(out id, Convert.ToInt32(timeout.TotalMilliseconds), linkedCts.Token))
                    {
                        return(null);
                    }
                }
                catch (OperationCanceledException)
                {
                    return(null);
                }

                if (!QueueData[_connectionInformation].TryRemove(id, out var item))
                {
                    return(null);
                }

                var hasError = false;
                try
                {
                    var newMessage = _messageFactory.Create(item.Body, item.Headers);

                    if (!string.IsNullOrEmpty(item.JobName))
                    {
                        var key = GenerateKey(item.JobName);

                        //add it to the cache
                        JobLastEventCache.Execute(context => item.JobEventTime, new Context(key));
                    }

                    Interlocked.Increment(ref DequeueCounts[_connectionInformation].ProcessedCount);

                    return(_receivedMessageFactory.Create(newMessage,
                                                          new MessageQueueId(id),
                                                          new MessageCorrelationId(item.CorrelationId)));
                }
                catch (Exception error)
                {
                    hasError = true;
                    //at this point, the record has been de-queued, but it can't be processed.
                    throw new PoisonMessageException(
                              "An error has occurred trying to re-assemble a message", error,
                              new MessageQueueId(id), null, null, null);
                }
                finally
                {
                    if (!hasError)
                    {
                        QueueWorking[_connectionInformation].TryAdd(item.Id, item);
                    }
                }
            }
        }