1.proto

  1. syntax = "proto3";
  2. option go_package = ".;proto";
  3. service Greeter {
  4. rpc SayHello (HelloRequest) returns (HelloReply);
  5. }
  6. message HelloRequest {
  7. string name = 1;
  8. }
  9. message HelloReply {
  10. string message = 1;
  11. }

2.server

  1. import logging
  2. from concurrent import futures
  3. import grpc
  4. from grpc_hello.proto import helloworld_pb2, helloworld_pb2_grpc
  5. class Greeter(helloworld_pb2_grpc.GreeterServicer):
  6. def SayHello(self, request, context):
  7. return helloworld_pb2.HelloReply(message=f"你好,{request.name},id:{request.id}")
  8. class LogInterceptor(grpc.ServerInterceptor):
  9. def intercept_service(self, continuation, handler_call_details):
  10. print("请求开始")
  11. print(type(handler_call_details))
  12. rsp = continuation(handler_call_details)
  13. print("请求结束")
  14. return rsp
  15. def serve():
  16. interceptor = LogInterceptor()
  17. server = grpc.server(futures.ThreadPoolExecutor(max_workers=10), interceptors=(interceptor,))
  18. helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
  19. server.add_insecure_port('[::]:50051')
  20. server.start()
  21. server.wait_for_termination()
  22. if __name__ == "__main__":
  23. logging.basicConfig()
  24. serve()

3.client

  1. import grpc
  2. from grpc_hello.proto import helloworld_pb2_grpc, helloworld_pb2
  3. from datetime import datetime
  4. # 1. 这个问题能改吗?
  5. # 2. 其他语言有没有这个问题 其他语言 go语言 python不服气
  6. class DefaultInterceptor(grpc.UnaryUnaryClientInterceptor):
  7. def intercept_unary_unary(self, continuation, client_call_details, request):
  8. start = datetime.now()
  9. rsp = continuation(client_call_details, request)
  10. print((datetime.now() - start).microseconds / 1000)
  11. return rsp
  12. if __name__ == "__main__":
  13. default_interceptor = DefaultInterceptor()
  14. with grpc.insecure_channel("localhost:50051") as channel:
  15. intercept_channel = grpc.intercept_channel(channel, default_interceptor)
  16. stub = helloworld_pb2_grpc.GreeterStub(intercept_channel)
  17. hello_request = helloworld_pb2.HelloRequest()
  18. hello_request.name = "bobby"
  19. rsp: helloworld_pb2.HelloReply = stub.SayHello(hello_request)
  20. print(rsp.message)