python 使用 thrift 教程

1、前言:  

  Thrift 是一種接口描述語言和二進制通訊協議。之前也沒接觸過,最近有個項目須要創建自動化測試,這個項目之間的微服務都是經過 Thrift 進行通訊的,而後寫自動化腳本以前研究了一下。python

  須要定義一個xxx.thrift的文件, 來生成各類語言的代碼,生成以後咱們的服務提供者和消費者,都須要把代碼引入,服務端把代碼實現,消費者直接使用API的存根,直接調用。apache

  和 http 相比,同屬於應用層,走 tcp 協議。Thrift 優點在於發送一樣的數據,request包 和 response包 要比 http 小不少,在總體性能上要優於 http 。json

 

2、使用方法

環境準備:windows

 

1.首先使用 thrift 以前須要定義一個 .thrift 格式的文件,好比 test.thrift服務器

service Transmit {
string sayMsg(1:string msg);
string invoke(1:i32 cmd 2:string token 3:string data)
}
View Code

而後運行命令:thrift-0.9.3.exe -gen py  test.thrift  生成 python 代碼socket

生成以下結構
tcp

 

 2.而後將生成的 python 代碼 和 文件,放到新建的 python 項目中。完成後先運行服務器代碼。ide

 服務端代碼 server.py:

import json
from test import Transmit
from test.ttypes import *
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
import socket


class TransmitHandler:
    def __init__(self):
        self.log = {}

    def sayMsg(self, msg):
        msg = json.loads(msg)
        print("sayMsg(" + msg + ")")
        return "say " + msg + " from " + socket.gethostbyname(socket.gethostname())

    def invoke(self,cmd,token,data):
        cmd = cmd
        token =token
        data = data
        if cmd ==1:
            return json.dumps({token:data})
        else:
            return 'cmd不匹配'

if __name__=="__main__":
    handler = TransmitHandler()
    processor = Transmit.Processor(handler)
    transport = TSocket.TServerSocket('127.0.0.1', 8000)
    tfactory = TTransport.TBufferedTransportFactory()
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()
    server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
    print("Starting python server...")
    server.serve()

 

客戶端代碼 client.py

import sys
import jsonfrom test import Transmit
from test.ttypes import *
from test.constants import *
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol


transport = TSocket.TSocket('127.0.0.1', 8000)
transport = TTransport.TBufferedTransport(transport)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = Transmit.Client(protocol)
# Connect!
transport.open()

cmd = 2
token = '1111-2222-3333-4444'
data = json.dumps({"name":"zhoujielun"})
msg = client.invoke(cmd,token,data)
print(msg)
transport.close()

# 執行結果:cmd不匹配
相關文章
相關標籤/搜索