在RPC框架中,Handler用于接收RpcRequest,經過處理后返回RpcResponse
@Slf4j
public class RpcRequestHandler {
????private final ServiceProvider serviceProvider;
? ? //獲取一個單例模式的服務提供類
????public RpcRequestHandler() {
????????serviceProvider = SingletonFactory.getInstance(ZkServiceProviderImpl.class);
????}
????/**
?????* Processing rpcRequest: call the corresponding method, and then return the method
?????*/
? ? //從請求中提取方法名成,并調用到這個方法的服務
????public Object handle(RpcRequest rpcRequest) {
????????Object service = serviceProvider.getService(rpcRequest.getRpcServiceName());
????????return invokeTargetMethod(rpcRequest, service);
????}
????/**
?????* get method execution results
?????*
?????* @param rpcRequest client request
?????* @param service????service object
?????* @return the result of the target method execution
?????*/
? ? //通過服務名稱調用方法并返回結果
????private Object invokeTargetMethod(RpcRequest rpcRequest, Object service) {
????????Object result;
????????try {
????????????Method method = service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamTypes());
????????????result = method.invoke(service, rpcRequest.getParameters());
????????????log.info("service:[{}] successful invoke method:[{}]", rpcRequest.getInterfaceName(), rpcRequest.getMethodName());
????????} catch (NoSuchMethodException | IllegalArgumentException | InvocationTargetException | IllegalAccessException e) {
????????????throw new RpcException(e.getMessage(), e);
????????}
????????return result;
????}
}