Thrift總結 四 Thrift實現雙向通訊

2021-09-29 19:47:12 字數 2089 閱讀 4163

前面介紹過 thrift 安裝和使用,介紹了thrift服務的發布和客戶端呼叫,可以檢視我之前的文章:

但是,之前介紹的都是單向的客戶端傳送訊息,服務端接收訊息。而客戶端卻得不到伺服器的響應。

那如果我們要實現雙向通訊(即:客戶端傳送請求,服務端處理返回,服務端傳送訊息,客戶端處理返回)的功能,該怎麼實現呢?

其實在不涉及語言平台的制約,webservice或是webapi 就可以實現這種客戶端發起請求,服務端的處理的單向流程。

然而,實際場景中,可能我們的某些業務需求,更需要服務端能夠響應請求並處理資料。下面我通過乙個demo案例,介紹下thrift 是如何實現雙向通訊的。

這裡不再贅述,戳這裡檢視我上篇文章的介紹:

編寫thrift指令碼,命名為student.thrift  如下:

service helloworldservice
生成service 的方法,之前的文章有介紹,這裡就不介紹了。

建立hellothrift.server 服務端工程,新增helloworldbidirectionserver類,helloworldbidirectionserver 實現了iface介面用於接收客戶端訊息,並有乙個客戶端傳輸層物件集合用於記錄所有已連線的客戶端。

public

class

helloworldbidirectionserver : helloworldbidirectionservice.iface

catch

(exception ex)

}public

static listtransportcollection = new list();

public

void sayhello(string

msg)

服務端接收到訊息:

", datetime.now, msg));

}public

void saytoclient(string

msg)

}catch

(exception ex)

}public

tprocesso***ctory getprocesso***ctory()

}public

class

helloworldbidirectionprocessor : tprocesso***ctory

helloworldbidirectionserver srv = new

helloworldbidirectionserver();

return

newglobal

::helloworldbidirectionservice.processor(srv);}}

首先建立hellothrift.client客戶端專案,新增接收服務端訊息的類helloworldbidirectionclient,裡面只有乙個實現iface介面的方法:

public

class

helloworldbidirectionclient

}

catch

(exception ex)

}public

void say(string

msg)

void

startlistern(tsocket tsocket)

public

void run(object

tsocket)

}catch

(exception ex)}}

class

helloworldbidirectionface : helloworldbidirectionservice.iface

收到服務端響應訊息

", datetime.now, msg));}}

實現客戶端,connectandlistern方法可以與服務端建立連線,並開啟客戶端埠監聽來自服務端的資訊。say方法可將訊息傳送至服務端。

測試效果如下:

1. 關於使用thrift 構建我們自己的rpc 的方法,這裡基本講完了。其他的方法本文就不再演示了,呼叫起來都是一樣。  

2. 後續會簡單討論一下thrift 框架的通訊原理。

thrift 實戰總結

return 實踐enum returncode struct valuegetresult service find something在實踐的時候,我發現它給valuegetresult 多生成了乙個變數 bool isset.value 所以thrift 並不是直接幫我們把查詢到的value返...

thrift入門教程 thrift資料集合

apache thrift 初學小講 二 乙個簡單示例 常用的有以下三種 1 buffered 使用經典的緩衝流socket 2 framed 非阻塞server必須使用這種 基於幀的方式的socket,每個幀都是按照4位元組的幀長加上幀的內容來組織,幀內容就是我們要收發的資料。讀的時候按長度預先將...

thrift開發問題總結

作為目前最流行的rpc框架,thrift不僅提供了通訊協議,同時提供了網路框架,解脫了程式設計師的生產力。thrift也是阿帕奇hadoop系列的rpc實現工具。本文主要聚焦在實現的thrift系統中,遇到的各種問題。但是thrift在隱藏一些底層細節的同時,也給應用層帶來了一些不確定性,這些不確定...