我有数十亿个对象,我试图在序列化为HDD的B +树中构建它们。我使用BPlusTree库作为数据结构,protobuf-net使用序列化/反序列化。在这方面,我将我的类定义为:
[ProtoContract]
public class B<C, M>
where C : IComparable<C>
where M : IData<C>
{
internal B()
{
lambda = new List<Lambda<C, M>>();
omega = 0;
}
internal B(C coordinate)
{
lambda = new List<Lambda<C, M>>();
e = coordinate;
omega = 0;
}
[ProtoMember(1)]
internal C e { set; get; }
[ProtoMember(2)]
internal List<Lambda<C, M>> lambda { private set; get; }
[ProtoMember(3)]
internal int omega { set; get; }
}
[ProtoContract]
public class Lambda<C, M>
where C : IComparable<C>
where M : IData<C>
{
internal Lambda() { }
internal Lambda(char tau, M atI)
{
this.tau = tau;
this.atI = atI;
}
[ProtoMember(1)]
internal char tau { private set; get; }
[ProtoMember(2)]
internal M atI { private set; get; }
}
我将序列化器/反序列化器定义如下:
public class BSerializer<C, M> : ISerializer<B<C, M>>
where C : IComparable<C>
where M : IData<C>
{
public B<C, M> ReadFrom(System.IO.Stream stream)
{
return Serializer.Deserialize<B<C, M>>(stream);
}
public void WriteTo(B<C, M> value, System.IO.Stream stream)
{
Serializer.Serialize<B<C, M>>(stream, value);
}
}
然后我在B + Tree(This library)数据结构中使用它们,定义为:
var options = new BPlusTree<C, B<C, M>>.OptionsV2(CSerializer, BSerializer);
var myTree = new BPlusTree<C, B<C, M>>(options);
B + Tree被定义为键值对的字典。我的key
(即C
)是一个整数,序列化程序是BPlusTree
库的默认序列化程序。我的Value
是使用B<C,M>
序列化的自定义对象protobuf-net
。
我的问题肯定会发生,但几乎是随机的;始终搜索Keys
,它会突然开始反序列化Value
,并在第一次调用B<C, M> ReadFrom(System.IO.Stream stream)
时要求TypeModel.CS
和ProtoReader.CS
个文件。我从NuGet
获得了两个包。
答案 0 :(得分:2)
检查代码,看起来调用代码假定序列化知道自己的长度;来自消息来源:
foreach (T i in items)
_serializer.WriteTo(i, io);
Protobuf消息不是自我终止的 - 谷歌protobuf规范定义了append === merge。因此,您需要为消息添加前缀。幸运的是,您应该可以切换到SerializeWithLengthPrefix
和DeserializeWithLengthPrefix
。如果这不起作用,那么值得将完全可重复的示例放在一起,以便对其进行调查。
答案 1 :(得分:2)
作为解决此问题的替代方法,您还可以聚合内置选择器的行为:
class BSerializer<C, M> : ISerializer<B<C, M>>
where C : IComparable<C>
where M : IData<C>
{
public B<C, M> ReadFrom(System.IO.Stream stream)
{
byte[] value = CSharpTest.Net.Serialization.PrimitiveSerializer.Bytes.ReadFrom(stream);
return Serializer.Deserialize<B<C, M>>(new MemoryStream(value));
}
public void WriteTo(B<C, M> value, System.IO.Stream stream)
{
using (var memory = new MemoryStream())
{
Serializer.Serialize<B<C, M>>(memory, value);
CSharpTest.Net.Serialization.PrimitiveSerializer.Bytes.WriteTo(memory.ToArray(), stream);
}
}
}
注意:由于不必要的数据副本,此方法可能是性能问题;但是,它可以帮助解决问题。
另一种可能性是将树定义为BPlusTree<TKey, byte[]>
并提供PrimitiveSerializer.Bytes
作为值序列化程序。这会将对象序列化的负担放在调用者身上,这可能是一件非常好的事情。这可能有益的原因有两个:
对于其他常见的序列化问题和一些示例,请阅读以下文章:
http://csharptest.net/1230/bplustree-and-custom-iserializer-implementations/