開發一款開源爬蟲框架系列(六):爬蟲分散式化RPC
阿新 • • 發佈:2019-01-26
最近終於有部分時間繼續開發爬蟲,主要的任務是客戶端和伺服器端分離,這就涉及到遠端呼叫的問題,所以研究了RPC,主要物件是Hessian、JMI、Dubbo、Thrift。進而想用幾篇博文分享一下幾種遠端呼叫協議的一些東西,以後再接著聊爬蟲。有興趣可以訪問我的爬蟲專案:https://gitee.com/coliza/MongooCrawler
經過研究最終選擇了自定義協議的方式完成RPC協議,以下是部分協議程式碼:
public class CrawlerTransferProtocol<T> { private int type; private Class<T> cls; private T content; public int getType() { return type; } public void setType(int type) { this.type = type; } public Class<T> getCls() { return cls; } public void setCls(Class<T> cls) { this.cls = cls; } public T getContent() { return content; } public void setContent(T content) { this.content = content; } public byte toTypeByte() throws Exception { switch (type) { case 0: return 0x0; case 1: return 0x1; case 2: return 0x2; case 3: return 0x3; default: throw new Exception("協議解析錯誤"); } } public int getContentLen() { return JSONObject.toJSONString(content).getBytes().length; } public byte[] toContentBytes() { return JSONObject.toJSONString(content).getBytes(); } }
type是型別,爬蟲需要傳輸的資料分為三類,分別是命令、URL、網頁文字;cls是發起端傳輸的具體型別,主要用於序列化和反序列化,這裡的序列化和反序列化協議選擇使用json協議;content代表需要傳輸的資訊物件,根據cls和content就能在被呼叫端反序列化生成被呼叫物件。
客戶端發起RPC呼叫的過程是這樣的:
Dubbo、Thrift的rpc大同小異,各自選擇的編碼方式不一樣,為了提高效能還會對傳輸的資料進行壓縮處理,尤其是Thrift這樣的跨語言RPC需要相容多種語言,位元組碼編碼需要充分考慮各語言的細節差異並遮蔽掉這些差異,往往是以犧牲效能為代價的。爬蟲的應用領域比較特殊,不需要兼顧這些方面,以上相當於實現了一個簡化版的RPC協議。有興趣的讀者可以留下評論。