The call context includes call properties and transmitted custom data other than interface-specific parameters. The call properties include the IP address, name of the application that initiates the call, and timeout period.
Specify and retrieve the ongoing call context
com.taobao.hsf.util.RequestCtxUtil provides a static method to specify and retrieve the call context. Based on ThreadLocal, getxxx removes the xxx property from the ThreadLocal variable. This method takes effect for only a single call of the current thread.
The following table describes the methods that are used to specify and retrieve specific properties.
- Consumers
Method Description setRequestTimeout() Specifies the timeout period for a single call. setUserId() Specifies the user ID of the unit service in the current call. This method is required for generic calls. getProviderIp() Retrieves the IP address of the provider that was latest called. setTargetServerIp(String ip) Specifies the IP address of the required provider in the next call of the current thread. This IP address must be included in the IP address list for memory-provided services. setDirectTargetServerIp(String targetIp) Specifies the IP address of the provider in the next call of the current thread. This method bypasses the registry and ignores the IP address list in the memory. - Providers
Method Description getClientIp() Retrieves the IP address of the caller. getAppNameOfClient() Retrieves the name of the application that is used by the caller. isHttpRequest() Specifies whether the call is an HTTP call. getHttpHeader(String key) Retrieves the header property of the HTTP request.
Transmit the custom request context
RpcContext provides a method to transmit additional data to the provider without interface modification. The parameter type can be the custom domain object (DO) type or a basic type. Make sure that the peer end can serialize parameters of the same type.
- Specify the context before the consumer initiates a call.
//setup context before rpc call RPCContext rpcContext = RPCContext.getClientContext(); rpcContext.putAttachment("tetantId", "123"); //This is an RPC call. The call context is also transmitted to the peer end. orderService.queryOrder(1L);
- Retrieve the context by using the methods of the provider.
//get context data RPCContext rpcContext = RPCContext.getServerContext(); String myContext = (String)rpcContext.getAttachment("tetantId");