Java Code Examples for com.alipay.sofa.rpc.core.request.SofaRequest#getMethodName()

The following examples show how to use com.alipay.sofa.rpc.core.request.SofaRequest#getMethodName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractHttp2ClientTransport.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
protected FullHttpRequest convertToHttpRequest(SofaRequest request) {
    HttpScheme scheme = SslContextBuilder.SSL ? HttpScheme.HTTPS : HttpScheme.HTTP;
    AsciiString hostName = new AsciiString(providerInfo.getHost() + ':' + providerInfo.getPort());
    String url = "/" + request.getTargetServiceUniqueName() + "/" + request.getMethodName();
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("send request to url :{}", url);
    }

    // Create a simple POST request with a body.
    FullHttpRequest httpRequest = new DefaultFullHttpRequest(HTTP_1_1, POST, url,
        wrappedBuffer(request.getData().array()));
    HttpHeaders headers = httpRequest.headers();
    addToHeader(headers, HttpHeaderNames.HOST, hostName);
    addToHeader(headers, HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
    addToHeader(headers, HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
    addToHeader(headers, HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
    addToHeader(headers, RemotingConstants.HEAD_SERIALIZE_TYPE,
        SerializerFactory.getAliasByCode(request.getSerializeType()));
    addToHeader(headers, RemotingConstants.HEAD_TARGET_APP, request.getTargetAppName());
    Map<String, Object> requestProps = request.getRequestProps();
    if (requestProps != null) {
        // <String, Object> 转扁平化 <String, String>
        flatCopyTo("", requestProps, headers);
    }
    return httpRequest;
}
 
Example 2
Source File: GenericServiceImpl.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public void generic(Request request, StreamObserver<Response> responseObserver) {

    SofaRequest sofaRequest = TracingContextKey.getKeySofaRequest().get(Context.current());

    String methodName = sofaRequest.getMethodName();
    Class[] argTypes = getArgTypes(request);
    try {
        Serializer serializer = SerializerFactory.getSerializer(request.getSerializeType());

        Method declaredMethod = proxyClass.getDeclaredMethod(methodName, argTypes);
        Object result = declaredMethod.invoke(ref, getInvokeArgs(request, argTypes, serializer));

        Response.Builder builder = Response.newBuilder();
        builder.setSerializeType(request.getSerializeType());
        builder.setType(declaredMethod.getReturnType().getName());
        builder.setData(ByteString.copyFrom(serializer.encode(result, null).array()));
        Response build = builder.build();
        responseObserver.onNext(build);
        responseObserver.onCompleted();
    } catch (Exception e) {
        LOGGER.error("Invoke " + methodName + " error:", e);
        throw new SofaRpcRuntimeException(e);
    }
}
 
Example 3
Source File: RestClientTransport.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
protected Method getMethod(SofaRequest request) throws SofaRpcException {
    String serviceUniqueName = request.getTargetServiceUniqueName();
    String methodName = request.getMethodName();
    String[] methodSigns = request.getMethodArgSigs();

    Method method = ReflectCache.getOverloadMethodCache(serviceUniqueName, methodName, methodSigns);
    if (method == null) {
        try {
            String interfaceName = request.getInterfaceName();
            method = ClassUtils.forName(interfaceName)
                .getMethod(methodName, ClassTypeUtils.getClasses(methodSigns));
            ReflectCache.putOverloadMethodCache(serviceUniqueName, method);
        } catch (NoSuchMethodException e) {
            throw new SofaRpcException(RpcErrorType.CLIENT_UNDECLARED_ERROR, "Method not found", e);
        }
    }
    return method;
}
 
Example 4
Source File: WeightConsistentHashLoadBalancer.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public ProviderInfo doSelect(SofaRequest request, List<ProviderInfo> providerInfos) {
    String interfaceId = request.getInterfaceName();
    String method = request.getMethodName();
    String key = interfaceId + "#" + method;
    // 判断是否同样的服务列表
    int hashcode = providerInfos.hashCode();
    Selector selector = selectorCache.get(key);
    // 原来没有
    if (selector == null ||
        // 或者服务列表已经变化
        selector.getHashCode() != hashcode) {
        selector = new Selector(interfaceId, method, providerInfos, hashcode);
        selectorCache.put(key, selector);
    }
    return selector.select(request);
}
 
Example 5
Source File: FailFastCluster.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public SofaResponse doInvoke(SofaRequest request) throws SofaRpcException {
    ProviderInfo providerInfo = select(request);
    try {
        SofaResponse response = filterChain(providerInfo, request);
        if (response != null) {
            return response;
        } else {
            throw new SofaRpcException(RpcErrorType.CLIENT_UNDECLARED_ERROR,
                "Failed to call " + request.getInterfaceName() + "." + request.getMethodName()
                    + " on remote server " + providerInfo + ", return null");
        }
    } catch (Exception e) {
        throw new SofaRpcException(RpcErrorType.CLIENT_UNDECLARED_ERROR,
            "Failed to call " + request.getInterfaceName() + "." + request.getMethodName()
                + " on remote server: " + providerInfo + ", cause by: "
                + e.getClass().getName() + ", message is: " + e.getMessage(), e);
    }
}
 
Example 6
Source File: LookoutSubscriber.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * create RpcClientLookoutModel
 * @param request
 * @param response
 * @return
 */
private RpcClientLookoutModel createClientMetricsModel(SofaRequest request, SofaResponse response) {

    RpcClientLookoutModel clientMetricsModel = new RpcClientLookoutModel();

    RpcInternalContext context = RpcInternalContext.getContext();

    String app = getStringAvoidNull(context.getAttachment(RpcConstants.INTERNAL_KEY_APP_NAME));
    String service = request.getTargetServiceUniqueName();
    String method = request.getMethodName();
    String protocol = getStringAvoidNull(context.getAttachment(RpcConstants.INTERNAL_KEY_PROTOCOL_NAME));
    String invokeType = request.getInvokeType();
    String targetApp = request.getTargetAppName();
    Long requestSize = getLongAvoidNull(context.getAttachment(RpcConstants.INTERNAL_KEY_REQ_SIZE));
    Long responseSize = getLongAvoidNull(context.getAttachment(RpcConstants.INTERNAL_KEY_RESP_SIZE));
    Long elapsedTime = getLongAvoidNull(context.getAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE));
    Boolean success = response != null && !response.isError() && response.getErrorMsg() == null &&
        (!(response.getAppResponse() instanceof Throwable));

    clientMetricsModel.setApp(app);
    clientMetricsModel.setService(service);
    clientMetricsModel.setMethod(method);
    clientMetricsModel.setProtocol(protocol);
    clientMetricsModel.setInvokeType(invokeType);
    clientMetricsModel.setTargetApp(targetApp);
    clientMetricsModel.setRequestSize(requestSize);
    clientMetricsModel.setResponseSize(responseSize);
    clientMetricsModel.setElapsedTime(elapsedTime);
    clientMetricsModel.setSuccess(success);

    return clientMetricsModel;
}
 
Example 7
Source File: LookoutSubscriber.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * create RpcServerLookoutModel
 * @param request
 * @param response
 * @return
 */
private RpcServerLookoutModel createServerMetricsModel(SofaRequest request, SofaResponse response) {

    RpcServerLookoutModel rpcServerMetricsModel = new RpcServerLookoutModel();

    RpcInternalContext context = RpcInternalContext.getContext();

    String app = request.getTargetAppName();
    String service = request.getTargetServiceUniqueName();
    String method = request.getMethodName();
    String protocol = getStringAvoidNull(request.getRequestProp(RemotingConstants.HEAD_PROTOCOL));
    String invokeType = request.getInvokeType();
    String callerApp = getStringAvoidNull(request.getRequestProp(RemotingConstants.HEAD_APP_NAME));
    Long elapsedTime = getLongAvoidNull(context.getAttachment(RpcConstants.INTERNAL_KEY_IMPL_ELAPSE));
    boolean success = response != null && !response.isError() && response.getErrorMsg() == null &&
        (!(response.getAppResponse() instanceof Throwable));

    rpcServerMetricsModel.setApp(app);
    rpcServerMetricsModel.setService(service);
    rpcServerMetricsModel.setMethod(method);
    rpcServerMetricsModel.setProtocol(protocol);
    rpcServerMetricsModel.setInvokeType(invokeType);
    rpcServerMetricsModel.setCallerApp(callerApp);
    rpcServerMetricsModel.setElapsedTime(elapsedTime);
    rpcServerMetricsModel.setSuccess(success);

    return rpcServerMetricsModel;
}
 
Example 8
Source File: ConsistentHashLoadBalancer.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public ProviderInfo doSelect(SofaRequest request, List<ProviderInfo> providerInfos) {
    String interfaceId = request.getInterfaceName();
    String method = request.getMethodName();
    String key = interfaceId + "#" + method;
    int hashcode = providerInfos.hashCode(); // 判断是否同样的服务列表
    Selector selector = selectorCache.get(key);
    if (selector == null // 原来没有
        ||
        selector.getHashCode() != hashcode) { // 或者服务列表已经变化
        selector = new Selector(interfaceId, method, providerInfos, hashcode);
        selectorCache.put(key, selector);
    }
    return selector.select(request);
}
 
Example 9
Source File: AbstractProxyClientTransport.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 同步调用
 *
 * @param request       请求对象
 * @param timeoutMillis 超时时间(毫秒)
 * @return 返回对象
 * @throws InvocationTargetException 反射调用异常
 * @since 5.2.0
 */
protected SofaResponse doInvokeSync(SofaRequest request, int timeoutMillis)
    throws InvocationTargetException, IllegalAccessException {
    SofaResponse response = new SofaResponse();
    Method method = getMethod(request);
    if (method == null) {
        throw new SofaRpcException(RpcErrorType.CLIENT_UNDECLARED_ERROR,
            "Not found method :" + request.getInterfaceName() + "." + request.getMethodName());
    }
    Object o = method.invoke(proxy, request.getMethodArgs());
    response.setAppResponse(o);
    return response;
}
 
Example 10
Source File: TestSyncFilter.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public SofaResponse invoke(FilterInvoker invoker, SofaRequest request) throws SofaRpcException {
    interfaceName = request.getInterfaceName();
    targetServiceUniqueName = request.getTargetServiceUniqueName();
    methodName = request.getMethodName();
    invokeType = request.getInvokeType();
    targetAppName = request.getTargetAppName();
    args = request.getMethodArgs();
    return invoker.invoke(request);
}
 
Example 11
Source File: HystrixFilterAsyncTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Test
public void testHystrixCircuitBreakerFallback() throws InterruptedException {
    // 强制开启熔断
    SetterFactory setterFactory = new SetterFactory() {

        @Override
        public HystrixCommand.Setter createSetter(FilterInvoker invoker, SofaRequest request) {
            String groupKey = invoker.getConfig().getInterfaceId();
            String commandKey = request.getMethodName() + "_circuit_breaker_test";
            return HystrixCommand.Setter
                .withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey))
                .andCommandKey(HystrixCommandKey.Factory.asKey(commandKey))
                .andCommandPropertiesDefaults(
                    HystrixCommandProperties.defaultSetter().withCircuitBreakerForceOpen(true));
        }
    };

    providerConfig = defaultServer(0);
    providerConfig.export();

    consumerConfig = defaultClient()
        .setTimeout(10000);

    SofaHystrixConfig.registerFallbackFactory(consumerConfig, new HystrixServiceFallbackFactory());
    SofaHystrixConfig.registerSetterFactory(consumerConfig, setterFactory);

    HystrixService hystrixService = consumerConfig.refer();
    //wait server ok
    Thread.sleep(2000);
    for (int i = 0; i < 20; i++) {
        long start = System.currentTimeMillis();
        hystrixService.sayHello("abc", 24);
        String result = (String) SofaResponseFuture.getResponse(10000, true);
        Assert.assertTrue((System.currentTimeMillis() - start) < HYSTRIX_DEFAULT_TIMEOUT);
        Assert.assertEquals(
            "fallback abc from server! age: 24, error: java.lang.RuntimeException",
            result);
        Assert.assertTrue((System.currentTimeMillis() - start) < HYSTRIX_DEFAULT_TIMEOUT);
    }
    // 熔断时服务端不应该接收到任何请求
    Assert.assertEquals(0, ((InvokeCounterHystrixService) providerConfig.getRef()).getExecuteCount());

}
 
