IT/CS

[CS] gRPC(Google Remote Procedure Call) 란?

어린이개발자 2025. 6. 19. 19:21

말로만 듣던 gRPC 에 대해 이해 및 정리를 하고 싶어서 글을 쓰게 되었다.

 

1. 개념

- 네트워크를 통한 함수 호출을 마치 로컬 함수처럼 수행할 수 있도록 해주는 RPC 프레임워크

- HTTP/2 프로토콜을 기반으로 통신

- 데이터 직렬화에는 Protocol Buffers (protobuf) 사용

 

2. 사용 목적

- 마이크로서비스 아키텍처에서 서비스 간 통신

- 다양한 언어 간 통신 지원 (ex. Java <-> Python <-> Go 등)

- 빠르고 경량화된 통신이 필요한 시스템

- 모바일, IoT, 클라우드 네이티브 환경에서의 고성능 API 구현

- 프로토콜 정의 파일 (.proto) 을 기반으로 자동으로 타입 안전한 코드 생성

- 클라이언트 <-> 서버 간 실시간 양방향 통신 가능

 

3. 단점

- 브라우저에서 직접 호출하기 어렵고, gRPC-Web 을 따로 구성해야 함

- .proto 파일, 코드 생성 등의 설정이 REST 보다 복잡할 수 있음

- 바이너리 프로토콜 (Protocol Buffers) 사용으로 디버깅이 REST 보다 어려움  

 

4. 샘플 코드

- 필요 패키지 설치

pip install grpcio grpcio-tools

 

- .proto 파일 작성

// hello.proto
syntax = "proto3";

service HelloService {
    rpc SayHello (HelloRequest) returns (HelloResponse);
}

message HelloRequest {
    string name = 1;
}

message HelloResponse {
    string message = 1;
}

 

- 메시지 클래스 (hello_pb2.py 파일) & gRPC 서비스 stub (hello_pb2_grpc.py 파일) 생성

python -m grpc_tools.protoc -I. --python_out=. -grpc_python_out=. hello.proto

 

- gRPC 서버 (server.py 파일) 구현 및 실행

from concurrent import futures
import grpc
import hello_pb2
import hello_pb2_grpc

class HelloService(hello_pb2_grpc.HelloServiceServicer):
    def SayHello(self, request, context):
        return hello_pb2.HelloResponse(message=f"안녕하세요, {request.name}님!")
    
def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    hello_pb2_grpc.add_HelloServiceServicer_to_server(HelloService(), server)
    server.add_insecure_port('[::]:50051')
    server.start()
    print("gRPC 서버 실행 중 (포트 50051)...")
    server.wait_for_termination()
    
if __name__ == '__main__':
    serve()
python server.py

 

- 클라이언트 (client.py) 구현 및 실행

import grpc
import hello_pb2
import hello_pb2_grpc

channel = grpc.insecure_channel('localhost:50051')
stub = hello_pb2_grpc.HelloServiceStub(channel)

response = stub.SayHello(hello_pb2.HelloRequest(name="김외솔"))
print(response.message)
python client.py
# 출력: 안녕하세요, 김외솔님!