gRPC

Google이 개발한 HTTP/2 + Protocol Buffers 기반 고성능 RPC(Remote Procedure Call) 프레임워크입니다.

핵심 특징

.proto 파일 정의

syntax = "proto3";

package post;

service PostService {
    rpc GetPost (PostRequest)          returns (PostResponse);          // Unary
    rpc ListPosts (Empty)              returns (stream PostResponse);  // Server Streaming
    rpc UploadPosts (stream PostRequest) returns (PostResponse);      // Client Streaming
    rpc Chat (stream ChatMessage)      returns (stream ChatMessage);  // Bidirectional
}

message PostRequest  { int64 id = 1; }
message PostResponse { int64 id = 1; string title = 2; string content = 3; }
message Empty {}
message ChatMessage  { string text = 1; }

4가지 통신 패턴

1. Unary (단순 요청-응답)
   Client ──req──→ Server ──res──→ Client

2. Server Streaming (서버가 스트림 응답)
   Client ──req──→ Server ──stream──→──→──→ Client

3. Client Streaming (클라이언트가 스트림 전송)
   Client ──stream──→──→──→ Server ──res──→ Client

4. Bidirectional Streaming (양방향 스트림)
   Client ←──stream──→ Server

Java 구현 예시

// 서버 측 구현
@GrpcService
public class PostServiceImpl extends PostServiceGrpc.PostServiceImplBase {

    @Override
    public void getPost(PostRequest req, StreamObserver<PostResponse> responseObserver) {
        PostResponse res = PostResponse.newBuilder()
            .setId(req.getId())
            .setTitle("제목")
            .build();
        responseObserver.onNext(res);
        responseObserver.onCompleted();
    }
}

// 클라이언트 측 호출
ManagedChannel channel = ManagedChannelBuilder
    .forAddress("localhost", 9090)
    .usePlaintext()
    .build();

PostServiceGrpc.PostServiceBlockingStub stub = PostServiceGrpc.newBlockingStub(channel);
PostResponse res = stub.getPost(PostRequest.newBuilder().setId(1).build());

REST vs gRPC

RESTgRPC
프로토콜HTTP/1.1HTTP/2
직렬화JSON (텍스트)Protocol Buffers (바이너리)
인터페이스 정의OpenAPI (선택).proto (필수)
스트리밍SSE / WebSocket 별도기본 제공
브라우저 지원O 직접 지원X grpc-web 필요
성능상대적으로 낮음높음 (바이너리, HTTP/2)
적합한 상황외부 API, 브라우저 통신내부 마이크로서비스 통신

언제 gRPC를 쓰나

핵심 정리

→ REST | HTTP | TCP

CSLOG에서 보기