private PostEvictionCallbackRegistration GetPostEvictionCallbackRegistration()
        {
            var registration = new PostEvictionCallbackRegistration();

            registration.EvictionCallback = DisposeValue;
            return(registration);
        }
Пример #2
0
        /// <summary>
        /// Adds an object to distributed cache
        /// </summary>
        /// <typeparam name="TItem">Cache object type</typeparam>
        /// <param name="partitionName">Cache Partition Name</param>
        /// <param name="key">Cache Key</param>
        /// <param name="value">Cache object</param>
        /// <param name="expirationToken">Cache <see cref="IChangeToken"/> expiration token to be used while adding cache item</param>
        /// <param name="postEvictionCallback"><see cref="PostEvictionCallbackRegistration"/> delegate</param>
        public void Set <TItem>(string partitionName, string key, TItem value, IChangeToken expirationToken = null,
                                PostEvictionCallbackRegistration postEvictionCallback = null)
        {
            var partition = GetPartition(partitionName);

            partition.Cache.Set(partitionName + key, value,
                                GetDistributedCacheEntryOptions(partition, expirationToken, postEvictionCallback));
        }
Пример #3
0
 /// <summary>
 /// Adds an object to distributed cache asynchronously without expiration change token
 /// </summary>
 /// <typeparam name="TItem">Cache object type</typeparam>
 /// <param name="partitionName">Cache Partition Name</param>
 /// <param name="key">Cache Key</param>
 /// <param name="value">Cache object</param>
 /// <param name="postEvictionCallback"><see cref="PostEvictionCallbackRegistration"/> delegate</param>
 /// <param name="token"><see cref="CancellationToken"/> to be used while setting cache item</param>
 public async Task SetAsync <TItem>(string partitionName, string key, TItem value,
                                    PostEvictionCallbackRegistration postEvictionCallback,
                                    CancellationToken token = default)
 {
     var partition = GetPartition(partitionName);
     await partition.Cache.SetAsync(partitionName + key, value,
                                    GetDistributedCacheEntryOptions(partition), token);
 }
Пример #4
0
        //TODO need a better LRU cache, //there is no scan timer at all.
        public TValue Set(object key, TValue value, TimeSpan slidingExpiration, PostEvictionCallbackRegistration evictionCallback = null)
        {
            var opt = new MemoryCacheEntryOptions();

            ////opt.AbsoluteExpirationRelativeToNow = slidingExpiration;
            opt.SlidingExpiration = slidingExpiration;
            if (null != evictionCallback)
            {
                opt.PostEvictionCallbacks.Add(evictionCallback);
            }
            return(_cache.Set(key, value, opt));
        }
Пример #5
0
        public static void Main()
        {
            ICacheManager cacheManager = CreateCacheManager();

            object result;
            string key       = "Key";
            object newObject = new object();
            object state     = new object();

            // Basic CRUD operations:

            // Create / Overwrite
            AddToCache(cacheManager, InMemoryStorePartition, key, newObject);
            AddToCache(cacheManager, DistributedMemoryStorePartition, key, newObject);

            // Retrieve, null if not found
            result = cacheManager.Get(InMemoryStorePartition, key);
            result = cacheManager.Get(DistributedMemoryStorePartition, key);

            // Retrieve
            bool found = cacheManager.TryGetValue(InMemoryStorePartition, key, out result);

            found = cacheManager.TryGetValue(DistributedMemoryStorePartition, key, out result);

            // Store and Get using weak references
            result = cacheManager.SetWeak(InMemoryStorePartition, key, newObject);
            result = cacheManager.GetWeak <object>(InMemoryStorePartition, key);

            result = cacheManager.SetWeak(DistributedMemoryStorePartition, key, newObject);
            result = cacheManager.GetWeak <object>(DistributedMemoryStorePartition, key);

            // Delete
            cacheManager.Remove(InMemoryStorePartition, key);
            cacheManager.Remove(DistributedMemoryStorePartition, key);


            // Callback when evicted
            PostEvictionCallbackRegistration postEvictionCallbackRegistration = new PostEvictionCallbackRegistration
            {
                EvictionCallback = (echoKey, value, reason, substate) =>
                {
                    Console.WriteLine($"{echoKey} : {value} was evicted due to {reason}");
                }
            };

            cacheManager.Set(InMemoryStorePartition, key, new object(), null, postEvictionCallbackRegistration);
            cacheManager.Set(DistributedMemoryStorePartition, key, new object(), null, postEvictionCallbackRegistration);

            AddPostEvictionPolicy(cacheManager, InMemoryStorePartition, key, postEvictionCallbackRegistration);
            AddPostEvictionPolicy(cacheManager, DistributedMemoryStorePartition, key, postEvictionCallbackRegistration);
        }
