Skip to content

Commit 5585435

Browse files
Supports use of JsonCacheSerializer
fix #106
1 parent de82636 commit 5585435

File tree

7 files changed

+123
-51
lines changed

7 files changed

+123
-51
lines changed

CoreDistributedCache/NHibernate.Caches.CoreDistributedCache.Tests/Async/CoreDistributedCacheFixture.cs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@
3737
using NHibernate.Caches.Common.Tests;
3838
using NUnit.Framework;
3939
using NSubstitute;
40+
using NHibernate.Caches.Util.JsonSerializer;
41+
using NHibernate.Engine;
4042

4143
namespace NHibernate.Caches.CoreDistributedCache.Tests
4244
{
@@ -68,5 +70,25 @@ public async Task KeySanitizerAsync()
6870
await (distribCache.Received().SetAsync(Arg.Is<string>(k => k.Contains(keySanitizer("-abc-"))), Arg.Any<byte[]>(),
6971
Arg.Any<DistributedCacheEntryOptions>()));
7072
}
73+
74+
[Test]
75+
public async Task CanUseCacheKeyWithJsonSerializerAsync()
76+
{
77+
var key = new CacheKey("keyTestJsonPut", NHibernateUtil.String, "someEntityName", Substitute.For<ISessionFactoryImplementor>());
78+
const string value = "valuePut";
79+
80+
var props = GetDefaultProperties();
81+
props["cache.serializer"] = typeof(DistributedCacheJsonSerializer).AssemblyQualifiedName;
82+
var cache = (CacheBase) DefaultProvider.BuildCache(DefaultRegion, props);
83+
// Due to async version, it may already be there.
84+
await (cache.RemoveAsync(key, CancellationToken.None));
85+
86+
Assert.That(await (cache.GetAsync(key, CancellationToken.None)), Is.Null, "cache returned an item we didn't add !?!");
87+
88+
await (cache.PutAsync(key, value, CancellationToken.None));
89+
var item = await (cache.GetAsync(key, CancellationToken.None));
90+
Assert.That(item, Is.Not.Null, "Unable to retrieve cached item");
91+
Assert.That(item, Is.EqualTo(value), "didn't return the item we added");
92+
}
7193
}
7294
}

CoreDistributedCache/NHibernate.Caches.CoreDistributedCache.Tests/CoreDistributedCacheFixture.cs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@
2727
using NHibernate.Caches.Common.Tests;
2828
using NUnit.Framework;
2929
using NSubstitute;
30+
using NHibernate.Caches.Util.JsonSerializer;
31+
using NHibernate.Engine;
3032

3133
namespace NHibernate.Caches.CoreDistributedCache.Tests
3234
{
@@ -35,6 +37,7 @@ public partial class CoreDistributedCacheFixture : CacheFixture
3537
{
3638
protected override bool SupportsSlidingExpiration => true;
3739
protected override bool SupportsClear => false;
40+
protected override bool SupportsDistinguishingKeysWithSameStringRepresentationAndHashcode => false;
3841

3942
protected override Func<ICacheProvider> ProviderBuilder =>
4043
() => new CoreDistributedCacheProvider();
@@ -62,5 +65,33 @@ public void KeySanitizer()
6265
distribCache.Received().Set(Arg.Is<string>(k => k.Contains(keySanitizer("-abc-"))), Arg.Any<byte[]>(),
6366
Arg.Any<DistributedCacheEntryOptions>());
6467
}
68+
69+
[Test]
70+
public void CanUseCacheKeyWithJsonSerializer()
71+
{
72+
var key = new CacheKey("keyTestJsonPut", NHibernateUtil.String, "someEntityName", Substitute.For<ISessionFactoryImplementor>());
73+
const string value = "valuePut";
74+
75+
var props = GetDefaultProperties();
76+
props["cache.serializer"] = typeof(DistributedCacheJsonSerializer).AssemblyQualifiedName;
77+
var cache = (CacheBase) DefaultProvider.BuildCache(DefaultRegion, props);
78+
// Due to async version, it may already be there.
79+
cache.Remove(key);
80+
81+
Assert.That(cache.Get(key), Is.Null, "cache returned an item we didn't add !?!");
82+
83+
cache.Put(key, value);
84+
var item = cache.Get(key);
85+
Assert.That(item, Is.Not.Null, "Unable to retrieve cached item");
86+
Assert.That(item, Is.EqualTo(value), "didn't return the item we added");
87+
}
88+
89+
private class DistributedCacheJsonSerializer : JsonCacheSerializer
90+
{
91+
public DistributedCacheJsonSerializer()
92+
{
93+
RegisterType(typeof(Tuple<string, object>), "tso");
94+
}
95+
}
6596
}
6697
}

CoreDistributedCache/NHibernate.Caches.CoreDistributedCache.Tests/NHibernate.Caches.CoreDistributedCache.Tests.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
</PropertyGroup>
1616
<ItemGroup>
1717
<ProjectReference Include="..\..\NHibernate.Caches.Common.Tests\NHibernate.Caches.Common.Tests.csproj" />
18+
<ProjectReference Include="..\..\Util\NHibernate.Caches.Util.JsonSerializer\NHibernate.Caches.Util.JsonSerializer.csproj" />
1819
<ProjectReference Include="..\NHibernate.Caches.CoreDistributedCache.Memcached\NHibernate.Caches.CoreDistributedCache.Memcached.csproj" />
1920
<ProjectReference Include="..\NHibernate.Caches.CoreDistributedCache.Memory\NHibernate.Caches.CoreDistributedCache.Memory.csproj" />
2021
<ProjectReference Include="..\NHibernate.Caches.CoreDistributedCache.Redis\NHibernate.Caches.CoreDistributedCache.Redis.csproj" />

