Thrift資料轉送序列化

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

Thrift的序列化是比Json更好用的結構(具體哪裡好了我還沒研究)。但是它有一個非常嚴重的問題:相容性差。常年使用Json的我們已經被慣壞了,潛意識裡就覺得資料預設是能保持相容的。

先說一下那個線上問題。我與公司其它部門用Thrift對接,先上了一版,我是調用方。接著,二次升級的時候,合作的部門改了一下Idl,在函數返回結果結構體的最前面,插入了一個結構,是一個結構體,原本第一版第一個位置是整形。然後他們上線了,我還在排隊上線。突然監控就報我介面返回了404(一般錯誤都轉成404)。然後去排查,發現返回了一堆負數,負數導致後面的邏輯出問題了,哪怕返回了整數,也是非常不正常。

這個關鍵的時刻,我們組長(永遠是他)給解釋了bug的原因,是Thrift不相容導致的。

struct Pair {1: required string key2: required string value}

上面這個結構體,如果解析成Json,是按照索引值對的形式展示,欄位變數的名稱是有意義的。而在Thrift裡面,依然是索引值對的形式,但是沒有用變數名的名字作為鍵,而是通過序號和類型作為鍵,序號決定位置,類型決定解析方式。

Versioning in Thrift is implemented via field identifiers. The field header for every member of a struct in Thrift is encoded with a unique field identifier. The combination of this field identifier and its type specifier is used to uniquely identify the field. The Thrift definition language supports automatic assignment of field identifiers, but it is good programming practice to always explicitly specify field identifiers.

之前寫過一篇《Golang開發Thrift介面》,這次接著以這個為基礎修改進行實驗。新增一個測試函數,返回我們要實驗的這個結構體。

Pair helloPair()

通過Idl產生Golang包:

thrift -v --gen go:package_prefix=go_code/test_thrift Hello1.thrift

helloimpl.go實現這個新增的方法:

func (h *HelloHandler) HelloPair() (*hello.Pair, error) {p := new(hello.Pair)p.Key = "rowkey"p.Value = "column-family"return p, nil}

啟動服務端:

go run helloserver.go helloimpl.go

helloclient.go增加調用:

res, err := client.HelloPair()fmt.Println(res.String())

結果如下:

$ go run helloclient.goPair({Key:rowkey Value:column-family})

結果正確,下面來類比錯誤的情況。這個類比很簡單,修改Idl順序:

struct Pair {2: required string key1: required string value}

重建一遍Idl,為了對比,我把這個Idl命名為Hello1.thrift。然後複製原檔案並重新命名為helloimpl1.gohelloserver1.go。把引用的包名改成hello "go_code/test_thrift/hello1"。再啟動服務端:

hello "go_code/test_thrift/hello1"

用戶端不做任何修改:

$ go run helloclient.goPair({Key:column-family Value:rowkey})

結果正好相反,Amazing有沒有。。。

本文所涉及到的完整源碼請參考。

參考文獻
  1. Thrift 個人實戰–Thrift 的序列化機制 - mumuxinfei

原文連結:Thrift資料轉送序列化,轉載請註明來源!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.