introduce

This article shows you how to automatically add RequestId for each API in gRPC microservices.

We will use RK-boot to start the gRPC service.

Please visit the following address for the full tutorial:

  • rkdev.info/cn
  • Rkdocs.net lilify. app/cn (standby)

The installation

go get github.com/rookie-ninja/rk-boot
Copy the code

Quick start

For details, please refer to:

  • The official documentation
  • Or, making

When the Meta interceptor is enabled, each request automatically contains the following values.

The Header button details
X-Request-Id The interceptor automatically generates the request ID.
X-[Prefix]-App Service name.
X-[Prefix]-App-Version Service version.
X-[Prefix]-App-Unix-Time The Unix time of the current service.
X-[Prefix]-Request-Received-Time The timestamp of the request was received.

1. Create the boot. Yaml

To verify this, we started commonService, which contains a series of common apis such as /rk/v1/healthy.

---
grpc:
  - name: greeter                   # Name of grpc entry
    port: 8080                      # Port of grpc entry
    enabled: true                   # Enable grpc entry
    commonService:
      enabled: true                 # Enable common service for testing
    interceptors:
      meta:
        enabled: true
Copy the code

2. Create a main. Go

package main

import (
   "context"
   "github.com/rookie-ninja/rk-boot"
)

// Application entrance.
func main() {
   // Create a new boot instance.
   boot := rkboot.NewBoot()

   // Bootstrap
   boot.Bootstrap(context.Background())

   // Wait for shutdown sig
   boot.WaitForShutdownSig(context.Background())
}
Copy the code

3. Start the main. Go

$ go run main.go
Copy the code

4. Verify

In boot.yaml, we did not enable enableRkGwOption, so we return headers with the grPC-metadata prefix.

$ curl -vs -X GET localhost:8080/rk/v1/healthy ... < Grpc-Metadata-Content-Type: application/grpc < Grpc-Metadata-X-Request-Id: cb8c0c77-39cd-4e15-89d2-66ba30fa7a46 < Grpc-Metadata-X-Rk-App-Name: rk-demo < Grpc-Metadata-X-Rk-App-Unix-Time: 2021-07-10T00:19:58.170222+08:00 < grpc-metadata-x-rk-app-version: master-f414049 < GRpc-metadata-x-rk-received Time: The 2021-07-10 T00:19:58. 170222 + 08:00... {"healthy":true}Copy the code

If we enable enableRkGwOption, grPC-Metadata will disappear!

---
grpc:
  ...
  enableRkGwOption: true
Copy the code
$ curl -vs -X GET localhost:8080/rk/v1/healthy ... < X-Request-Id: 2ae18df6-d132-42ce-841c-571f19a88787 < X-Rk-App-Name: rk-demo < X-Rk-App-Unix-Time: 2021-07-10T00:24:10.281868+08:00 < X-RK-app-version: master-f414049 < X-Rk-received Time: The 2021-07-10 T00: good. 281868 + 08:00... {"healthy":true}Copy the code

Covering the requestId

If we want to customize requestId, we need to add a Header.

func (server *GreeterServer) Greeter(ctx context.Context, request *greeter.GreeterRequest) (*greeter.GreeterResponse, error) { // Override request id rkgrpcctx.AddHeaderToClient(ctx, rkginctx.RequestIdKey, "request-id-override") // We expect new request id attached to logger rkgrpcctx.GetLogger(ctx).Info("Received request") return &greeter.GreeterResponse{ Message: fmt.Sprintf("Hello %s!" , request.Name), }, nil }Copy the code

In the header returned, there are two X-Request-ids, because GRPC will merge the values, not replace them, for the same Key.

On the client side, however, the last value is extracted.

$ curl -vs -X GET "localhost:8080/v1/greeter? name=rk-dev" ... < X-Request-Id: 4e858644-f2e2-48b2-adec-a1d329497abf < X-Request-Id: request-id-override < X-Rk-App-Name: Rk-demo < X-rk-app-UNIX-time: 2021-07-10T00:29:19.030555+08:00 < X-Rk-app-version: master-f414049 < X-Rk-received Time: The 2021-07-10 T00: did. 030555 + 08:00... {"Message":"Hello rk-dev!" }Copy the code

If we started the log interceptor, we would see the following log.

2021-07-10T00:29:19.030+0800 INFO BASIC /main.go:40 Received Request {"requestId": "request-id-override"}Copy the code
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- endTime = 2021-07-10 T00: did. 030673 + 08:00 StartTime = 2021-07-10 T00: did. 030535 + 08:00 elapsedNano = 138133 timezone = CST ids={"eventId":"request-id-override","requestId":"request-id-override"} app={"appName":"rk-demo","appVersion":"master-f414049","entryName":"greeter","entryType":"GrpcEntry"} Env = {" arch ", "amd64", "az" : "*", "domain" : "*", "hostname" : "lark. Local", "localIP" : "10.8.0.2", "OS" : "Darwin", "realm" : "*", "region ":" * "} payloads={"grpcMethod":"Greeter","grpcService":"api.v1.Greeter","grpcType":"unaryServer","gwMethod":"GET","gwPath":"/v1/ Greeter gwScheme ", "" :" HTTP ", "gwUserAgent" : "curl / 7.64.1"} error = {} counters = {} pairs = {} timing = {} remoteAddr=localhost:58601 operation=/api.v1.Greeter/Greeter resCode=OK eventStatus=Ended EOECopy the code

Overrides the header prefix

---
grpc:
  - name: greeter
    ...
    interceptors:
      meta:
        enabled: true        # Enable meta interceptor/middleware
        prefix: "Override"   # Override prefix which formed as X-[Prefix]-xxx
Copy the code
$ curl -vs -X GET localhost:8080/rk/v1/healthy
...
< X-Override-App-Name: rk-demo
< X-Override-App-Unix-Time: 2021-07-10T00:34:59.974205+08:00
< X-Override-App-Version: master-f414049
< X-Override-Received-Time: 2021-07-10T00:34:59.974205+08:00
< X-Request-Id: 4deded12-2d39-42a5-b740-b4f74dd73c90
...
{"healthy":true}
Copy the code