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.
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.
|setRequestTimeout()||Specifies the time-out period for a single call.|
|setUserId()||Specifies the userId of the unit service in the current call. This method is required for generic call.|
|getProviderIp()||Retrieves the IP address of the provider that was latest called.|
|setTargetServerIp(String ip)||Specifies the IP address of the required server 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)||Specifies the IP address of the server in the next call of the current thread. This method bypasses the registry and ignores the address list in the memory.|
|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 basic types. Ensure 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"); //rpc call and context is also transmitted to the remote 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");