Skip to content

Instantly share code, notes, and snippets.

@ptupitsyn
Created July 28, 2020 10:12
Show Gist options
  • Save ptupitsyn/bad4064b01a0cab20769eff2bd2e7aca to your computer and use it in GitHub Desktop.
Save ptupitsyn/bad4064b01a0cab20769eff2bd2e7aca to your computer and use it in GitHub Desktop.
Apache Ignite.NET GroBuf Serialization
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Apache.Ignite" Version="2.8.1" />
<PackageReference Include="AutoMapper" Version="10.0.0" />
<PackageReference Include="GroBuf" Version="1.5.5" />
</ItemGroup>
</Project>
using System;
using Apache.Ignite.Core;
using Apache.Ignite.Core.Binary;
using AutoMapper;
using GroBuf;
using GroBuf.DataMembersExtracters;
namespace ConsoleApp19
{
class Program
{
static void Main()
{
var сfg = new IgniteConfiguration
{
BinaryConfiguration = new BinaryConfiguration
{
Serializer = new GroBufIgniteSerializer()
}
};
var ignite = Ignition.Start(сfg);
var cache = ignite.GetOrCreateCache<int, Foo>("c");
cache.Put(1, new Foo {X = 5});
cache.Put(2, new Foo {X = 10});
Console.WriteLine(cache.Get(1));
Console.WriteLine(cache.Get(2));
}
}
internal class GroBufIgniteSerializer : IBinarySerializer
{
private const string DataField = "Data";
private static readonly Serializer Serializer =
new Serializer(new PropertiesExtractor(), options: GroBufOptions.WriteEmptyObjects);
private static readonly IMapper Mapper =
new MapperConfiguration(x => { x.CreateMap<Foo, Foo>(); }).CreateMapper();
public void WriteBinary(object obj, IBinaryWriter writer)
{
if (obj == null)
{
writer.WriteByteArray(DataField, null);
}
else
{
var data = Serializer.Serialize(obj.GetType(), obj);
writer.WriteByteArray(DataField, data);
}
}
public void ReadBinary(object obj, IBinaryReader reader)
{
var data = reader.ReadByteArray(DataField);
if (data == null)
{
return;
}
// Ideally, we should be able to deserialize directly into obj, to reduce allocations and avoid AutoMapper.
var res = Serializer.Deserialize(obj.GetType(), data);
Mapper.Map(res, obj);
}
}
class Foo
{
public int? X { get; set; }
public override string ToString()
{
return $"{nameof(X)}: {X}";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment