Search in sources :

Example 26 with SofaRpcException

use of com.alipay.sofa.rpc.core.exception.SofaRpcException in project sofa-rpc by sofastack.

the class JDKInvocationHandler method invoke.

@Override
public Object invoke(Object proxy, Method method, Object[] paramValues) throws Throwable {
    String methodName = method.getName();
    Class[] paramTypes = method.getParameterTypes();
    if ("toString".equals(methodName) && paramTypes.length == 0) {
        return proxyInvoker.toString();
    } else if ("hashCode".equals(methodName) && paramTypes.length == 0) {
        return proxyInvoker.hashCode();
    } else if ("equals".equals(methodName) && paramTypes.length == 1) {
        Object another = paramValues[0];
        return proxy == another || (proxy.getClass().isInstance(another) && proxyInvoker.equals(JDKProxy.parseInvoker(another)));
    }
    SofaRequest sofaRequest = MessageBuilder.buildSofaRequest(method.getDeclaringClass(), method, paramTypes, paramValues);
    SofaResponse response = proxyInvoker.invoke(sofaRequest);
    if (response.isError()) {
        throw new SofaRpcException(RpcErrorType.SERVER_UNDECLARED_ERROR, response.getErrorMsg());
    }
    Object ret = response.getAppResponse();
    if (ret instanceof Throwable) {
        throw (Throwable) ret;
    } else {
        if (ret == null) {
            return ClassUtils.getDefaultPrimitiveValue(method.getReturnType());
        }
        return ret;
    }
}
Also used : SofaRequest(com.alipay.sofa.rpc.core.request.SofaRequest) SofaResponse(com.alipay.sofa.rpc.core.response.SofaResponse) SofaRpcException(com.alipay.sofa.rpc.core.exception.SofaRpcException)

Example 27 with SofaRpcException

use of com.alipay.sofa.rpc.core.exception.SofaRpcException in project sofa-rpc by sofastack.

the class TestInvoker method invoke.

@Override
public SofaResponse invoke(SofaRequest request) throws SofaRpcException {
    this.request = request;
    if ("throwRPC".equals(request.getMethodName())) {
        throw new SofaRpcException(RpcErrorType.SERVER_UNDECLARED_ERROR, "xxxx");
    }
    SofaResponse response = new SofaResponse();
    try {
        Method method = TestInterface.class.getMethod(request.getMethodName(), ClassTypeUtils.getClasses(request.getMethodArgSigs()));
        Object ret = method.invoke(testInterface, request.getMethodArgs());
        response = new SofaResponse();
        response.setAppResponse(ret);
    } catch (Exception e) {
        response.setErrorMsg(e.getMessage());
    }
    return response;
}
Also used : Method(java.lang.reflect.Method) SofaResponse(com.alipay.sofa.rpc.core.response.SofaResponse) SofaRpcException(com.alipay.sofa.rpc.core.exception.SofaRpcException) SofaRpcException(com.alipay.sofa.rpc.core.exception.SofaRpcException)

Example 28 with SofaRpcException

use of com.alipay.sofa.rpc.core.exception.SofaRpcException in project sofa-rpc by sofastack.

the class AbstractCluster method doSendMsg.

/**
 * 调用客户端
 *
 * @param transport 客户端连接
 * @param request   Request对象
 * @return 调用结果
 * @throws SofaRpcException rpc异常
 */
