RPC--RPCHandler的实现

在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;

}

}