찾다
백엔드 개발GolanggRPC: 어디 사세요? 무엇을 먹나요?

The first time I heard about RPC was in a distributed systems class, when I was studying Computer Science. I thought it was cool, but at the time I remember not understanding exactly why I would use RPC instead of using the REST standard, for example. Time passes, and I go to work in a company where part of the legacy system was using SOAP. I remember thinking: "hmm, interesting! It looks like RPC, but passes through XML". Years later, I heard about gRPC for the first time, but I never fully understood what it was, what it ate and what it was for.

As my blog serves a lot of personal documentation, I thought it would be cool to document here what I learned about, starting with what RPC is and then moving on to gRPC.

Come on, what is RPC?

RPC is an acronym for Remote Procedure Call. In other words, you send procedures/commands to a remote server. Simply put, this is RPC. It works as follows:

gRPC: onde vive? o que come?

RPC works over both UDP and TCP. It's up to you to see what makes sense for your use case! If you don't mind a possible response or even losing packets, UDP. Otherwise, use TCP. For those who enjoy reading the RFCs, you can find the link here!

OK, but how does RPC differ from a REST call, for example?

Both are ways of architecting APIs, however, the REST architecture has very well-defined principles that must be followed to have a RESTfull architecture. RPC even has principles, but they are defined between client and server. For the RPC client, it is as if it were calling a local procedure.

Another important point is that for RPC, it doesn't matter much whether the connection is TCP or UDP. As for REST APIs, if you want to follow RESTfull, you won't be able to use UDP.

For those who want to know more about it, I recommend this excellent AWS guide on RPC x REST.

And how to implement an RPC server with Go?

We have two main entities, the client and the server.

Starting with the server...

The server is a WEB server, commonly used in any microservice. Let's then define the type of connection we will use, in our case, TCP was chosen:

func main() {
  addr, err := net.ResolveTCPAddr("tcp", "0.0.0.0:52648")
  if err != nil {
    log.Fatal(err)
  }

  conn, err := net.ListenTCP("tcp", addr)
  if err != nil {
    log.Fatal(err)
  }
  defer conn.Close()

  // ...
}

With our server instanced, we will need a handler, that is, our procedure to be executed. It is important to say that we always need to define what arguments will come from and what we will respond to in our HTTP connection. To simplify our proof of concept, we will receive an argument structure and respond to that same structure:

type Args struct {
  Message string
}

type Handler int

func (h *Handler) Ping(args *Args, reply *Args) error {
  fmt.Println("Received message: ", args.Message)

  switch args.Message {
  case "ping", "Ping", "PING":
    reply.Message = "pong"
  default:
    reply.Message = "I don't understand"
  }

  fmt.Println("Sending message: ", reply.Message)
  return nil
}

Having created our processor, now just make it accept connections:

func main() {
  // ...

  h := new(Handler)
  log.Printf("Server listening at %v", conn.Addr())
  s := rpc.NewServer()
  s.Register(h)
  s.Accept(conn)
}

Defining the customer...

As the client and server need to follow the same defined structure, here we will redefine the argument structure to be sent by our client:

type Args struct {
  Message string
}

To make it easier, let's make an interactive client: it will read entries in STDIN and when it receives a new entry, it sends it to our server. For educational purposes, we will write the answer received.

func main() {
  client, err := rpc.Dial("tcp", "localhost:52648")
  if err != nil {
    log.Fatal(err)
  }

  for {
    log.Println("Please, inform the message:")

    scanner := bufio.NewScanner(os.Stdin)
    scanner.Scan()

    args := Args{Message: scanner.Text()}
    log.Println("Sent message:", args.Message)
    reply := &Args{}
    err = client.Call("Handler.Ping", args, reply)
    if err != nil {
      log.Fatal(err)
    }

    log.Println("Received message:", reply.Message)
    log.Println("-------------------------")
  }
}

You can see that we need to provide the address where the server is running and which Handler (procedure) we want to execute.

An important addendum is that we are transporting binary data and by default Go will use encoding/gob. If you want to use another standard, such as JSON, you will need to tell your server to accept that new codec.

For those who want to see the complete code, just access the PoC.

And what is gRPC?

gRPC is a framework for writing applications using RPC! This framework is currently maintained by the CNCF and according to the official documentation it was created by Google:

gRPC was initially created by Google, which has used a single general-purpose RPC infrastructure called Stubby to connect the large number of microservices running within and across its data centers for over a decade. In March 2015, Google decided to build the next version of Stubby and make it open source. The result was gRPC, which is now used in many organizations outside of Google to power use cases from microservices to the "last mile" of computing (mobile, web, and Internet of Things).

In addition to working on different operating systems and on different architectures, gRPC also has the following advantages:

  • Bibliotecas idiomáticas em 11 linguagens;
  • Framework simples para definição do seu serviço e extremamente performático.
  • Fluxo bi-direcional de dados utilizando http/2 para transporte;
  • Funcionalidades extensíveis como autenticação, tracing, balanceador de carga e verificador de saúde.

