gRPC, Protocol buffers

dev_314·2023년 5월 23일
0

참고
Introduction to gRPC

gRPC

gRPC는 protocol buffers을 두 가지 용도로 사용한다.

  1. Interface Definition Language (IDL)
  2. underlying message interchange format.

gRPC에서는, client app이 직접적으로 다른 머신에서 작동 중인 server application의 메서드를 마치 'local object'처럼 호출할 수 있다. 이로써 분산 app, service를 더 쉽게 만들 수 있다.

다른 RPC 시스템 처럼, gRPC도 '서비스를 정의하고', '파라미터와 리턴 타입을 가지고 원격으로 호출할 수 있는 메서드를 식별하자'는 아이디어를 기본으로 한다.

서버는 클라이언트의 요청을 처리하기 위해 이를 위한 인터페이스를 구현하고, gRPC 서버를 가동시킨다.

클라이언트는 stub를 가진다.

stub: 서버의 메서드와 동일한 메서드를 제공하는 것

gRPC 클라이언트와 서버는 다양한 환경에서 작동할 수 있고, gRPC를 지원하는 어떠한 언어로도 작성될 수 있다.

Protocol Buffers

기본적으로 gRPC는 Protocol Buffers를 사용한다.

Protocol Buffers
	- Google’s mature open source mechanism for serializing structured data 

protocol buffers를 사용하려면 우선, proto file로 serialize하고 싶은 데이터의 구조를 정의해야 한다.

proto file
	- 단순히 '.proto' 확장자의 text file을 의미함

Protocol buffer data는 message라는 단위로 조직된다.

message
	- a small logical record of information
    - containing a series of name-value pairs called `fields`.
    

message는 다음과 같은 구조를 가진다.

// message는 'type key = value' 형태의 field를 가진다
message Person {
  string name = 1; 
  int32 id = 2;
  bool has_ponycopter = 3;
}

message를 통해 데이터 구조를 한 다음, protocol buffer 컴파일러인 protoc을 사용해서 data access classes를 만든다.

원하는 언어로 만들면 된다.

data access class는 각 필드에 접근할 수 있는 accessors를 제공한다.

like name() and set_name(), as well as methods to serialize/parse the whole structure to/from raw bytes. So, for instance, if your chosen language is C++, running the compiler on the example above will generate a class called Person. You can then use this class in your application to populate, serialize, and retrieve Person protocol buffer messages.

You define gRPC services in ordinary proto files, with RPC method parameters and return types specified as protocol buffer messages:

실습

참고
Basics tutorial

  1. .proto 확장자 파일을 만들어서 gRPC 통신을 위한 인터페이스를 정의한다. (마치 gqlgen에서 schema.graphql을 정의하는 것과 비슷)

  2. 다음 명령을 통해 protoc를 가지고 컴파일 (파일 generate)

protoc --go_out=. --go_opt=paths=source_relative \
    --go-grpc_out=. --go-grpc_opt=paths=source_relative \
    helloworld/helloworld.proto
profile
블로그 이전했습니다 https://dev314.tistory.com/

0개의 댓글