python使用thrift簡(jiǎn)單方法

第一步

在有docker的服務(wù)器操作,如果沒(méi)有 可以找一臺(tái)閑置的機(jī)器安裝docker

yum install docker -y

然后啟動(dòng)docker

systemctl start docker


第二步 下載thrift鏡像

docker pull thrift


第三步

準(zhǔn)備thrift文件

cat WebMonitor.thrift? 定義了一個(gè)類的名字,以及定義了一個(gè)方法輸出的值是string,

輸入的值1號(hào)位置是accesstime的string,2號(hào)位置是url的string

service WebMonitorService {

? ? string? webAccess(1:string accesstime,2:string url)

}

在thrift文件所在位置運(yùn)行docker

docker run -v "$PWD:/data" thrift thrift -o /data? --gen py /data/WebMonitor.thrift

運(yùn)行后在當(dāng)前目錄生成一個(gè)文件夾,叫g(shù)en-py,里面有個(gè)文件夾叫WebMonitor對(duì)應(yīng)的是thrift文件的名字

在WebMonitor文件夾里有個(gè)py文件叫WebMonitorService.py的文件

在之后編寫的server.py以及client.py需要修改相應(yīng)的配置

在gen-py中編寫server.py,其中的WebMonitorService以及webAccess以及webAccess方法里的參數(shù)需要跟thrift文件中定義的一一對(duì)應(yīng)

# -*- coding: UTF-8 -*-

"""

# furyamber

"""

from WebMonitor import WebMonitorService

from thrift.transport import TSocket

from thrift.transport import TTransport

from thrift.protocol import TBinaryProtocol

from thrift.server import TServer

import datetime

import sys

reload(sys)

import requests

import subprocess

sys.setdefaultencoding('utf-8')

class WebMonitorServiceHandler:

? ? """

? ? # WebMonitorServiceHandler是中定義的方法用于實(shí)現(xiàn)在thrift文件中定義的接口

? ? """

? ? def __init__(self):

? ? ? ? self.log = {}

? ? def webAccess(self,accesstime,url):

? ? ? ? try:

? ? ? ? ? ? r = requests.get(url,timeout=1)

? ? ? ? except Exception,e:

? ? ? ? ? ? response_time=0

? ? ? ? else:

? ? ? ? ? ? response_time=int(r.elapsed.microseconds)

? ? ? ? print response_time

? ? ? ? return str(response_time)

# 實(shí)例化Handler

handler = WebMonitorServiceHandler()

# 根據(jù)handler創(chuàng)建一個(gè)processor

processor = WebMonitorService.Processor(handler)

# 指定端口啟動(dòng)transport

transport = TSocket.TServerSocket(port=9090)

# 創(chuàng)建tfactory, pfactory

tfactory = TTransport.TBufferedTransportFactory()?

pfactory = TBinaryProtocol.TBinaryProtocolFactory()?

# 創(chuàng)建Server

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

print 'Starting the server...'

# 啟動(dòng)server

server.serve()?

print 'done.'

⑥編寫client.py文件

#!/usr/bin/env python

#-*- coding:utf-8 -*-

__author__ = "furyamber@qq.com"

__created__ = "2018-12-05 14:14:37"

from WebMonitor import WebMonitorService

from thrift import Thrift

from thrift.transport import TSocket

from thrift.transport import TTransport

from thrift.protocol import TBinaryProtocol

import datetime

import time

from apscheduler.schedulers.background import BackgroundScheduler

def timedTask():

? ? now = int(time.time())

? ? now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

? ? try:

? ? ? ? # 連接Socket,根據(jù)實(shí)際情況修改為server所在的地址

? ? ? ? transport = TSocket.TSocket('192.168.1.30', 9090)

? ? ? ? # 獲取Transport

? ? ? ? transport = TTransport.TBufferedTransport(transport)

? ? ? ? # 獲取TBinaryProtocol

? ? ? ? protocol = TBinaryProtocol.TBinaryProtocol(transport)

? ? ? ? # 創(chuàng)建一個(gè)Client

? ? ? ? client = WebMonitorService.Client(protocol)

? ? ? ? # 連接通道transport

? ? ? ? transport.open()

? ? ? ? # 調(diào)用某個(gè)沒(méi)有返回值的函數(shù)

? ? ? ? print client.webAccess(now,"http://www.baidu.com")

? ? ? ? # 調(diào)用某個(gè)有返回值的函數(shù)

? ? ? ? # 關(guān)閉通道transport

? ? ? ? transport.close()

? ? except Thrift.TException, tx:

? ? ? ? print '%s' % (tx.message)

if __name__ == '__main__':

? ? # 創(chuàng)建后臺(tái)執(zhí)行的 schedulers

? ? scheduler = BackgroundScheduler()?

? ? # 添加調(diào)度任務(wù)

? ? # 調(diào)度方法為 timedTask,觸發(fā)器選擇 interval(間隔性),間隔時(shí)長(zhǎng)為 2 秒

? ? scheduler.add_job(timedTask, 'interval', seconds=1)

? ? # 啟動(dòng)調(diào)度任務(wù)

? ? scheduler.start()

? ? while True:

? ? ? ? print(time.time())

? ? ? ? time.sleep(5)

第七步

把需要gen-py拷貝到需要的服務(wù)器或者客戶機(jī)上,分別安裝需要的python模塊,可以把gen-py改成你想要的名字

服務(wù)端運(yùn)行要安裝thrift木塊以及requests模塊

然后運(yùn)行python server.py啟動(dòng)服務(wù)端

客戶端要安裝thrift以及APScheduler模塊

運(yùn)行python client.py啟動(dòng)客戶端

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容