Skip to content

Commit 4cb8afe

Browse files
authored
Merge pull request #37 from cnblogs/add-BinaryFormatter
Implement BinaryFormatterTranscoder
2 parents 47e4421 + 658f015 commit 4cb8afe

File tree

7 files changed

+81
-8
lines changed

7 files changed

+81
-8
lines changed

Enyim.Caching/Configuration/MemcachedClientConfiguration.cs

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -125,9 +125,24 @@ public MemcachedClientConfiguration(
125125
NodeLocator = options.Servers.Count > 1 ? typeof(DefaultNodeLocator) : typeof(SingleNodeLocator);
126126
}
127127

128-
if(options.Transcoder != null)
128+
if(!string.IsNullOrEmpty(options.Transcoder))
129129
{
130-
_transcoder = options.Transcoder;
130+
try
131+
{
132+
if (options.Transcoder == "BinaryFormatterTranscoder")
133+
options.Transcoder = "Enyim.Caching.Memcached.Transcoders.BinaryFormatterTranscoder";
134+
135+
var transcoderType = Type.GetType(options.Transcoder);
136+
if (transcoderType != null)
137+
{
138+
Transcoder = Activator.CreateInstance(transcoderType) as ITranscoder;
139+
_logger.LogDebug($"Use '{options.Transcoder}'");
140+
}
141+
}
142+
catch (Exception ex)
143+
{
144+
_logger.LogError(new EventId(), ex, $"Unable to load '{options.Transcoder}'");
145+
}
131146
}
132147

133148
if (options.NodeLocatorFactory != null)

Enyim.Caching/Configuration/MemcachedClientOptions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ public class MemcachedClientOptions : IOptions<MemcachedClientOptions>
1919

2020
public string KeyTransformer { get; set; }
2121

22-
public ITranscoder Transcoder { get; set; }
22+
public string Transcoder { get; set; }
2323

2424
public IProviderFactory<IMemcachedNodeLocator> NodeLocatorFactory { get; set; }
2525

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.IO;
4+
using System.Runtime.Serialization.Formatters.Binary;
5+
using System.Text;
6+
7+
namespace Enyim.Caching.Memcached.Transcoders
8+
{
9+
public class BinaryFormatterTranscoder : DefaultTranscoder
10+
{
11+
protected override ArraySegment<byte> SerializeObject(object value)
12+
{
13+
using (var ms = new MemoryStream())
14+
{
15+
new BinaryFormatter().Serialize(ms, value);
16+
return new ArraySegment<byte>(ms.GetBuffer(), 0, (int)ms.Length);
17+
}
18+
}
19+
20+
public override T Deserialize<T>(CacheItem item)
21+
{
22+
return (T)base.Deserialize(item);
23+
}
24+
25+
protected override object DeserializeObject(ArraySegment<byte> value)
26+
{
27+
using (var ms = new MemoryStream(value.Array, value.Offset, value.Count))
28+
{
29+
return new BinaryFormatter().Deserialize(ms);
30+
}
31+
}
32+
}
33+
}

Enyim.Caching/Memcached/Transcoders/DefaultTranscoder.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ object ITranscoder.Deserialize(CacheItem item)
2828
return this.Deserialize(item);
2929
}
3030

31-
T ITranscoder.Deserialize<T>(CacheItem item)
31+
public virtual T Deserialize<T>(CacheItem item)
3232
{
3333
if (item.Data == null || item.Data.Count == 0) return default(T);
3434

@@ -184,7 +184,7 @@ protected virtual object Deserialize(CacheItem item)
184184
// earlier versions serialized decimals with TypeCode.Decimal
185185
// even though they were saved by BinaryFormatter
186186
case TypeCode.Decimal:
187-
//case TypeCode.Object: return this.DeserializeObject(data);
187+
case TypeCode.Object: return this.DeserializeObject(data);
188188
default: throw new InvalidOperationException("Unknown TypeCode was returned: " + code);
189189
}
190190
}

MemcachedTest/MemcachedClientTest.cs

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,21 +19,27 @@ public abstract class MemcachedClientTest
1919
private static readonly Enyim.Caching.ILog log = Enyim.Caching.LogManager.GetLogger(typeof(MemcachedClientTest));
2020
public const string TestObjectKey = "Hello_World";
2121

22-
protected virtual MemcachedClient GetClient(MemcachedProtocol protocol = MemcachedProtocol.Binary)
22+
protected virtual MemcachedClient GetClient(MemcachedProtocol protocol = MemcachedProtocol.Binary, bool useBinaryFormatterTranscoder = false)
2323
{
2424
IServiceCollection services = new ServiceCollection();
2525
services.AddEnyimMemcached(options =>
2626
{
2727
options.AddServer("memcached", 11211);
2828
options.Protocol = protocol;
29+
if (useBinaryFormatterTranscoder)
30+
{
31+
options.Transcoder = "BinaryFormatterTranscoder";
32+
}
2933
});
30-
services.AddLogging();
34+
services.AddLogging(builder => builder.SetMinimumLevel(LogLevel.Error).AddConsole());
35+
3136
IServiceProvider serviceProvider = services.BuildServiceProvider();
3237
var client = serviceProvider.GetService<IMemcachedClient>() as MemcachedClient;
3338
client.Remove("VALUE");
3439
return client;
3540
}
3641

42+
[Serializable]// This attribute is for BinaryFormatterTranscoder
3743
public class TestData
3844
{
3945
public TestData() { }
@@ -60,6 +66,11 @@ public async Task StoreObjectTest()
6066
{
6167
Assert.True(await client.StoreAsync(StoreMode.Set, TestObjectKey, td, DateTime.Now.AddSeconds(5)));
6268
}
69+
70+
using (MemcachedClient client = GetClient(MemcachedProtocol.Binary, true))
71+
{
72+
Assert.True(await client.StoreAsync(StoreMode.Set, TestObjectKey, td, DateTime.Now.AddSeconds(5)));
73+
}
6374
}
6475

6576
[Fact]
@@ -83,6 +94,18 @@ public void GetObjectTest()
8394
Assert.Equal(td2.FieldC, 19810619);
8495
Assert.True(td2.FieldD, "Object was corrupted.");
8596
}
97+
98+
using (MemcachedClient client = GetClient(MemcachedProtocol.Binary, true))
99+
{
100+
Assert.True(client.Store(StoreMode.Set, TestObjectKey, td), "Initialization failed.");
101+
TestData td2 = client.Get<TestData>(TestObjectKey);
102+
103+
Assert.NotNull(td2);
104+
Assert.Equal(td2.FieldA, "Hello");
105+
Assert.Equal(td2.FieldB, "World");
106+
Assert.Equal(td2.FieldC, 19810619);
107+
Assert.True(td2.FieldD, "Object was corrupted.");
108+
}
86109
}
87110

88111
[Fact]

MemcachedTest/MemcachedTest.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
<ItemGroup>
77
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.0.0" />
88
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.0.0" />
9+
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.0.0" />
910
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.3.0" />
1011
<PackageReference Include="xunit" Version="2.3.0-beta3-build3705" />
1112
<PackageReference Include="xunit.runner.visualstudio" Version="2.3.0-beta3-build3705" />

SampleWebApp/appsettings.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@
1313
"receiveTimeout": "00:00:15",
1414
"deadTimeout": "00:00:15",
1515
"queueTimeout": "00:00:00.150"
16-
}
16+
}//,
17+
//"Transcoder": "BinaryFormatterTranscoder"
1718
//,
1819
//"KeyTransformer": "Enyim.Caching.Memcached.SHA1KeyTransformer"
1920
//,

0 commit comments

Comments
 (0)