Acquire Kitex RPC Info

Acquire RPC information

The default lifecycle of Kitex’s RPCInfo is from the start of the request to the return of the request (performance considerations), and then it will be placed in sync.Pool to reuse. On the Server side, if it is asynchronously obtained and used in the business Handler, it may lead to read dirty data, nil panic.

Note: Some information needs to rely on the transport protocol (TTHeader or HTTP2) and corresponding MetaHandler. Please refer to here.

1.1 Synchronous usage

Information obtainedKitex fetch method
Get Caller’s Servicecaller, ok := kitexutil.GetCaller(ctx)
Get RPC Methodmethod, ok := kitexutil.GetMethod(ctx)
Get Caller’s addresscluster, ok := kitexutil.GetCallerAddr(ctx)
Get ServiceName defined in IDLsvcName, ok := kitexutil.GetIDLServiceName(ctx)
Get caller’s handler methodcallerMethod, ok := kitexutil.GetCallerHandlerMethod(ctx)
Only the caller is a Kitex server will have this method information by default, or you can set K_METHOD into context.Context then kitex will get it.
Get the transport protocoltp, ok := kitexutil.GetTransportProtocol(ctx)
Get the remote address from the caller-side.ctx = metainfo.WithBackwardValues(ctx)
// set ctx first,then execute RPC call …
err, resp := cli.YourMethod(ctx, req)
rip, ok := metainfo.GetBackwardValue(ctx, consts.RemoteAddr)
Note: Not applicable to oneway method

1.2 Asynchronous usage

If you need to get RPCInfo in the new goroutine, there are two ways to use it. Choose one and get the specific information as above.

  • Method 1: Use the rpcinfo.FreezeRPCInfo provided by Kitex to copy the initial RPCInfo and then use it. However, there is additional consumption due to deep copying of rpcinfo.
import (
    "github.com/cloudwego/kitex/pkg/rpcinfo"
    "github.com/cloudwego/kitex/pkg/utils/kitexutil"
)
// this creates a read-only copy of `ri` and attaches it to the new context
ctx2 := rpcinfo.FreezeRPCInfo(ctx)
go func(ctx context.Context) {
    // ...
    ri := rpcinfo.GetRPCInfo(ctx) // OK

    // eg: get client psm
    // caller, ok := kitexutil.GetCaller(ctx)
    //...
}(ctx2)
  • Method 2 [Kitex v0.8.0+]: Disable RPCInfo pool Set environment variables KITEX_DISABLE_RPCINFO_POOL=true or configure rpcinfo.EnablePool(false) in the code.

Meta Info Transparent Transmission

Please see Meta Info Transparent Transmission.


Last modified December 9, 2024 : Update prerequisite.md (#1178) (b5e2299)