Example 12
Source File: HystrixFilterAsyncTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Test
public void testHystrixThreadPoolRejectedFallback() throws InterruptedException {
    // 强制开启熔断
    SetterFactory setterFactory = new SetterFactory() {

        @Override
        public HystrixCommand.Setter createSetter(FilterInvoker invoker, SofaRequest request) {
            String groupKey = invoker.getConfig().getInterfaceId() + "thread_pool_rejected";
            String commandKey = request.getMethodName() + "thread_pool_rejected";
            return HystrixCommand.Setter
                .withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey))
                .andCommandKey(HystrixCommandKey.Factory.asKey(commandKey))
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionTimeoutEnabled(false))
                .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter().withCoreSize(1));
        }
    };

    providerConfig = defaultServer(2000);
    providerConfig.export();

    consumerConfig = defaultClient()
        .setTimeout(10000);

    SofaHystrixConfig.registerFallbackFactory(consumerConfig, new HystrixServiceFallbackFactory());
    SofaHystrixConfig.registerSetterFactory(consumerConfig, setterFactory);

    HystrixService HystrixService = consumerConfig.refer();
    //wait server ok
    Thread.sleep(3000);
    for (int i = 0; i < 20; i++) {
        long start = System.currentTimeMillis();
        HystrixService.sayHello("abc", 24);
        Future future = SofaResponseFuture.getFuture();
        // 第一个请求用于阻塞线程池,其他请求会直接线程池拒绝
        if (i > 0) {
            Assert.assertTrue(future.isDone());
            String result = (String) SofaResponseFuture.getResponse(10000, true);
            Assert.assertEquals(
                "fallback abc from server! age: 24, error: java.util.concurrent.RejectedExecutionException",
                result);
            Assert.assertTrue((System.currentTimeMillis() - start) < HYSTRIX_DEFAULT_TIMEOUT);
        }
    }
    Thread.sleep(3000);
    // 只有第一个线程执行了,所以服务端只会收到一个请求
    Assert.assertEquals(1, ((InvokeCounterHystrixService) providerConfig.getRef()).getExecuteCount());

}