python使用grpc

编程入门 行业动态 更新时间:2024-10-27 21:18:42

<a href=https://www.elefans.com/category/jswz/34/1770869.html style=python使用grpc"/>

python使用grpc

proto

首先编写proto,也可以根据对象生成proto

syntax = "proto3";package text;service TextSender{rpc Send(Text) returns (SendResponse);rpc Resend(Text) returns (SendResponse);
}message Text{string text = 1;
}message SendResponse{bool sucess = 1;string para = 2;
}

生成py文件

py -m grpc_tools.protoc -I/ --python_out=. --pyi_out=. --grpc_python_out=. first.proto

编写

根据proto生成的文件编写函数

# server.py
from concurrent import futures
import loggingimport grpc
import first_pb2
import first_pb2_grpcclass Sender(first_pb2_grpc.TextSenderServicer):def Send(self, request, context):return first_pb2.SendResponse(sucess=True, para="first")def Resend(self, request, context):return first_pb2.SendResponse(sucess=True, para="second")def serve():port = "50051"server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))first_pb2_grpc.add_TextSenderServicer_to_server(Sender(), server)server.add_insecure_port("[::]:" + port)server.start()print("Server started, listening on " + port)server.wait_for_termination()if __name__ == "__main__":logging.basicConfig()serve()
# client.py
from __future__ import print_functionimport loggingimport grpc
import first_pb2
import first_pb2_grpcdef run():print("Will try to greet world ...")with grpc.insecure_channel("39.105.170.229:50051") as channel:stub = first_pb2_grpc.TextSenderStub(channel)response = stub.Send(first_pb2.Text(text="you"))print(f"Greeter client received: {response.sucess} for the {response.para} times")response = stub.Resend(first_pb2.Text(text='you'))print(f"Greeter client received: {response.sucess} for the {response.para} times")if __name__ == "__main__":logging.basicConfig()run()

启动

注册到nacos

import nacos
import timeSERVER_ADDRESSES = ":8848"  # Nacos服务器地址
NAMESPACE = "d344b685-a423-4770-a6e4-da81245b5dc9"  # Nacos的命名空间ID# 获取Nacos客户端
client = nacos.NacosClient(SERVER_ADDRESSES, namespace=NAMESPACE, username="nacos", password="nacos")# 服务注册
client.add_naming_instance("grpc-demo", "1.2.3.4", port=50051)while True:try:client.send_heartbeat("grpc-demo", "1.2.3.4", port=50051)time.sleep(30)except Exception as e:print(f"Error: {e}")time.sleep(5)  # 在尝试重新发送心跳之前稍作延迟

更多推荐

python使用grpc

本文发布于:2023-12-06 17:21:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1668274.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:python   grpc

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!