Пример #6
0
        private void AddEvictionTracker(string key, object item, TimeSpan expirationSpan, PostEvictionDelegate callback)
        {
            if (expirationSpan > TimeSpan.Zero)
            {
                var cache   = ExpirationTrackingCache;
                var options = new MemoryCacheEntryOptions()
                {
                    //AbsoluteExpiration = absoluteExpiration,
                    AbsoluteExpirationRelativeToNow = expirationSpan
                };
                var callbackRegistration = new PostEvictionCallbackRegistration();
                callbackRegistration.EvictionCallback = callback;
                callbackRegistration.State            = key;
                options.PostEvictionCallbacks.Add(callbackRegistration);

                cache.Set(key, new object(), options);
            }
        }
Пример #7
0
        public CircuitRegistry(
            IOptions <CircuitOptions> options,
            ILogger <CircuitRegistry> logger)
        {
            _options = options.Value;
            _logger  = logger;

            ConnectedCircuits = new ConcurrentDictionary <string, CircuitHost>(StringComparer.Ordinal);

            DisconnectedCircuits = new MemoryCache(new MemoryCacheOptions
            {
                SizeLimit = _options.MaxRetainedDisconnectedCircuits,
            });

            _postEvictionCallback = new PostEvictionCallbackRegistration
            {
                EvictionCallback = OnEntryEvicted,
            };
        }
Пример #8
0
        void KeepClient(UdpClient2 client)
        {
            PostEvictionCallbackRegistration cb = new PostEvictionCallbackRegistration();

            cb.EvictionCallback = (key, value, reason, state) =>
            {
                if (reason == EvictionReason.Expired)//
                {
                    _logger?.LogInformation($"UDP cache client expired:{key.ToString()},{reason.ToString()}");
                    UdpClient2 c = value as UdpClient2;
                    if (c.Active)
                    {
                        KeepClient(c);
                        _logger?.LogInformation($"UDP cache client readd:{key.ToString()}");
                    }
                }
            };
            _clientManager.Set(client.EndPoint, client, TimeSpan.FromMilliseconds(CLIENT_ACTIVE_TIMEOUT), cb);
        }
Пример #9
0
        public CircuitRegistry(
            IOptions <CircuitOptions> options,
            ILogger <CircuitRegistry> logger,
            CircuitIdFactory CircuitHostFactory)
        {
            _options          = options.Value;
            _logger           = logger;
            _circuitIdFactory = CircuitHostFactory;
            ConnectedCircuits = new ConcurrentDictionary <CircuitId, CircuitHost>();

            DisconnectedCircuits = new MemoryCache(new MemoryCacheOptions
            {
                SizeLimit = _options.DisconnectedCircuitMaxRetained,
            });

            _postEvictionCallback = new PostEvictionCallbackRegistration
            {
                EvictionCallback = OnEntryEvicted,
            };
        }
Пример #10
0
        private ExtendedDistributedCacheEntryOptions GetDistributedCacheEntryOptions(ICachePartition cachePartition,
                                                                                     IChangeToken expirationToken = null,
                                                                                     PostEvictionCallbackRegistration postEvictionCallback = null)
        {
            var cacheEntryOptions = new ExtendedDistributedCacheEntryOptions
            {
                AbsoluteExpiration = cachePartition.AbsoluteExpiration,
                AbsoluteExpirationRelativeToNow = cachePartition.AbsoluteExpirationRelativeToNow,
                SlidingExpiration = cachePartition.SlidingExpiration,
                Priority          = cachePartition.Priority
            };

            if (expirationToken != null)
            {
                cacheEntryOptions.ExpirationTokens.Add(expirationToken);
            }
            if (postEvictionCallback != null)
            {
                cacheEntryOptions.PostEvictionCallbacks.Add(postEvictionCallback);
            }
            return(cacheEntryOptions);
        }