E como utilizar o gRPC com Go?

Para nossa sorte, Go é uma das 11 linguagens que tem bibliotecas oficiais para o gRPC! É importante falar que esse framework usa o Protocol Buffer para serializar a mensagem. O primeiro passo então é instalar o protobuf de forma local e os plugins para Go:

brew install protobuf
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest

E adicionar os plugins ao seu PATH:

export PATH="$PATH:$(go env GOPATH)/bin"

A mágica do protobuf...

Vamos então criar nossos arquivos .proto! Nesse arquivo vamos definir nosso serviço, quais os handlers que ele possui e para cada handler, qual a requisição e qual resposta esperadas.

syntax = "proto3";

option go_package = "github.com/mfbmina/poc_grpc/proto";

package ping_pong;

service PingPong {
  rpc Ping (PingRequest) returns (PingResponse) {}
}

message PingRequest {
  string message = 1;
}

message PingResponse {
  string message = 1;
}

Com o arquivo .proto, vamos fazer a mágica do gRPC + protobuf acontecer. Os plugins instalados acima, conseguem gerar tudo o que for necessário para um servidor ou cliente gRPC com o seguinte comando:

protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative proto/ping_pong.proto

Esse comando vai gerar dois arquivos: ping_pong.pb.go e ping_pong_grpc.pb.go. Recomendo dar uma olhada nesses arquivos para entender melhor a estrutura do servidor e do cliente. Com isso, podemos então construir o servidor:

Construindo o servidor...

Para conseguir comparar com o RPC comum, vamos utilizar a mesma lógica: recebemos PING e respondemos PONG. Aqui definimos um servidor e um handler para a requisição e usamos as definições vindas do protobuf para a requisição e resposta. Depois, é só iniciar o servidor:

type server struct {
  pb.UnimplementedPingPongServer
}

func (s *server) Ping(_ context.Context, in *pb.PingRequest) (*pb.PingResponse, error) {
  r := &pb.PingResponse{}
  m := in.GetMessage()
  log.Println("Received message:", m)

  switch m {
  case "ping", "Ping", "PING":
    r.Message = "pong"
  default:
    r.Message = "I don't understand"
  }

  log.Println("Sending message:", r.Message)

  return r, nil
}

func main() {
  l, err := net.Listen("tcp", ":50051")
  if err != nil {
    log.Fatal(err)
  }

  s := grpc.NewServer()
  pb.RegisterPingPongServer(s, &server{})
  log.Printf("Server listening at %v", l.Addr())

  err = s.Serve(l)
  if err != nil {
    log.Fatal(err)
  }
}

E o cliente...

Para consumir o nosso servidor, precisamos de um cliente. o cliente é bem simples também. A biblioteca do gRPC já implementa basicamente tudo que precisamos, então inicializamos um client e só chamamos o método RPC que queremos usar, no caso o Ping. Tudo vem importado do código gerado via plugins do protobuf.

func main() {
    conn, err := grpc.NewClient("localhost:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()
    c := pb.NewPingPongClient(conn)

    for {
        log.Println("Enter text: ")
        scanner := bufio.NewScanner(os.Stdin)
        scanner.Scan()
        msg := scanner.Text()
        log.Printf("Sending message: %s", msg)

        ctx, cancel := context.WithTimeout(context.Background(), time.Second)
        defer cancel()
        r, err := c.Ping(ctx, &pb.PingRequest{Message: msg})
        if err != nil {
            log.Fatal(err)
        }

        log.Printf("Received message: %s", r.GetMessage())
        log.Println("-------------------------")
    }
}

Quem tiver interesse para ver o código completo, pode acessar a PoC gRPC.

Considerações finais

O gRPC não é nada mais que uma abstração em cima do RPC convencional utilizando o protobuf como serializador e o protocolo http/2. Existem algumas considerações de performance ao se utilizar o http/2 e em alguns cenários, como em requisições com o corpo simples, o http/1 se mostra mais performático que o http/2. Recomendo a leitura deste benchmark e desta issue aberta no golang/go sobre o http/2. Contudo, em requisições de corpo complexo, como grande parte das que resolvemos dia a dia, gRPC se torna uma solução extremamente atraente devido ao serializador do protobuf, que é extremamente mais rápido que JSON. O Elton Minetto fez um blog post explicando melhor essas alternativas e realizando um benchmark. Um consideração também é o protobuf consegue resolver o problema de inconsistência de contratos entre servidor e cliente, contudo é necessário uma maneira fácil de distribuir os arquivos .proto.

Por fim, minha recomendação é use gRPC se sua equipe tiver a necessidade e a maturidade necessária para tal. Hoje, grande parte das aplicações web não necessitam da performance que gRPC visa propor e nem todos já trabalharam com essa tecnologia, o que pode causar uma menor velocidade e qualidade nas entregas. Como nessa postagem eu citei muitos links, decidi listar todas as referências abaixo:

  • RPC
  • RPC RFC
  • RPC x REST
  • PoC RPC
  • net/rpc
  • encoding/gob
  • CNCF - Cloud Native Computing Foundation
  • gRPC
  • Protocol Buffer
  • PoC gRPC
  • http/1 x http/2 x gRPC
  • http/2 issue
  • JSON x Protobuffers X Flatbuffers

Espero que vocês tenham gostado do tema e obrigado!

위 내용은 gRPC: 어디 사세요? 무엇을 먹나요?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
GO에서 패키지 초기화에 Init을 사용합니다GO에서 패키지 초기화에 Init을 사용합니다Apr 24, 2025 pm 06:25 PM

GO에서는 INT 기능이 패키지 초기화에 사용됩니다. 1) INT 기능은 패키지 초기화시 자동으로 호출되며 글로벌 변수 초기화, 연결 설정 및 구성 파일로드에 적합합니다. 2) 파일 순서로 실행할 수있는 여러 개의 초기 함수가있을 수 있습니다. 3)이를 사용할 때 실행 순서, 테스트 난이도 및 성능 영향을 고려해야합니다. 4) 부작용을 줄이고, 종속성 주입을 사용하고, 초기화를 지연하여 초기 기능의 사용을 최적화하는 것이 좋습니다.

