The request context includes call properties and transmitted custom data other than call-defined parameters. The call properties include the called address, name of the application that initiates the call, and time-out period.

Set and retrieve the ongoing call context

com.taobao.hsf.util.RequestCtxUtil provides the static method used to set and retrieve the call context. Based on ThreadLocal, getXXX removes the XXX property from the ThreadLocal variable. This method takes effect only for a single call of the current thread. The following table lists the methods used to set and retrieve specific properties.

Consumer

Method Description
setRequestTimeout() Sets the time-out period for a single call.
setUserId() Sets the userId of the unit service in the current call (this method is required by generic call).
getProviderIp() Retrieves the IP address of the provider that was called most recently.
setTargetServerIp(String ip) Sets the IP address of the target provider in the next call of the current thread. This IP address must be included in the address list for memory-provided services.
setDirectTargetServerIp(String targetIp) Sets the IP address of the target provider in the next call of the current thread. This method bypasses the registry and ignores the address list in the memory.

Provider

Method Description
getClientIp() Retrieves the IP address of the caller.
getAppNameOfClient() Retrieves the name of the application used by the caller.
isHttpRequest() Indicates 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 the method used to transmit additional data to the provider without interface modification. Parameters belong to the custom domain object (DO) type or basic types. Ensure that the peer end can serialize parameters of the same type.

Set the context before the consumer initiates a call.

//setup context before rpc call
RPCContext rpcContext = RPCContext.getClientContext();
rpcContext.putAttachment("tetantId", "123");

//RPC call and context are 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");