개요

  • 구글이 개발한 오픈 소스 원격 프로시저 호출 시스템
  • 마이크로서비스 아키텍처
  • HTTP/2 프로토콜 사용
  • JSON에 비해 작음. 이진 데이터 사용
  • 일반적으로 HTTP/JSON 요청보다 빠름

설치하기

$ pip install grpcio
$ pip install grpcio-tools
$ git clone https://github.com/grpc/grpc # 예제 필요시

helloworld.proto

syntax = "proto3";
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";
package helloworld;

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}

helloworld_client.py

from __future__ import print_function
import logging
import grpc
import helloworld_pb2
import helloworld_pb2_grpc

def run():
    with grpc.insecure_channel('localhost:50051') as channel:
        stub = helloworld_pb2_grpc.GreeterStub(channel)
        response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'))
    print("Greeter client received: " + response.message)

if __name__ == '__main__':
    logging.basicConfig()
    run()

helloworld_server.py

from concurrent import futures
import logging
import grpc
import helloworld_pb2
import helloworld_pb2_grpc

class Greeter(helloworld_pb2_grpc.GreeterServicer):
    def SayHello(self, request, context):
        return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)

def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    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()

.proto 컴파일

$ python -m grpc_tools.protoc -I../../protos --python_out=. --grpc_python_out=. ../../protos/helloworld.proto

실행하기

$ nohup python helloworld_server.py &
$ python helloworld_client.py

또다른 .proto 파일의 예

syntax = "proto3";

package vectors;

message Point {
    double x = 1;
    double y = 2;
    double z = 3;
}

message Vector {
    Point start = 1;
    Point end = 2;
}

message Vectors {
    repeated Vector vectors = 1;
}

참고자료