GO의 선택 설명 : 다중화 동시 작업GO의 선택 설명 : 다중화 동시 작업Apr 24, 2025 pm 05:21 PM

go'selectStatementsTreamLinesconcurramprogrammingBymultiplexingOperations.1) ItallowSwaitingOnMultipLechannelOperations, executingThefirStreadYone.2) thedefaultCasePreventsDeadLocksHavingThepRamToproCeedifNooperationSready.3) Itcanusedfored

GO의 고급 동시성 기술 : 컨텍스트 및 대기 그룹GO의 고급 동시성 기술 : 컨텍스트 및 대기 그룹Apr 24, 2025 pm 05:09 PM

Contextandwaitgroupsarecrucialingformaninggoroutineeseforoutineeseferfectial

마이크로 서비스 아키텍처를 사용하는 이점마이크로 서비스 아키텍처를 사용하는 이점Apr 24, 2025 pm 04:29 PM

goisbeneficialformicroservicesduetoitssimplicity, 효율성, AndrobustConcurrenCysupport.1) Go'sdesignempasizessimplicityandefficiency, 이상적인 formicroservices.2) itsconcurrencymodelusinggoroutinesandChannelsAnllingoSyhighconcrency.3) FASTCOMPI

Golang vs. Python : 장단점Golang vs. Python : 장단점Apr 21, 2025 am 12:17 AM

golangisidealforbuildingscalablesystemsdueToitsefficiencyandconcurrency

Golang 및 C : 동시성 대 원시 속도Golang 및 C : 동시성 대 원시 속도Apr 21, 2025 am 12:16 AM

Golang은 동시성에서 C보다 낫고 C는 원시 속도에서 Golang보다 낫습니다. 1) Golang은 Goroutine 및 Channel을 통해 효율적인 동시성을 달성하며, 이는 많은 동시 작업을 처리하는 데 적합합니다. 2) C 컴파일러 최적화 및 표준 라이브러리를 통해 하드웨어에 가까운 고성능을 제공하며 극도의 최적화가 필요한 애플리케이션에 적합합니다.

Golang을 사용하는 이유는 무엇입니까? 혜택과 장점이 설명되었습니다Golang을 사용하는 이유는 무엇입니까? 혜택과 장점이 설명되었습니다Apr 21, 2025 am 12:15 AM

Golang을 선택하는 이유는 다음과 같습니다. 1) 높은 동시성 성능, 2) 정적 유형 시스템, 3) 쓰레기 수집 메커니즘, 4) 풍부한 표준 라이브러리 및 생태계는 효율적이고 신뢰할 수있는 소프트웨어를 개발하기에 이상적인 선택입니다.

Golang vs. C : 성능 및 속도 비교Golang vs. C : 성능 및 속도 비교Apr 21, 2025 am 12:13 AM

Golang은 빠른 개발 및 동시 시나리오에 적합하며 C는 극도의 성능 및 저수준 제어가 필요한 시나리오에 적합합니다. 1) Golang은 쓰레기 수집 및 동시성 메커니즘을 통해 성능을 향상시키고, 고전성 웹 서비스 개발에 적합합니다. 2) C는 수동 메모리 관리 및 컴파일러 최적화를 통해 궁극적 인 성능을 달성하며 임베디드 시스템 개발에 적합합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구