1.proto
syntax = "proto3";option go_package = ".;proto";service Greeter {rpc SayHello (HelloRequest) returns (HelloReply);}message HelloRequest {string name = 1;}message HelloReply {string message = 1;}
2.server
import loggingfrom concurrent import futuresimport grpcfrom grpc_hello.proto import helloworld_pb2, helloworld_pb2_grpcclass Greeter(helloworld_pb2_grpc.GreeterServicer): def SayHello(self, request, context): return helloworld_pb2.HelloReply(message=f"你好,{request.name},id:{request.id}") class LogInterceptor(grpc.ServerInterceptor): def intercept_service(self, continuation, handler_call_details): print("请求开始") print(type(handler_call_details)) rsp = continuation(handler_call_details) print("请求结束") return rsp def serve(): interceptor = LogInterceptor() server = grpc.server(futures.ThreadPoolExecutor(max_workers=10), interceptors=(interceptor,)) helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) server.add_insecure_port('[::]:50051') server.start() server.wait_for_termination() if __name__ == "__main__": logging.basicConfig() serve()
3.client
import grpcfrom grpc_hello.proto import helloworld_pb2_grpc, helloworld_pb2from datetime import datetime# 1. 这个问题能改吗?# 2. 其他语言有没有这个问题 其他语言 go语言 python不服气class DefaultInterceptor(grpc.UnaryUnaryClientInterceptor): def intercept_unary_unary(self, continuation, client_call_details, request): start = datetime.now() rsp = continuation(client_call_details, request) print((datetime.now() - start).microseconds / 1000) return rsp if __name__ == "__main__": default_interceptor = DefaultInterceptor() with grpc.insecure_channel("localhost:50051") as channel: intercept_channel = grpc.intercept_channel(channel, default_interceptor) stub = helloworld_pb2_grpc.GreeterStub(intercept_channel) hello_request = helloworld_pb2.HelloRequest() hello_request.name = "bobby" rsp: helloworld_pb2.HelloReply = stub.SayHello(hello_request) print(rsp.message)