CoreDistributedCache/NHibernate.Caches.CoreDistributedCache/Async/CoreDistributedCache.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,15 +33,15 @@ public override async Task<object> GetAsync(object key, CancellationToken cancel
3333
return null;
3434
}
3535

36-
var cacheKey = GetCacheKey(key);
36+
var (fullKey, cacheKey) = GetCacheKey(key);
3737
Log.Debug("Fetching object '{0}' from the cache.", cacheKey);
3838

3939
var cachedData = await (_cache.GetAsync(cacheKey, cancellationToken)).ConfigureAwait(false);
4040
if (cachedData == null)
4141
return null;
4242

43-
var entry = _serializer.Deserialize(cachedData) as Tuple<object, object>;
44-
return Equals(entry?.Item1, key) ? entry.Item2 : null;
43+
var entry = _serializer.Deserialize(cachedData) as Tuple<string, object>;
44+
return Equals(entry?.Item1, fullKey) ? entry.Item2 : null;
4545
}
4646

4747
/// <inheritdoc />
@@ -63,10 +63,10 @@ public override Task PutAsync(object key, object value, CancellationToken cancel
6363
try
6464
{
6565

66-
var entry = new Tuple<object, object>(key, value);
66+
var (fullKey, cacheKey) = GetCacheKey(key);
67+
var entry = new Tuple<string, object>(fullKey, value);
6768
var cachedData = _serializer.Serialize(entry);
6869

69-
var cacheKey = GetCacheKey(key);
7070
var options = new DistributedCacheEntryOptions();
7171
if (UseSlidingExpiration)
7272
options.SlidingExpiration = Expiration;
@@ -96,7 +96,7 @@ public override Task RemoveAsync(object key, CancellationToken cancellationToken
9696
try
9797
{
9898

99-
var cacheKey = GetCacheKey(key);
99+
var (_, cacheKey) = GetCacheKey(key);
100100
Log.Debug("removing item with key: {0}", cacheKey);
101101
return _cache.RemoveAsync(cacheKey, cancellationToken);
102102
}

CoreDistributedCache/NHibernate.Caches.CoreDistributedCache/CoreDistributedCache.cs

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -293,13 +293,15 @@ private static bool GetAppendHashcodeToKey(IDictionary<string, string> props)
293293
return append;
294294
}
295295

296-
private string GetCacheKey(object key)
296+
private (string fullKey, string sanitzedKey) GetCacheKey(object key)
297297
{
298298
var baseKey = _cacheKeyPrefix + _fullRegion + ":" + key;
299-
var keyAsString = AppendHashcodeToKey
299+
baseKey = AppendHashcodeToKey
300300
? baseKey + "@" + key.GetHashCode()
301301
: baseKey;
302302

303+
var keyAsString = baseKey;
304+
303305
if (_maxKeySize < keyAsString.Length)
304306
{
305307
// Hash it for respecting max key size. Collisions will be avoided by storing the actual key along
@@ -337,7 +339,7 @@ private string GetCacheKey(object key)
337339

338340
Log.Debug("Using cache key '{0}' for object key '{1}'.", keyAsString, key);
339341

340-
return keyAsString;
342+
return (baseKey, keyAsString);
341343
}
342344

343345
/// <inheritdoc />
@@ -348,15 +350,15 @@ public override object Get(object key)
348350
return null;
349351
}
350352

351-
var cacheKey = GetCacheKey(key);
353+
var (fullKey, cacheKey) = GetCacheKey(key);
352354
Log.Debug("Fetching object '{0}' from the cache.", cacheKey);
353355

354356
var cachedData = _cache.Get(cacheKey);
355357
if (cachedData == null)
356358
return null;
357359

358-
var entry = _serializer.Deserialize(cachedData) as Tuple<object, object>;
359-
return Equals(entry?.Item1, key) ? entry.Item2 : null;
360+
var entry = _serializer.Deserialize(cachedData) as Tuple<string, object>;
361+
return Equals(entry?.Item1, fullKey) ? entry.Item2 : null;
360362
}
361363

362364
/// <inheritdoc />
@@ -372,10 +374,10 @@ public override void Put(object key, object value)
372374
throw new ArgumentNullException(nameof(value), "null value not allowed");
373375
}
374376

375-
var entry = new Tuple<object, object>(key, value);
377+
var (fullKey, cacheKey) = GetCacheKey(key);
378+
var entry = new Tuple<string, object>(fullKey, value);
376379
var cachedData = _serializer.Serialize(entry);
377380

378-
var cacheKey = GetCacheKey(key);
379381
var options = new DistributedCacheEntryOptions();
380382
if (UseSlidingExpiration)
381383
options.SlidingExpiration = Expiration;
@@ -394,7 +396,7 @@ public override void Remove(object key)
394396
throw new ArgumentNullException(nameof(key));
395397
}
396398

397-
var cacheKey = GetCacheKey(key);
399+
var (_, cacheKey) = GetCacheKey(key);
398400
Log.Debug("removing item with key: {0}", cacheKey);
399401
_cache.Remove(cacheKey);
400402
}

0 commit comments

Comments
 (0)