Пример #11
0
        void KeepLocker(Locker <UdpClient2> locker)
        {
            PostEvictionCallbackRegistration cb = new PostEvictionCallbackRegistration();

            cb.EvictionCallback = (key, value, reason, state) =>
            {
                if (reason == EvictionReason.Expired)//
                {
                    _logger?.LogInformation($"UDP server locker expired:{key.ToString()},{reason.ToString()}");
                    Locker <UdpClient2> locker = value as Locker <UdpClient2>;
                    if ((DateTime.Now - locker.Owner.LastActive).TotalMilliseconds <= CLIENT_ACTIVE_TIMEOUT)
                    {
                        KeepLocker(locker);
                        _logger?.LogInformation($"UDP locker cache readd:{key.ToString()}");
                    }
                    else
                    {
                        locker.Destroy();
                    }
                }
            };
            _clientLockers.Set(locker.Number, locker, TimeSpan.FromMilliseconds(CLIENT_ACTIVE_TIMEOUT), cb);
        }
Пример #12
0
        public static void Main()
        {
            ICacheManager cacheManager = CreateCacheManager();
            var           greeting     = "";
            var           cacheKey     = "cache_key";
            var           fileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "WatchedFiles"));

            do
            {
                if (!cacheManager.TryGetValue(InMemoryStorePartition, cacheKey, out greeting))
                {
                    using (var streamReader = new StreamReader(fileProvider.GetFileInfo("example.txt").CreateReadStream()))
                    {
                        greeting = streamReader.ReadToEnd();
                        PostEvictionCallbackRegistration postEvictionCallbackRegistration = new PostEvictionCallbackRegistration
                        {
                            EvictionCallback = (echoKey, value, reason, substate) =>
                            {
                                Console.WriteLine($"{echoKey} : {value} was evicted due to {reason}");
                            }
                        };

                        cacheManager.Set(InMemoryStorePartition, cacheKey, new object(), fileProvider.Watch("example.txt"), postEvictionCallbackRegistration);

                        Console.WriteLine($"{cacheKey} updated from source.");
                    }
                }
                else
                {
                    Console.WriteLine($"{cacheKey} retrieved from cache.");
                }

                Console.WriteLine(greeting);
                Console.WriteLine("Press any key to continue. Press the ESC key to exit");
            }while (Console.ReadKey(true).Key != ConsoleKey.Escape);
        }
            private static void InvokeCallbacks(CacheEntry entry)
            {
                List <PostEvictionCallbackRegistration> callbackRegistrations = Interlocked.Exchange(ref entry._tokens._postEvictionCallbacks, null);

                if (callbackRegistrations == null)
                {
                    return;
                }

                for (int i = 0; i < callbackRegistrations.Count; i++)
                {
                    PostEvictionCallbackRegistration registration = callbackRegistrations[i];

                    try
                    {
                        registration.EvictionCallback?.Invoke(entry.Key, entry.Value, entry.EvictionReason, registration.State);
                    }
                    catch (Exception e)
                    {
                        // This will be invoked on a background thread, don't let it throw.
                        entry._cache._logger.LogError(e, "EvictionCallback invoked failed");
                    }
                }
            }
Пример #14
0
        private static void AddPostEvictionPolicy(ICacheManager cacheManager, string partitionName, string key, PostEvictionCallbackRegistration postEvictionCallbackRegistration)
        {
            // Remove on token expiration
            var cts = new CancellationTokenSource();

            cacheManager.Set(InMemoryStorePartition, key, new object(), new CancellationChangeToken(cts.Token), postEvictionCallbackRegistration);

            // Fire the token to see the registered callback being invoked
            cts.Cancel();

            // Expire an entry if the dependent entry expires
            cacheManager.Set(InMemoryStorePartition, "key1", "value1");

            // expire this entry if the entry with key "key2" expires.
            cts = new CancellationTokenSource();
            cacheManager.Set(InMemoryStorePartition, "key2", "value2", new CancellationChangeToken(cts.Token), postEvictionCallbackRegistration);

            // Fire the token to see the registered callback being invoked
            cts.Cancel();
        }