Merge branch 'feature_distributeCache' of https://github.com/EngRajabi/Ocelot into EngRajabi-feature_distributeCache

This commit is contained in:
TomPallister
2020-04-13 18:01:39 +01:00
3 changed files with 162 additions and 2 deletions

View File

@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
namespace Ocelot.Cache
{
public class AspMemoryCache<T> : IOcelotCache<T>
{
private readonly IMemoryCache _memoryCache;
private readonly Dictionary<string, List<string>> _regions;
public AspMemoryCache(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
_regions = new Dictionary<string, List<string>>();
}
public void Add(string key, T value, TimeSpan ttl, string region)
{
if (ttl.TotalMilliseconds <= 0)
return;
_memoryCache.Set(key, value, ttl);
SetRegion(region, key);
}
public T Get(string key, string region)
{
_memoryCache.TryGetValue<T>(key, out T value);
return value;
}
public void ClearRegion(string region)
{
if (_regions.ContainsKey(region))
{
var keys = _regions[region];
foreach (var key in keys)
{
_memoryCache.Remove(key);
}
}
}
public void AddAndDelete(string key, T value, TimeSpan ttl, string region)
{
if (_memoryCache.TryGetValue(key, out object oldValue))
_memoryCache.Remove(key);
Add(key, value, ttl, region);
}
private void SetRegion(string region, string key)
{
if (_regions.ContainsKey(region))
{
var current = _regions[region];
if (!current.Contains(key))
{
current.Add(key);
}
}
else
{
_regions.Add(region, new List<string> { key });
}
}
}
}

View File

@ -58,8 +58,12 @@ namespace Ocelot.DependencyInjection
Services = services;
Services.Configure<FileConfiguration>(configurationRoot);
Services.TryAddSingleton<IOcelotCache<FileConfiguration>, InMemoryCache<FileConfiguration>>();
Services.TryAddSingleton<IOcelotCache<CachedResponse>, InMemoryCache<CachedResponse>>();
//Services.TryAddSingleton<IOcelotCache<FileConfiguration>, InMemoryCache<FileConfiguration>>();
//Services.TryAddSingleton<IOcelotCache<CachedResponse>, InMemoryCache<CachedResponse>>();
Services.TryAddSingleton<IOcelotCache<FileConfiguration>, AspMemoryCache<FileConfiguration>>();
Services.TryAddSingleton<IOcelotCache<CachedResponse>, AspMemoryCache<CachedResponse>>();
Services.TryAddSingleton<IHttpResponseHeaderReplacer, HttpResponseHeaderReplacer>();
Services.TryAddSingleton<IHttpContextRequestHeaderReplacer, HttpContextRequestHeaderReplacer>();
Services.TryAddSingleton<IHeaderFindAndReplaceCreator, HeaderFindAndReplaceCreator>();