天天看點

Storm-源碼分析- Thrift的使用

首先是storm.thrift, 作為idl裡面定義了用到的資料結構和service 

然後backtype.storm.generated, 存放從idl通過thrift自動轉化成的java代碼

比如對于nimbus service 

在idl的定義為,

而對應在nimbus.java的java代碼如下,

1. 首先get client,

看看backtype.storm.utils下面的client.getconfiguredclient的邏輯, 

隻是從配置中取出nimbus的host:port, 并new nimbusclient

nimbusclient 繼承自thriftclient, public class nimbusclient extends thriftclient 

thriftclient又做了什麼? 關鍵是怎麼進行資料序列化和怎麼将資料傳輸到remote 

這裡看出thrift對transport和protocol的封裝 

對于transport, 其實就是對socket的封裝, 使用tsocket(host, port) 

然後對于protocol, 預設使用tbinaryprotocol, 如果你不指定的話

2. 調用任意rpc 

那麼就看看submittopologywithopts

可以看出上面的nimbus的interface裡面有這個方法的定義, 而且thrift不僅僅自動産生java interface, 而且還提供整個rpc client端的實作

分兩步, 

首先send_submittopologywithopts, 調用sendbase 

接着, recv_submittopologywithopts, 調用receivebase 

可以看出thrift對protocol的封裝, 不需要自己處理序列化, 調用protocol的接口搞定 

thrift強大的地方是, 實作了整個協定棧而不光隻是idl的轉化, 對于server也給出多種實作 

下面看看在nimbus server端, 是用clojure來寫的 

可見其中使用thrift封裝的nonblockingserversocket, thshaserver, tbinaryprotocol, proccessor, 非常簡單 

其中processor會使用service-handle來處理recv到的資料, 是以作為使用者隻需要在service-handle中實作nimbus$iface, 其他和server相關的, thrift都已經幫你封裝好了, 這裡使用的idl也在backtype.storm.generated, 因為clojure基于jvm是以idl隻需要轉化成java即可.