protected SofaResponse doSendMsg(ProviderInfo providerInfo, ClientTransport transport, SofaRequest request) throws SofaRpcException {
    RpcInternalContext context = RpcInternalContext.getContext();
    // 添加调用的服务端远程地址
    RpcInternalContext.getContext().setRemoteAddress(providerInfo.getHost(), providerInfo.getPort());
    try {
        // 根据服务端版本特殊处理
        checkProviderVersion(providerInfo, request);
        String invokeType = request.getInvokeType();
        int timeout = resolveTimeout(request, consumerConfig, providerInfo);
        SofaResponse response = null;
        // 同步调用
        if (RpcConstants.INVOKER_TYPE_SYNC.equals(invokeType)) {
            long start = RpcRuntimeContext.now();
            try {
                response = transport.syncSend(request, timeout);
            } finally {
                if (RpcInternalContext.isAttachmentEnable()) {
                    long elapsed = RpcRuntimeContext.now() - start;
                    context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE, elapsed);
                }
            }
        } else // 单向调用
        if (RpcConstants.INVOKER_TYPE_ONEWAY.equals(invokeType)) {
            long start = RpcRuntimeContext.now();
            try {
                transport.oneWaySend(request, timeout);
                response = buildEmptyResponse(request);
            } finally {
                if (RpcInternalContext.isAttachmentEnable()) {
                    long elapsed = RpcRuntimeContext.now() - start;
                    context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE, elapsed);
                }
            }
        } else // Callback调用
        if (RpcConstants.INVOKER_TYPE_CALLBACK.equals(invokeType)) {
            // 调用级别回调监听器
            SofaResponseCallback sofaResponseCallback = request.getSofaResponseCallback();
            if (sofaResponseCallback == null) {
                SofaResponseCallback methodResponseCallback = consumerConfig.getMethodOnreturn(request.getMethodName());
                if (methodResponseCallback != null) {
                    // 方法的Callback
                    request.setSofaResponseCallback(methodResponseCallback);
                }
            }
            // 记录发送开始时间
            context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_SEND_TIME, RpcRuntimeContext.now());
            // 开始调用
            transport.asyncSend(request, timeout);
            response = buildEmptyResponse(request);
        } else // Future调用
        if (RpcConstants.INVOKER_TYPE_FUTURE.equals(invokeType)) {
            // 记录发送开始时间
            context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_SEND_TIME, RpcRuntimeContext.now());
            // 开始调用
            ResponseFuture future = transport.asyncSend(request, timeout);
            // 放入线程上下文
            RpcInternalContext.getContext().setFuture(future);
            response = buildEmptyResponse(request);
        } else {
            throw new SofaRpcException(RpcErrorType.CLIENT_UNDECLARED_ERROR, "Unknown invoke type:" + invokeType);
        }
        return response;
    } catch (SofaRpcException e) {
        throw e;
    } catch (Throwable e) {
        // 客户端其它异常
        throw new SofaRpcException(RpcErrorType.CLIENT_UNDECLARED_ERROR, e);
    }
}
Also used : RpcInternalContext(com.alipay.sofa.rpc.context.RpcInternalContext) SofaResponseCallback(com.alipay.sofa.rpc.core.invoke.SofaResponseCallback) ResponseFuture(com.alipay.sofa.rpc.message.ResponseFuture) SofaResponse(com.alipay.sofa.rpc.core.response.SofaResponse) SofaRpcException(com.alipay.sofa.rpc.core.exception.SofaRpcException)

Example 29 with SofaRpcException

use of com.alipay.sofa.rpc.core.exception.SofaRpcException in project sofa-rpc by sofastack.

the class AbstractCluster method invoke.

@Override
public SofaResponse invoke(SofaRequest request) throws SofaRpcException {
    SofaResponse response = null;
    try {
        // 为什么要放在这里,因为走了filter的话,就要求有地址了
        if (consumerConfig.isMock()) {
            return doMockInvoke(request);
        }
        // 做一些初始化检查,例如未连接可以连接
        checkClusterState();
        // 开始调用
        // 计数+1
        countOfInvoke.incrementAndGet();
        response = doInvoke(request);
        return response;
    } catch (SofaRpcException e) {
        // 客户端收到异常(客户端自己的异常)
        throw e;
    } finally {
        // 计数-1
        countOfInvoke.decrementAndGet();
    }
}
Also used : SofaResponse(com.alipay.sofa.rpc.core.response.SofaResponse) SofaRpcException(com.alipay.sofa.rpc.core.exception.SofaRpcException)

Example 30 with SofaRpcException

use of com.alipay.sofa.rpc.core.exception.SofaRpcException in project sofa-rpc by sofastack.

the class RestTest method testAll.

