来看一个jute序列化,反序列化的例子
首先创建一个实例
public class MockReqHeader implements Record {
private long sessionId;
private String type;
public MockReqHeader() {
}
public MockReqHeader(long sessionId, String type) {
this.sessionId = sessionId;
this.type = type;
}
//... get set method
@Override
public void serialize(OutputArchive outputArchive, String s) throws IOException {
outputArchive.startRecord(this, s);
outputArchive.writeLong(sessionId, "sessionId");
outputArchive.writeString(type, "type");
outputArchive.endRecord(this, s);
}
@Override
public void deserialize(InputArchive inputArchive, String s) throws IOException {
inputArchive.startRecord(s);
sessionId = inputArchive.readLong("sessionId");
type = inputArchive.readString("type");
inputArchive.endRecord(s);
}
}
上面这个类反应了jute的序列化,反序列。大致有几个点需要注意下:
- 实例类实现了Record接口的serialize、deserialize的方法
- 构建一个序列化器OutputArchive
- 序列化
- 反序列化
运行一下看看
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
BinaryOutputArchive binaryOutputArchive =
BinaryOutputArchive.getArchive(byteArrayOutputStream);
new MockReqHeader(666, "ok").serialize(binaryOutputArchive, "header");
//这里通常是网络传输
ByteBuffer byteBuffer = ByteBuffer.wrap(byteArrayOutputStream.toByteArray());
//反序列化
ByteBufferInputStream byteBufferInputStream = new ByteBufferInputStream(byteBuffer);
BinaryInputArchive binaryInputArchive =
BinaryInputArchive.getArchive(byteBufferInputStream);
MockReqHeader header = new MockReqHeader();
header.deserialize(binaryInputArchive, "header");
byteBufferInputStream.close();
byteArrayOutputStream.close();