Xu Wenhao

View on GitHub
5 March 2012

Some Missing Tips For Apache Thrift

by Xu Wenhao

Thrift是个好东西,我们目前在内部大量使用thrift作为跨语言的数据交换方式,以及RPC的接口,thrift对于各种语言的支持都非常不错,不过Facebook对于thrift的文档实在是太少了。好在open source总是有人会把没有的东西给补上。这不,有人仿照google给protobuf的文档,在github上写了这么个东西 — — Thrift: The Missing Guide ,不过看了一下,相对还是比较简单,其实Thrift还是有不少undocumented的功能,比如,可以给field设默认值,比如,thrift支持union。

给field设默认值很有用,主要是为了向后的版本兼容,大量的field会以optional出现,但是可能有默认值,如果需要在代码里逐一设置,既容易犯错,写起来也麻烦,设了默认值之后,就没有这个问题了,而且序列化的时候,默认值是不占空间的。

比如这样:

namespace java com.xuwh.thrift
struct Person {  
  1:required string firstName,  
  2:required string lastName,  
  3:optional bool fullTime = 1,  
  4:optional bool adult = 0  
}
union的这个功能我还是从著名的Nathan Marz那边看来的,好处是可以让一些互斥的field作为union出现,而不是有一堆堆optional的field,语义上也更加明确了,比如这样
namespace java com.xuwh.thrift
struct Person {  
  1:required string firstName,  
  2:required string lastName,  
  3:optional bool fullTime = 1,  
  4:optional bool adult = 0  
}
struct Organization {  
  1:required string organizationName,  
  2:required i32 numOfEmployee  
}
union FoundationMember {  
  1:required Person person,  
  2:required Organization organization  
}
很多open source的project的代码虽然看起来很简单,但是还是有不少好玩精巧的功能的,只是实在没有时间一一都琢磨过来。
tags: