Apache Thrift 序列化和RPC框架

为什么需要Thrift?

Imagine the situation, where you have lots of applications written in different languages. In most popular scenario these are internal applications that perform various tasks and were written by separate development teams. How you enable those applications to talk to each other? Sure, you may add some REST APIs. But in many cases – especially when you transfer binary data – this solution doesn’t provide acceptable performance or maintainability.

Thrift的定义:

Apache Thrift is an open source cross language serialization and remote procedure call (RPC) framework. With support for over 20 programming languages, Apache Thrift can play an important role in many distributed application solutions. As a serialization platform Apache Thrift enables efficient cross language storage and retrieval of a wide range of data structures. As an RPC framework, Apache Thrift enables rapid development of complete cross language services with little more than a few lines of code.

IDL的定义:

An interface description language or interface definition language(IDL), is a specification language used to describe a software component's application programming interface(API). IDLs describe an interface in a language-independent way, enabling communication between software components that do not share one language. For example, between those written in C++and those written in Java.  IDLs are commonly used in remote procedure call software. In these cases the machines at either end of the link may be using different operating systems and computer languages. IDLs offer a bridge between the two different systems.

Thrift的原理:

First, let's have a look at Apache Thrift from developer's point of view. Main concept of this framework is a service, which resembles classes that you know from object-oriented programming languages. Every service has methods, which are defined in a familiar way, using various data typesimplemented in Apache Thrift. The data types are mapped to their native counterparts in every language, so in case of simple ones, like int, they are mapped to integer in every language, but more complex, like set becomes, for example, array in PHP or HashSet in Java. The services are defined in so called Apache Thrift document, in which you use Interface Description Language (IDL) syntax (if you want to learn details about this syntax head to theofficial documentation).

Then, from this file – using Apache Thrift compiler – you generate server and client stubs. These pieces of code are calling Apache Thrift library and you use them to implement server and clients – it's like filling the blank spaces with the relevant code (i.e. creating objects, calling methods, etc.) to allow cross-communication between your applications. The code that you generate for both client and server is embedded in your application. It is illustrated in the following image:


Figure 1. Source: "Learning Apache Thrift", Krzysztof Rakowski, Packt Publishing, December 2015

Before we get to the example code, which will explain this concept, let's have a quick look at the architecture of Apache Thrift. It is illustrated with the following simple image:


Figure 2. Source: "Learning Apache Thrift", Krzysztof Rakowski, Packt Publishing, December 2015

Transport provides a way to read and write payload from and to the medium you use (most commonly – a network or a socket). Protocol is mostly independent of the transport used and is responsible for encoding and decoding the data, so it can be transmitted. Most popular protocols are: binary, compact (Thrift's own) or JSON. Processor is generated automatically by the Apache Thrift compiler. These three layers are combined in server and client codes. When you want two applications to communicate with each other, you need to use the same set of transport and protocol for encoding and decoding the information.

Thrift例子:

1. Describing services with Apache Thrift IDL

Service interfaces are the basis for communications between clients and servers in Apache Thrift. Apache Thrift services are defined using an Interface Definition Language

(IDL) similar to C in its notation. IDL code is saved in plain text files with a “.thrift” extension.

/************** hello.thrift ******************/

service HelloSvc {                           #A

string hello_func()                  #B

}

/************** hello.thrift ******************/

This IDL file declares a single service interface called HelloSvc #A. HelloSvc has onefunction, hello_func(), which accepts no parameters and returns a string #B. To use this

interface in an RPC application we can compile it with the Apache Thrift IDL Compiler.The IDLCompiler will generate stub code for both clients using the interface and

servers implementingthe interface. In this example we will begin by using the compiler to generate Python stubs forthe HelloSvc.

/**************************************/

thrift --gen py hello.thrift

/*************************************/

2. Building a Python Server

/****************************** hello_server.py **************************/

import sys

sys.path.append("gen-py")

from hello import HelloSvc

from thrift.transport import TSocket

from thrift.transport import TTransport

from thrift.protocol import TBinaryProtocol

from thrift.server import TServer

class HelloHandler:

def hello_func(self):

print("[Server] Handling client request")

return "Hello from the python server"

handler = HelloHandler()

proc = HelloSvc.Processor(handler)

trans_ep = TSocket.TServerSocket(port=9095)

trans_fac = TTransport.TBufferedTransportFactory()

proto_fac = TBinaryProtocol.TBinaryProtocolFactory()

server = TServer.TSimpleServer(proc, trans_ep, trans_fac, proto_fac)

server.serve()

/****************************** hello_server.py **************************/

open service:

/************************************/

python hello_server.py

/************************************/

3.Building a Python Client

/*********************************** hello_client.py *********************/

import sys

sys.path.append("gen-py")

from hello import HelloSvc

from thrift.transport import TSocket

from thrift.transport import TTransport

from thrift.protocol import TBinaryProtocol

trans_ep = TSocket.TSocket("localhost", 9095)

trans_buf = TTransport.TBufferedTransport(trans_ep)

proto = TBinaryProtocol.TBinaryProtocol(trans_buf)

client = HelloSvc.Client(proto)

trans_ep.open()

msg = client.hello_func()

print("[Client] received: %s" % msg)

/*********************************** hello_client.py *********************/

open client:

/*********************************/

python hello_client.py

/*********************************/

4. Building a Java Client

As a final example let’s put together a Java client for our service. Our first step is to generate

Java stubs for the service.

/****************************************/

thrift --gen java hello.thrift

/****************************************/


/*************************** HelloClient.java *********************/

import org.apache.thrift.protocol.TBinaryProtocol;

import org.apache.thrift.transport.TSocket;

import org.apache.thrift.TException;

public class HelloClient {

public static void main(String[] args) throws TException {

TSocket trans_ep = new TSocket("localhost", 9095);

TBinaryProtocol protocol = new TBinaryProtocol(trans_ep);

HelloSvc.Client client = new HelloSvc.Client(protocol);

trans_ep.open();

String str = client.hello_func();

System.out.println("[Client] received: " + str);

}

}

/*************************** HelloClient.java *********************/

complie and open client:

/******************************************************************/

javac -cp /usr/local/lib/libthrift-1.0.0.jar: /usr/local/lib/slf4j-api-1.7.2.jar: /usr/local/lib/slf4j-nop-1.7.2.jar HelloClient.java gen-java/HelloSvc.java

java -cp /usr/local/lib/libthrift-1.0.0.jar:/usr/local/lib/slf4j-api-1.7.2.jar:/usr/local/lib/slf4j-nop-1.7.2.jar:./gen-java:.   HelloClient

/******************************************************************/

参考文献:

1.http://www.thrift.pl/

2.http://thrift-tutorial.readthedocs.io/en/latest/intro.html

3.《THE PROGRAMMER'S GUIDE TO Apache Thrift》第一章

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,456评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,370评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,337评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,583评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,596评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,572评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,936评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,595评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,850评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,601评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,685评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,371评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,951评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,934评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,167评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,636评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,411评论 2 342

推荐阅读更多精彩内容