- 구글에서 개발한 통신 프레임워크
- 원격에 있는 애플리케이션의 메소드를 로컬 메소드처럼 직접 호출할 수 있다.
- 클라이언트에서 서버로 바로 요청을 보낼 수 있다.
- 분산 애플리케이션을 보다 쉽게 만들 수 있다.
서비스 인터페이스(.proto)
gRPC 사용시 가장 먼저 작성해야 할 코드
메소드 종류, 파라미터, 메시지 형식 등을 작성
gRPC Stub
클라이언트 측 코드
gRPC Server
서버 측 코드
ProductInfo.proto를 실행시키면 서버 스켈레톤과 클라이언트 스텁(총 2개)가 생성된다.
생성된 2개의 코드를 import하여 서버, 클라이언트 실행 코드를 작성한다.
서버측 코드를 실행시킨다.
클라이언트 측 코드를 실행시킨다.
간단하게 인사를 출력하는 예제를 따라 작성했다.
1. gRPC를 설치해준다. 다음 명령어를 차례로 터미널에 입력한다.
python -m pip install --upgrade pip
python -m pip install grpcio
python -m pip install grpcio-tools
syntax = "proto3";
package ecommerce;
service ProductInfo {
rpc sayHello (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. ./hello.proto
나는 파일명이 hello.proto였고,
from concurrent import futures
import logging
import grpc
import hello_pb2
import hello_pb2_grpc
class HelloInfoServicer(hello_pb2_grpc.HelloInfoServicer):
def sayHello(self, request, context):
return hello_pb2.HelloReply(message='Hello, %s!' % request.name)
def serve():
port = '50052'
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
hello_pb2_grpc.add_HelloInfoServicer_to_server(HelloInfoServicer(), server)
server.add_insecure_port('[::]:' + port)
server.start()
print("Server started, listening on " + port)
server.wait_for_termination()
if __name__ == '__main__':
logging.basicConfig()
serve()
from __future__ import print_function
import logging
import grpc
import product_pb2
import product_pb2_grpc
def run():
print("Will try to greet world ...")
with grpc.insecure_channel('localhost:50052') as channel:
stub = product_pb2_grpc.ProductInfoStub(channel)
response = stub.sayHello(product_pb2.HelloRequest(name='azamman'))
print("Greeter client received: " + response.message)
if __name__ == '__main__':
logging.basicConfig()
run()
python hello_server.py
python hello_client.py
좋은 글 감사합니다. 자주 올게요 :)