-
Notifications
You must be signed in to change notification settings - Fork 31
Add a .Net Core distributed cache #29
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
fredericDelaporte
merged 8 commits into
nhibernate:master
from
fredericDelaporte:DistributedCore
Apr 2, 2018
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
d2745ad
Add a .Net Core distributed cache
fredericDelaporte 80b78d9
Refine .Net Core distributed cache factory model
fredericDelaporte 0db48db
Provide distributed cache factories
fredericDelaporte 58e0110
Support cache implementations having a max key length
fredericDelaporte 1a6ece4
Add a Memcached distributed cache factory
fredericDelaporte 4f319c9
Add sample test config for Redis and SqlServer
fredericDelaporte 5a88fb6
Generate XML comment documentation for Core distributed caches
fredericDelaporte b597957
Remove code obsoleted by rebase
fredericDelaporte File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
5 changes: 5 additions & 0 deletions
5
CoreDistributedCache/NHibernate.Caches.CoreDistributedCache.Memcached/AssemblyInfo.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
using System; | ||
using System.Reflection; | ||
|
||
[assembly: CLSCompliant(true)] | ||
[assembly: AssemblyDelaySign(false)] |
157 changes: 157 additions & 0 deletions
157
CoreDistributedCache/NHibernate.Caches.CoreDistributedCache.Memcached/MemcachedFactory.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,157 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using Enyim.Caching; | ||
using Enyim.Caching.Configuration; | ||
using Microsoft.Extensions.Caching.Distributed; | ||
using Microsoft.Extensions.Logging; | ||
using Newtonsoft.Json; | ||
|
||
namespace NHibernate.Caches.CoreDistributedCache.Memcached | ||
{ | ||
/// <summary> | ||
/// A Memcached distributed cache factory. | ||
/// </summary> | ||
public class MemcachedFactory : IDistributedCacheFactory | ||
{ | ||
private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(MemcachedFactory)); | ||
private const string _configuration = "configuration"; | ||
|
||
private readonly IDistributedCache _cache; | ||
|
||
/// <summary> | ||
/// Constructor with configuration properties. It supports <c>configuration</c>, which has to be a JSON string | ||
/// structured like the value part of the <c>"enyimMemcached"</c> property in an appsettings.json file. | ||
/// </summary> | ||
/// <param name="properties">The configurations properties.</param> | ||
public MemcachedFactory(IDictionary<string, string> properties) : this() | ||
{ | ||
MemcachedClientOptions options; | ||
if (properties != null && properties.TryGetValue(_configuration, out var configuration) && !string.IsNullOrWhiteSpace(configuration)) | ||
{ | ||
options = JsonConvert.DeserializeObject<MemcachedClientOptions>(configuration); | ||
} | ||
else | ||
{ | ||
Log.Warn("No {0} property provided", _configuration); | ||
options = new MemcachedClientOptions(); | ||
} | ||
|
||
var loggerFactory = new LoggerFactory(); | ||
|
||
_cache = new MemcachedClient(loggerFactory, new MemcachedClientConfiguration(loggerFactory, options)); | ||
} | ||
|
||
private MemcachedFactory() | ||
{ | ||
Constraints = new CacheConstraints | ||
{ | ||
MaxKeySize = 250, | ||
KeySanitizer = SanitizeKey | ||
}; | ||
} | ||
|
||
// According to https://groups.google.com/forum/#!topic/memcached/Tz1RE0FUbNA, | ||
// memcached key can't contain space, newline, return, tab, vertical tab or form feed. | ||
// Since keys contains entity identifiers which may be anything, purging them all. | ||
private static readonly char[] ForbiddenChar = new [] { ' ', '\n', '\r', '\t', '\v', '\f' }; | ||
|
||
private static string SanitizeKey(string key) | ||
{ | ||
foreach (var forbidden in ForbiddenChar) | ||
{ | ||
key = key.Replace(forbidden, '-'); | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I have checked two other implementations: For reference, here is how I have checked: [Test]
public void PerfTest()
{
var keys = new[]
{
"abcdefghijklmnopkrstuvwxyz",
"abcde\fghijklm\nopk\r \tu\vwxyz",
"abcdefghijklmnopkrstuvwxyzabcdefghijklmnopkrstuvwxyzabcdefghijklmnopkrstuvwxyzabcdefghijklmnopkrstuvwxyz" +
"abcdefghijklmnopkrstuvwxyzabcdefghijklmnopkrstuvwxyzabcdefghijklmnopkrstuvwxyzabcdefghijklmnopkrstuvwxyz",
"abcde\fghijklm\nopk\r \tu\vwxyzabcde\fghijklm\nopk\r \tu\vwxyzabcde\fghijklm\nopk\r \tu\vwxyzabcde\fghijklm\nopk\r \tu\vwxyz" +
"abcde\fghijklm\nopk\r \tu\vwxyzabcde\fghijklm\nopk\r \tu\vwxyzabcde\fghijklm\nopk\r \tu\vwxyzabcde\fghijklm\nopk\r \tu\vwxyz"
};
var sw = new Stopwatch();
Regex purgeForbiddenChar = null;
HashSet<char> forbiddenCharSet = null;
char[] forbiddenChar = null;
var algos = new[]
{
new Tuple<string, System.Action, Func<string, string>>("Regex",
() => purgeForbiddenChar = new Regex("[ \n\r\t\v\f]", RegexOptions.Compiled),
s => purgeForbiddenChar.Replace(s, "-")),
new Tuple<string, System.Action, Func<string, string>>("Builder",
() => forbiddenCharSet = new HashSet<char> { ' ', '\n', '\r', '\t', '\v', '\f' },
s =>
{
var sanitizedKey = new StringBuilder();
foreach (var c in s)
{
sanitizedKey.Append(forbiddenCharSet.Contains(c) ? '-' : c);
}
return sanitizedKey.ToString();
}),
new Tuple<string, System.Action, Func<string, string>>("Replace",
() => forbiddenChar = new[] { '\n', ' ', '\r', '\t', '\v', '\f' },
s =>
{
foreach (var forbidden in forbiddenChar)
{
s = s.Replace(forbidden, '-');
}
return s;
})
};
foreach (var algo in algos)
{
sw.Restart();
algo.Item2();
foreach (var k in keys)
{
Console.WriteLine(algo.Item3(k));
}
Console.WriteLine($"{sw.Elapsed} for {algo.Item1} warmup");
foreach (var k in keys)
{
sw.Restart();
for (var i = 0; i < 1000; i++)
{
algo.Item3(k + i);
}
Console.WriteLine($"{sw.Elapsed} for {algo.Item1} key {k}");
}
}
} |
||
return key; | ||
} | ||
|
||
/// <inheritdoc /> | ||
public CacheConstraints Constraints { get; } | ||
|
||
/// <inheritdoc /> | ||
[CLSCompliant(false)] | ||
public IDistributedCache BuildCache() | ||
{ | ||
return _cache; | ||
} | ||
|
||
private class LoggerFactory : Microsoft.Extensions.Logging.ILoggerFactory | ||
{ | ||
public void Dispose() | ||
{ | ||
} | ||
|
||
public ILogger CreateLogger(string categoryName) | ||
{ | ||
return new LoggerWrapper(NHibernateLogger.For(categoryName)); | ||
} | ||
|
||
public void AddProvider(ILoggerProvider provider) | ||
{ | ||
} | ||
} | ||
|
||
private class LoggerWrapper : ILogger | ||
{ | ||
private readonly INHibernateLogger _logger; | ||
|
||
public LoggerWrapper(INHibernateLogger logger) | ||
{ | ||
_logger = logger; | ||
} | ||
|
||
void ILogger.Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, | ||
Func<TState, Exception, string> formatter) | ||
{ | ||
if (!IsEnabled(logLevel)) | ||
return; | ||
|
||
if (formatter == null) | ||
throw new ArgumentNullException(nameof(formatter)); | ||
|
||
_logger.Log( | ||
TranslateLevel(logLevel), | ||
new NHibernateLogValues("EventId {0}: {1}", new object[] { eventId, formatter(state, exception) }), | ||
// Avoid double logging of exception by not providing it to the logger, but only to the formatter. | ||
null); | ||
} | ||
|
||
public bool IsEnabled(LogLevel logLevel) | ||
=> _logger.IsEnabled(TranslateLevel(logLevel)); | ||
|
||
public IDisposable BeginScope<TState>(TState state) | ||
=> NoopScope.Instance; | ||
|
||
private NHibernateLogLevel TranslateLevel(LogLevel level) | ||
{ | ||
switch (level) | ||
{ | ||
case LogLevel.None: | ||
return NHibernateLogLevel.None; | ||
case LogLevel.Trace: | ||
return NHibernateLogLevel.Trace; | ||
case LogLevel.Debug: | ||
return NHibernateLogLevel.Debug; | ||
case LogLevel.Information: | ||
return NHibernateLogLevel.Info; | ||
case LogLevel.Warning: | ||
return NHibernateLogLevel.Warn; | ||
case LogLevel.Error: | ||
return NHibernateLogLevel.Error; | ||
case LogLevel.Critical: | ||
return NHibernateLogLevel.Fatal; | ||
} | ||
|
||
return NHibernateLogLevel.Trace; | ||
} | ||
|
||
private class NoopScope : IDisposable | ||
{ | ||
public static readonly NoopScope Instance = new NoopScope(); | ||
|
||
public void Dispose() | ||
{ | ||
} | ||
} | ||
} | ||
} | ||
} |
34 changes: 34 additions & 0 deletions
34
...es.CoreDistributedCache.Memcached/NHibernate.Caches.CoreDistributedCache.Memcached.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
<Import Project="../../NHibernate.Caches.props" /> | ||
<PropertyGroup> | ||
<Product>NHibernate.Caches.CoreDistributedCache.Memcached</Product> | ||
<Title>NHibernate.Caches.CoreDistributedCache.Memcached</Title> | ||
<Description>Memcached cache provider for NHibernate using .Net Core IDistributedCache (EnyimMemcachedCore).</Description> | ||
<!-- Targeting net461 explicitly in order to avoid https://github.com/dotnet/standard/issues/506 for net461 consumers--> | ||
<TargetFrameworks>net461;netstandard2.0</TargetFrameworks> | ||
<SignAssembly>False</SignAssembly> | ||
<GenerateDocumentationFile>true</GenerateDocumentationFile> | ||
<PackageReleaseNotes>* New feature | ||
* #28 - Add a .Net Core DistributedCache</PackageReleaseNotes> | ||
</PropertyGroup> | ||
<PropertyGroup Condition="'$(TargetFramework)' == 'net461'"> | ||
<DefineConstants>NETFX;$(DefineConstants)</DefineConstants> | ||
</PropertyGroup> | ||
<ItemGroup> | ||
<None Include="..\..\NHibernate.Caches.snk" Link="NHibernate.snk" /> | ||
</ItemGroup> | ||
<ItemGroup> | ||
<ProjectReference Include="..\NHibernate.Caches.CoreDistributedCache\NHibernate.Caches.CoreDistributedCache.csproj" /> | ||
</ItemGroup> | ||
<ItemGroup> | ||
<Content Include="../../readme.md"> | ||
<PackagePath>./NHibernate.Caches.readme.md</PackagePath> | ||
</Content> | ||
<Content Include="../../LICENSE.txt"> | ||
<PackagePath>./NHibernate.Caches.license.txt</PackagePath> | ||
</Content> | ||
</ItemGroup> | ||
<ItemGroup> | ||
<PackageReference Include="EnyimMemcachedCore" Version="2.1.0" /> | ||
</ItemGroup> | ||
</Project> |
5 changes: 5 additions & 0 deletions
5
CoreDistributedCache/NHibernate.Caches.CoreDistributedCache.Memory/AssemblyInfo.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
using System; | ||
using System.Reflection; | ||
|
||
[assembly: CLSCompliant(true)] | ||
[assembly: AssemblyDelaySign(false)] |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It is a bit messy to integrate a library meant to be used with the .Net Core default dependency injection system with NHibernate factories/configuration logic.
EnyimMemcachedCore was the worst case, due to its dependency on a logger factory (I have provided it through a wrapping of the NHibernate one) and its structured configuration (thus the JSON trick I have choosen for it).
Maybe should each factory also expose directly a constructor with the cache dependencies (at least
IMemcachedClientConfiguration
and maybeILoggerFactory
for this case)for users who would set the factory programmatically.