Configs2026年4月13日·1 分钟阅读

gRPC-Go — High-Performance RPC Framework for Go

gRPC-Go is the Go implementation of gRPC, a high-performance, open-source RPC framework. It uses Protocol Buffers for serialization and HTTP/2 for transport, enabling efficient communication between microservices with strongly-typed contracts.

AI
AI Open Source · Community
快速使用

先拿来用,再决定要不要深挖

这里应该同时让用户和 Agent 知道第一步该复制什么、安装什么、落到哪里。

# Install protoc compiler and Go plugins
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

# Define your service (hello.proto)
# syntax = "proto3";
# package hello;
# service Greeter {
#   rpc SayHello (HelloRequest) returns (HelloReply) {}
# }
# message HelloRequest { string name = 1; }
# message HelloReply { string message = 1; }

# Generate Go code
protoc --go_out=. --go-grpc_out=. hello.proto

Introduction

gRPC is a modern RPC framework that uses Protocol Buffers for interface definition and serialization, and HTTP/2 for transport. It provides strongly-typed service contracts, streaming, and efficient binary serialization — making it the standard for microservice communication at Google, Netflix, Square, and thousands of companies.

With over 23,000 GitHub stars (Go implementation), gRPC-Go is the most popular gRPC implementation. gRPC is language-agnostic — a Go server can communicate with Python, Java, C++, or any other gRPC client seamlessly.

What gRPC Does

gRPC lets you define service interfaces in .proto files, then auto-generates client and server code in any supported language. Instead of REST (JSON over HTTP/1.1), gRPC uses binary Protocol Buffers over HTTP/2 — providing smaller payloads, faster serialization, bidirectional streaming, and built-in code generation.

Architecture Overview

[.proto Service Definition]
service UserService {
  rpc GetUser(GetUserRequest)
    returns (User) {}
  rpc ListUsers(ListRequest)
    returns (stream User) {}
}
        |
   [protoc + plugins]
   Generate Go code
        |
+-------+-------+
|               |
[Server]        [Client]
Implement       Auto-generated
service         stub with
interface       typed methods
        |
   [HTTP/2 Transport]
   Binary Protocol Buffers
   Multiplexed streams
   Header compression
        |
   [Features]
   Unary, Server streaming,
   Client streaming,
   Bidirectional streaming
   Interceptors, Deadlines,
   Metadata, Load balancing

Self-Hosting & Configuration

// Server implementation
package main

import (
    "context"
    "log"
    "net"
    "google.golang.org/grpc"
    pb "myapp/proto/hello"
)

type server struct {
    pb.UnimplementedGreeterServer
}

func (s *server) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloReply, error) {
    return &pb.HelloReply{Message: "Hello, " + req.Name}, nil
}

func main() {
    lis, _ := net.Listen("tcp", ":50051")
    s := grpc.NewServer()
    pb.RegisterGreeterServer(s, &server{})
    log.Println("gRPC server listening on :50051")
    s.Serve(lis)
}
// Client
package main

import (
    "context"
    "log"
    "google.golang.org/grpc"
    "google.golang.org/grpc/credentials/insecure"
    pb "myapp/proto/hello"
)

func main() {
    conn, _ := grpc.NewClient("localhost:50051",
        grpc.WithTransportCredentials(insecure.NewCredentials()))
    defer conn.Close()

    client := pb.NewGreeterClient(conn)
    resp, err := client.SayHello(context.Background(),
        &pb.HelloRequest{Name: "World"})
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("Response: %s", resp.Message)
}

Key Features

  • Code Generation — auto-generate clients and servers from .proto files
  • Strongly Typed — compile-time type safety for all messages and RPCs
  • HTTP/2 — multiplexing, header compression, bidirectional streaming
  • 4 RPC Types — unary, server streaming, client streaming, bidirectional
  • Interceptors — middleware for logging, auth, metrics, and tracing
  • Deadlines — built-in request deadline propagation
  • Load Balancing — client-side load balancing with pluggable policies
  • Cross-Language — Go, Python, Java, C++, C#, Node.js, Ruby, and more

Comparison with Similar Tools

Feature gRPC REST (JSON) tRPC GraphQL Thrift
Serialization Protobuf (binary) JSON (text) JSON JSON Binary
Transport HTTP/2 HTTP/1.1 HTTP HTTP TCP/HTTP
Streaming Yes (4 types) No (SSE only) No Subscriptions No
Code Gen Yes (.proto) OpenAPI (optional) TypeScript types Schema Yes (.thrift)
Performance Very High Moderate Moderate Moderate Very High
Browser Support Via grpc-web Native Native Native Limited
Best For Microservices Web APIs TS full-stack Flexible APIs High-perf RPC

FAQ

Q: gRPC vs REST — when should I use gRPC? A: gRPC for internal microservice communication where performance and type safety matter. REST for public APIs, browser clients, and when human readability is important.

Q: Can browsers use gRPC? A: Not directly (browsers do not support HTTP/2 trailers). Use grpc-web (a proxy that translates) or gRPC-Gateway (generates REST endpoints from .proto files).

Q: How do I add authentication? A: Use interceptors for auth middleware. Support JWT tokens via metadata, mutual TLS for service-to-service auth, or integrate with auth providers via custom credentials.

Q: What is Connect (buf.build)? A: Connect is a modern alternative to grpc-go that generates HTTP/1.1+JSON and gRPC-compatible services from .proto files, with better browser support and simpler API.

Sources

讨论

登录后参与讨论。
还没有评论,来写第一条吧。

相关资产