백엔드 개발 Golang gRPC: 어디 사세요? 무엇을 먹나요?

gRPC: 어디 사세요? 무엇을 먹나요?

Sep 28, 2024 am 06:07 AM

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으로 문의하세요.

핫 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 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

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

Debian Openssl의 취약점은 무엇입니까? Debian Openssl의 취약점은 무엇입니까? Apr 02, 2025 am 07:30 AM

보안 통신에 널리 사용되는 오픈 소스 라이브러리로서 OpenSSL은 암호화 알고리즘, 키 및 인증서 관리 기능을 제공합니다. 그러나 역사적 버전에는 알려진 보안 취약점이 있으며 그 중 일부는 매우 유해합니다. 이 기사는 데비안 시스템의 OpenSSL에 대한 일반적인 취약점 및 응답 측정에 중점을 둘 것입니다. DebianopensSL 알려진 취약점 : OpenSSL은 다음과 같은 몇 가지 심각한 취약점을 경험했습니다. 심장 출혈 ​​취약성 (CVE-2014-0160) :이 취약점은 OpenSSL 1.0.1 ~ 1.0.1F 및 1.0.2 ~ 1.0.2 베타 버전에 영향을 미칩니다. 공격자는이 취약점을 사용하여 암호화 키 등을 포함하여 서버에서 무단 읽기 민감한 정보를 사용할 수 있습니다.

프론트 엔드에서 백엔드 개발로 전환하면 Java 또는 Golang을 배우는 것이 더 유망합니까? 프론트 엔드에서 백엔드 개발로 전환하면 Java 또는 Golang을 배우는 것이 더 유망합니까? Apr 02, 2025 am 09:12 AM

백엔드 학습 경로 : 프론트 엔드에서 백엔드 초보자로서 프론트 엔드에서 백엔드까지의 탐사 여행은 프론트 엔드 개발에서 변화하는 백엔드 초보자로서 이미 Nodejs의 기초를 가지고 있습니다.

GO에서 플로팅 포인트 번호 작업에 어떤 라이브러리가 사용됩니까? GO에서 플로팅 포인트 번호 작업에 어떤 라이브러리가 사용됩니까? Apr 02, 2025 pm 02:06 PM

Go Language의 부동 소수점 번호 작동에 사용되는 라이브러리는 정확도를 보장하는 방법을 소개합니다.

Go 's Crawler Colly의 큐 스레드의 문제는 무엇입니까? Go 's Crawler Colly의 큐 스레드의 문제는 무엇입니까? Apr 02, 2025 pm 02:09 PM

Go Crawler Colly의 대기열 스레딩 문제는 Colly Crawler 라이브러리를 GO 언어로 사용하는 문제를 탐구합니다. � ...

Beego ORM의 모델과 관련된 데이터베이스를 지정하는 방법은 무엇입니까? Beego ORM의 모델과 관련된 데이터베이스를 지정하는 방법은 무엇입니까? Apr 02, 2025 pm 03:54 PM

Beegoorm 프레임 워크에서 모델과 관련된 데이터베이스를 지정하는 방법은 무엇입니까? 많은 Beego 프로젝트에서는 여러 데이터베이스를 동시에 작동해야합니다. Beego를 사용할 때 ...

이동 중에 왜 println 및 string () 함수로 문자열이 다른 효과를 갖는 이유는 무엇입니까? 이동 중에 왜 println 및 string () 함수로 문자열이 다른 효과를 갖는 이유는 무엇입니까? Apr 02, 2025 pm 02:03 PM

Go Language의 문자열 인쇄의 차이 : println 및 String () 함수 사용 효과의 차이가 진행 중입니다 ...

Redis Stream을 사용하여 GO Language에서 메시지 대기열을 구현할 때 User_ID 유형 변환 문제를 해결하는 방법은 무엇입니까? Redis Stream을 사용하여 GO Language에서 메시지 대기열을 구현할 때 User_ID 유형 변환 문제를 해결하는 방법은 무엇입니까? Apr 02, 2025 pm 04:54 PM

Go Language에서 메시지 대기열을 구현하기 위해 Redisstream을 사용하는 문제는 Go Language와 Redis를 사용하는 것입니다 ...

골란드의 사용자 정의 구조 레이블이 표시되지 않으면 어떻게해야합니까? 골란드의 사용자 정의 구조 레이블이 표시되지 않으면 어떻게해야합니까? Apr 02, 2025 pm 05:09 PM

골란드의 사용자 정의 구조 레이블이 표시되지 않으면 어떻게해야합니까? Go Language 개발을 위해 Goland를 사용할 때 많은 개발자가 사용자 정의 구조 태그를 만날 것입니다 ...

See all articles