protobuf python grpc簡單使用

2021-10-11 22:54:45 字數 2684 閱讀 7847

python install grpcio

pip install grpcio-tools

// [python quickstart]

// python -m grpc_tools.protoc --python_out=. --grpc_python_out=. -i. helloworld.proto

// helloworld.proto

syntax =

"proto3"

;service greeter

rpc sayhelloagain(hellorequest) returns (helloreply)

}message hellorequest

message helloreply

python -m grpc_tools.protoc --python_out=./ --grpc_python_out=./ -i./ hello.proto
生成檔案如圖所示:

# 實現 proto 檔案中定義的 greeterservicer

class

greeter

(hello_pb2_grpc.greeterservicer)

:# 實現 proto 檔案中定義的 rpc 呼叫

defsayhello

(self, request, context)

:return hello_pb2.helloreply(message =

'hello '

.format

(msg = request.name)

)def

sayhelloagain

(self, request, context)

:return hello_pb2.helloreply(message=

'hello '

.format

(msg = request.name)

)def

serve()

:# 啟動 rpc 服務

server = grpc.server(futures.threadpoolexecutor(max_workers=10)

) hello_pb2_grpc.add_greeterservicer_to_server(greeter(

), server)

server.add_insecure_port(

'[::]:50051'

) server.start(

)try

:while

true

: time.sleep(60*

60*24)

# one day in seconds

except keyboardinterrupt:

server.stop(0)

if __name__ ==

'__main__'

: serve(

)client:

import grpc

import hello_pb2

import hello_pb2_grpc

defrun()

:# 連線 rpc 伺服器

channel = grpc.insecure_channel(

'localhost:50051'

)# 呼叫 rpc 服務

stub = hello_pb2_grpc.greeterstub(channel)

response = stub.sayhello(hello_pb2.hellorequest(name=

'czl'))

print

("greeter client received: "

+ response.message)

response = stub.sayhelloagain(hello_pb2.hellorequest(name=

'daydaygo'))

print

("greeter client received: "

+ response.message)

if __name__ ==

'__main__'

: run(

)

執行server:

python hello_grpc_server.py
另起乙個命令列視窗,運營client:

python test_grpc.py
執行結果:

至此,python版本 grpc demo成功執行

SpringBoot Swagger簡單使用

io.springfox springfox swagger2 2.9.2 io.springfox springfox swagger ui 2.9.2 import org.springframework.context.annotation.bean import org.springfram...

UICollectionView的簡單使用

所屬controller要遵循三個協議 uicollectionviewdatasource,uicollectionviewdelegate,uicollectionviewdelegateflowlayout uicollectionviewflowlayout flowlayout uicol...

BGAQRCode Android的簡單使用

compile com.google.zxing core 3.2.1 xmlns android 這句是使用選擇器框架時用到的 xmlns tools package com.huaqiang.zxingdemo 選擇框架用到 android name android.permission.cam...