一、前言
在完成了前面的理论学习后,现在可以从源码角度来解析Zookeeper的细节,首先笔者想从序列化入手,因为在网络通信、数据存储中都用到了序列化,下面开始分析。
二、序列化
序列化主要在zookeeper.jute包中,其中涉及的主要接口如下
· InputArchive
· OutputArchive
· Index
· Record
2.1 InputArchive
其是所有反序列化器都需要实现的接口,其方法如下
InputArchive的类结构如下
- BinaryInputArchive
- CsvInputArchive
XmlInputArchive
Java
运行代码
复制代码
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/**} return Float.parseFloat(v.getValue());}
// 读取double类型
public double readDouble(String tag) throws IOException {Value v = next(); if (!"double".equals(v.getType())) { throw new IOException("Error deserializing "+tag+"."); } return Double.parseDouble(v.getValue());}
// 读取String类型
public String readString(String tag) throws IOException {Value v = next(); if (!"string".equals(v.getType())) { throw new IOException("Error deserializing "+tag+"."); } return Utils.fromXMLString(v.getValue());}
// 读取Buffer类型
public byte[] readBuffer(String tag) throws IOException {Value v = next(); if (!"string".equals(v.getType())) { throw new IOException("Error deserializing "+tag+"."); } return Utils.fromXMLBuffer(v.getValue());}
// 读取Record类型
public void readRecord(Record r, String tag) throws IOException {r.deserialize(this, tag);}
// 开始读取Record
public void startRecord(String tag) throws IOException {Value v = next(); if (!"struct".equals(v.getType())) { throw new IOException("Error deserializing "+tag+"."); }}
// 结束读取Record
public void endRecord(String tag) throws IOException {Value v = next(); if (!"/struct".equals(v.getType())) { throw new IOException("Error deserializing "+tag+"."); }}
// 开始读取vector
public Index startVector(String tag) throws IOException {Value v = next(); if (!"array".equals(v.getType())) { throw new IOException("Error deserializing "+tag+"."); } return new XmlIndex();}
// 结束读取vector
public void endVector(String tag) throws IOException {}// 开始读取Map
public Index startMap(String tag) throws IOException {return startVector(tag);}
// 停止读取Map
public void endMap(String tag) throws IOException { endVector(tag); }
}