Skip to content

gRPC Server Example

go-zero provides a gRPC server that provides:

  1. Service discovery capability (etcd as registration centre)
  2. Load Balancer(p2c algorithms)
  3. Node Affinity
  4. Multi-node direct connection mode
  5. Timeout processing
  6. Traffic limiting, breaking
  7. Authentication capacity
  8. Exception Capture

In go-zero, we can use goctl to quickly sound a gRPC service or create an example of a gRPC service using the goctl 0 code.

:::tip Tips Quickly generate and start a goctl service example for a gRPC service that can be referenced Quick Start Microservice Book :::

We’re here to create a full gRPC service with a proto.

1. Create a service directory and initialize the go module project

Section titled “1. Create a service directory and initialize the go module project”
Terminal window
$ mkdir demo && cd demo
$ go mod init demo
$ goctl rpc -o greet.proto
Terminal window
$ goctl rpc protoc greet.proto --go_out=. --go-grpc_out=. --zrpc_out=.

::tip Tips

  1. goctl installation please refer to Goctl Installation
  2. rpc code generation command tutorial reference goctl rpc
  3. Proto use related questions refer to Proto Code Generating FAQ :::
demo
├── etc
│   └── greet.yaml
├── go.mod
├── greet
│   ├── greet.pb.go
│   └── greet_grpc.pb.go
├── greet.go
├── greet.proto
├── greetclient
│   └── greet.go
└── internal
├── config
│   └── config.go
├── logic
│   └── pinglogic.go
├── server
│   └── greetserver.go
└── svc
└── servicecontext.go
8 directories, 11 files

:::tip hint service directory structure introduction refer to Project Structure :::

In go-zero we support the etcd service registration and direct connection mode and we only adjust the static configuration files in the etc directory.

:::tip hint gRPC service configuration accessible GRPC Service Configuration

In addition to a go-zero built-in ecd as a service, the community also provides support for the discovery of services such as nacos, consul, etc. More Services found components for details :::

etcd 服务注册 To use etcd as a registry, simply add the etcd configuration to the static configuration file, with the following minimal reference configuration (gray underlined section):

demo/etc/greet.yaml
Name: greet.rpc
ListenOn: 0.0.0.0:8080
Etcd:
Hosts:
- 127.0.0.1:2379
Key: greet.rpc

The service is registered with the key greet.rpc, which we can see in etcd by the following method:

Terminal window
$ etcdctl get --prefix greet.rpc
greet.rpc/7587870460981677828
192.168.72.53:8080

Since the key registered by etcd is greet.rpc, from the business presentation layer, it is a key registered to etcd, but go-zero is actually storing the key with an etcd The go-zero layer is actually storing the key with a tenant id of etcd, so during service discovery, it will also fetch all available ip nodes with the etcdctl get --prefix command.

直连模式 By contrast, using direct link mode removes the etcd configuration, go-zero auto-identification, with a minimum configuration reference:

demo/etc/greet.yaml
Name: greet.rpc
ListenOn: 0.0.0.0:8080

The code generated by goctl does not require the user to implement the stub. The goctl tool will help you to implement all of this, referencing the following:

demo/internal/server/greetserver.go
// Code generated by goctl. DO NOT EDIT.
// Source: greet.proto
package server
import (
"context"
"demo/greet"
"demo/internal/logic"
"demo/internal/svc"
)
type GreetServer struct {
svcCtx *svc.ServiceContext
greet.UnimplementedGreetServer
}
func NewGreetServer(svcCtx *svc.ServiceContext) *GreetServer {
return &GreetServer{
svcCtx: svcCtx,
}
}
func (s *GreetServer) Ping(ctx context.Context, in *greet.Request) (*greet.Response, error) {
l := logic.NewPingLogic(ctx, s.svcCtx)
return l.Ping(in)
}

Once the code is generated with goctl, we simply need to fill in our business code in the log file, reference business code (grey bottom texture part):

demo/internal/logic/pinglogic.go
package logic
import (
"context"
"demo/greet"
"demo/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type PingLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewPingLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PingLogic {
return &PingLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *PingLogic) Ping(in *greet.Request) (*greet.Response, error) {
return &greet.Response{
Pong: "pong",
}, nil
}

gRPC provides debugging capabilities so that we can debug with tools like grpcurl, In go-zero, it is recommended to turn it on in development and test environments, and off in pre-production and official environments,So we configure the environment mode in the static configuration file as dev or test (default is dev environment), the relevant code is as follows:

demo/greet.go

package main
...
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
ctx := svc.NewServiceContext(c)
s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
greet.RegisterGreetServer(grpcServer, server.NewGreetServer(ctx))
if c.Mode == service.DevMode || c.Mode == service.TestMode {
reflection.Register(grpcServer)
}
})
...
}

demo/etc/greet.yaml

Name: greet.rpc
ListenOn: 0.0.0.0:8080
Mode: dev
Etcd:
Hosts:
- 127.0.0.1:2379
Key: greet.rpc

go-zero rpc is embedded in a very rich intermediary, seeserverinterceptors

  • StreamAuthorizeInterceptor|UnaryAuthorizeInterceptor
  • StreamBreakerInterceptor|UnaryBreakerInterceptor
  • UnaryPrometheusInterceptor
  • StreamRecoverInterceptor|UnaryRecoverInterceptor
  • UnarySheddingInterceptor
  • UnaryStatInterceptor
  • UnaryTimeoutInterceptor
  • StreamTraceInterceptor|UnaryTraceInterceptor

In the above built-in intermediates, link tracking intermediates, indicator statistical intermediary, time statistical intermediary, abnormal capture medium, melting intermediation can be configured to turn on or off and other intermediates will be enabled by default. Specific configuration can be consultedservice configuration

package main
...
var configFile = flag.String("f", "etc/greet.yaml", "the config file")
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
ctx := svc.NewServiceContext(c)
s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
greet.RegisterGreetServer(grpcServer, server.NewGreetServer(ctx))
if c.Mode == service.DevMode || c.Mode == service.TestMode {
reflection.Register(grpcServer)
}
})
defer s.Stop()
s.AddUnaryInterceptors(exampleUnaryInterceptor)
s.AddStreamInterceptors(exampleStreamInterceptor)
fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
s.Start()
}
func exampleUnaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
// TODO: fill your logic here
return handler(ctx, req)
}
func exampleStreamInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
// TODO: fill your logic here
return handler(srv, ss)
}

Reference Metata