@Test
public void testAll() throws InterruptedException {
    // 只有1个线程 执行
    ServerConfig serverConfig = new ServerConfig().setStopTimeout(60000).setPort(8802).setProtocol(RpcConstants.PROTOCOL_TYPE_REST).setContextPath("/xyz");
    // .setQueues(100).setCoreThreads(1).setMaxThreads(2);
    // 发布一个服务,每个请求要执行1秒
    ProviderConfig<RestService> providerConfig = new ProviderConfig<RestService>().setInterfaceId(RestService.class.getName()).setRef(new RestServiceImpl()).setServer(serverConfig).setBootstrap("rest").setRegister(false);
    providerConfig.export();
    ConsumerConfig<RestService> consumerConfig = new ConsumerConfig<RestService>().setInterfaceId(RestService.class.getName()).setDirectUrl("rest://127.0.0.1:8802/xyz?uniqueId=&version=1.0&timeout=0&delay=-1&id=rpc-cfg-0&dynamic=true&weight=100&accepts=100000&startTime=1523240755024&appName=test-server&pid=22385&language=java&rpcVer=50300").setProtocol("rest").setBootstrap("rest").setTimeout(30000).setConnectionNum(5).setRegister(false);
    final RestService helloService = consumerConfig.refer();
    Assert.assertEquals(helloService.query(11), "hello world !null");
    int times = 5;
    final CountDownLatch latch = new CountDownLatch(times);
    final AtomicInteger count = new AtomicInteger();
    // 瞬间发起5个请求,那么服务端肯定在排队
    for (int i = 0; i < times; i++) {
        Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    helloService.add(22, "xxx");
                    count.incrementAndGet();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    latch.countDown();
                }
            }
        }, "thread" + i);
        thread.start();
        LOGGER.info("send " + i);
        try {
            Thread.sleep(200);
        } catch (Exception ignore) {
        }
    }
    latch.await(3, TimeUnit.SECONDS);
    // 应该执行了5个请求
    Assert.assertTrue(count.get() == 5);
    Assert.assertEquals(helloService.add(11, "yyy"), "create ok !11");
    Assert.assertEquals(helloService.query(11), "hello world !yyy");
    Assert.assertEquals(helloService.query(11, "xxx"), "hello world !yyy");
    Assert.assertEquals(helloService.update(11, "xxx").readEntity(String.class), "update ok !11");
    Assert.assertEquals(helloService.query(11), "hello world !xxx");
    Assert.assertEquals(helloService.delete(11), "xxx");
    boolean error = false;
    try {
        helloService.error("11");
    } catch (Exception e) {
        error = true;
        Assert.assertTrue(e instanceof SofaRpcException);
    }
    Assert.assertTrue(error);
    ExampleObj obj = new ExampleObj();
    obj.setId(11);
    obj.setName("name");
    ExampleObj serverobk = helloService.object(obj);
    Assert.assertEquals(serverobk.getId(), obj.getId());
    Assert.assertEquals(serverobk.getName(), obj.getName() + " server");
    ExampleObj obj2 = new ExampleObj();
    obj2.setId(22);
    obj2.setName("name22");
    List<ExampleObj> objs = helloService.objects(Arrays.asList(obj, obj2));
    Assert.assertEquals(objs.size(), 2);
    Assert.assertEquals(objs.get(1).getId(), obj2.getId());
    Assert.assertEquals(objs.get(1).getName(), obj2.getName() + " server");
    Assert.assertEquals(helloService.get("zzz"), "serverzzz");
    Assert.assertEquals(helloService.post("zzz", "boddddy"), "server zzzboddddy");
    providerConfig.unExport();
}
Also used : CountDownLatch(java.util.concurrent.CountDownLatch) SofaRpcException(com.alipay.sofa.rpc.core.exception.SofaRpcException) SofaRpcException(com.alipay.sofa.rpc.core.exception.SofaRpcException) ServerConfig(com.alipay.sofa.rpc.config.ServerConfig) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.junit.Test) ActivelyDestroyTest(com.alipay.sofa.rpc.test.ActivelyDestroyTest)

Aggregations

SofaRpcException (com.alipay.sofa.rpc.core.exception.SofaRpcException)91 Test (org.junit.Test)35 RequestBase (com.alipay.sofa.rpc.core.request.RequestBase)28 SofaResponseCallback (com.alipay.sofa.rpc.core.invoke.SofaResponseCallback)27 ServerConfig (com.alipay.sofa.rpc.config.ServerConfig)24 ActivelyDestroyTest (com.alipay.sofa.rpc.test.ActivelyDestroyTest)23 SofaTimeOutException (com.alipay.sofa.rpc.core.exception.SofaTimeOutException)22 ConsumerConfig (com.alipay.sofa.rpc.config.ConsumerConfig)21 CountDownLatch (java.util.concurrent.CountDownLatch)20 SofaResponse (com.alipay.sofa.rpc.core.response.SofaResponse)19 ProviderConfig (com.alipay.sofa.rpc.config.ProviderConfig)16 HelloService (com.alipay.sofa.rpc.test.HelloService)16 RpcInvokeContext (com.alipay.sofa.rpc.context.RpcInvokeContext)15 ApplicationConfig (com.alipay.sofa.rpc.config.ApplicationConfig)14 RpcInternalContext (com.alipay.sofa.rpc.context.RpcInternalContext)14 SofaRequest (com.alipay.sofa.rpc.core.request.SofaRequest)11 HelloServiceImpl (com.alipay.sofa.rpc.test.HelloServiceImpl)11 HashMap (java.util.HashMap)9 Filter (com.alipay.sofa.rpc.filter.Filter)8 InvokeTimeoutException (com.alipay.remoting.rpc.exception.InvokeTimeoutException)7