前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Thrift入门实践

Thrift入门实践

原创
作者头像
Marky Lumin
发布2018-01-23 15:36:59
1.5K0
发布2018-01-23 15:36:59
举报
文章被收录于专栏:刘明的小酒馆刘明的小酒馆

简介

Thrift是由facebook研发,用于各服务之间RPC的一个跨语言通信框架。C/S架构

Thrift IDL

为了能够把不同的语言连接在一起,就必须要有一种“中间语言”,来关联客户端和服务端的两种不同语言。

这种规范语言就是IDL(Interface Description Language),接口定义语言。

具体的语法、定义参考下文,基本是C风格

生成代码

在编写好IDL之后,使用thrift的命令就可以生成对应语言的框架。

e.g IDL文件:HelloWorld.thrift

代码语言:txt
复制
namespace py thrift_test.hello

enum RequestType {
   SAY_HELLO,   //问好
   QUERY_TIME,  //询问时间
}

struct Request {
   1: required RequestType type;  // 请求的类型,必选
   2: required string name;       // 发起请求的人的名字,必选
   3: optional i32 age;           // 发起请求的人的年龄,可选
}

exception RequestException {
   1: required i32 code;
   2: optional string reason;
}

// 服务名
service HelloWordService {
   string doAction(1: Request request) throws (1:RequestException qe); // 可能抛出异常。
}

执行命令生成对应的代码框架。执行成功后将在同级目录下产生一个文件夹,内部构如下:

代码语言:txt
复制
gen-py
├── __init__.py
└── thrift_test
    ├── __init__.py
    └── hello
        ├── HelloWordService-remote
        ├── HelloWordService.py
        ├── __init__.py
        ├── constants.py
        └── ttypes.py

其中里包含了在IDL里定义好的各种数据类型对应封装的Python类,包含了所有定义的常量,则定义对应Service的完整描述,包括接口定义(),Client的调用桩等。

编写实现

对应语言的框架生成好之后,需要做的就是编写具体的实现了,以python为例,就是要实现对应里的方法,作为handler和其他各种组件组合,从而生成服务端代码。

以下是具体的例子

编写

代码语言:txt
复制
# -*- coding: utf-8 -*-

import datetime

from thrift_test.hello import ttypes
from thrift_test.hello import HelloWordService
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer

__HOST = 'localhost'
__PORT = 9577


class HelloWordHandler(object):
    def doAction(self, request):
        ret_msg = ''
        if request.type == ttypes.RequestType.SAY_HELLO:
            ret_msg = 'Hello %s, we received your msg' % request.name
        elif request.type == ttypes.RequestType.QUERY_TIME:
            ret_msg = "current_time: " + str(datetime.datetime.now())
        print 'get request: %s' % request
        return ret_msg


handler = HelloWordHandler()
processor = HelloWordService.Processor(handler)
transport = TSocket.TServerSocket(__HOST, __PORT)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()

server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)

print "starting server..."

server.serve()

print "done"

编写

代码语言:txt
复制
# -*- coding: utf-8 -*-

import datetime

from thrift_test.hello import ttypes
from thrift_test.hello import HelloWordService
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer

__HOST = 'localhost'
__PORT = 9577


class HelloWordHandler(object):
    def doAction(self, request):
        ret_msg = ''
        if request.type == ttypes.RequestType.SAY_HELLO:
            ret_msg = 'Hello %s, we received your msg' % request.name
        elif request.type == ttypes.RequestType.QUERY_TIME:
            print "type query"
            ret_msg = "current_time: " + str(datetime.datetime.now())
        print 'get request: %s' % request
        return ret_msg


handler = HelloWordHandler()
processor = HelloWordService.Processor(handler)
transport = TSocket.TServerSocket(__HOST, __PORT)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()

server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)

print "starting server..."

server.serve()

print "done"

liuminghao@n8-160-227:~/repos/thrift_test/demo$ cat client.py 
# -*- coding:utf-8
from thrift_test.hello import HelloWordService
from thrift_test.hello.ttypes import Request,RequestType
from thrift import Thrift
from thrift.transport import TSocket, TTransport
from thrift.protocol import TBinaryProtocol

try:
    transport = TSocket.TSocket('localhost',9577)
    transport = TTransport.TBufferedTransport(transport)
    protocol = TBinaryProtocol.TBinaryProtocol(transport)
    client = HelloWordService.Client(protocol)
    transport.open()

    req = Request(RequestType.SAY_HELLO,"mark",12)

    print "request 1"

    msg = client.doAction(req)

    print "server msg 1: " + msg 

    req = Request(RequestType.QUERY_TIME,"marky")

    print "request 2"

    msg = client.doAction(req)

    print "server msg 2: " + msg 

    transport.close()

except Thrift.TException as e:
    print "exception: " + e.message 

先运行再执行,结果如下:

代码语言:txt
复制
request 1
server msg 1: Hello mark, we received your msg
request 2
server msg 2: current_time: 2018-01-15 15:14:40.800472

如上即为一个ThriftRPC的基本使用示范。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 简介
  • Thrift IDL
  • 生成代码
  • 编写实现
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档