Search in sources :

Example 1 with Invoker

use of com.alipay.sofa.rpc.invoke.Invoker in project sofa-rpc by sofastack.

the class BoltConsumerBootstrapTest method testAttrUpdate.

@Test
public void testAttrUpdate() {
    // 发布一个服务
    ServerConfig serverConfig0 = new ServerConfig().setStopTimeout(0).setPort(22224).setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT).setQueues(100).setCoreThreads(5).setMaxThreads(5);
    ProviderConfig<HelloService> providerConfig0 = new ProviderConfig<HelloService>().setId("p-0").setInterfaceId(HelloService.class.getName()).setUniqueId("attr").setRef(new HelloServiceImpl(1000)).setServer(serverConfig0).setRepeatedExportLimit(5);
    providerConfig0.export();
    ConsumerConfig<HelloService> consumerConfig0 = new ConsumerConfig<HelloService>().setInterfaceId(HelloService.class.getName()).setUniqueId("attr").setProxy("jdk").setDirectUrl("bolt://127.0.0.1:22224").setTimeout(500);
    HelloService proxy = consumerConfig0.refer();
    Invoker invoker = JDKProxy.parseInvoker(proxy);
    Cluster cluster = consumerConfig0.getConsumerBootstrap().getCluster();
    boolean error = false;
    try {
        proxy.sayHello("11", 11);
    } catch (Exception e) {
        LOGGER.info(e.getMessage());
        error = true;
    }
    Assert.assertTrue(error);
    // wrong key
    error = false;
    try {
        consumerConfig0.getConfigListener().attrUpdated(Collections.singletonMap("loadbalance", "asdasd"));
    } catch (Exception e) {
        error = true;
    }
    Assert.assertFalse(error);
    // wrong value
    error = false;
    try {
        consumerConfig0.getConfigListener().attrUpdated(Collections.singletonMap("loadBalancer", "asdasd"));
    } catch (Exception e) {
        error = true;
    }
    Assert.assertFalse(error);
    // 动态加大超时时间
    consumerConfig0.getConfigListener().attrUpdated(Collections.singletonMap("timeout", "2000"));
    Invoker invoker2 = JDKProxy.parseInvoker(proxy);
    Cluster cluster2 = consumerConfig0.getConsumerBootstrap().getCluster();
    error = false;
    try {
        proxy.sayHello("11", 11);
    } catch (Exception e) {
        e.printStackTrace();
        error = true;
    }
    Assert.assertFalse(error);
    Assert.assertTrue(invoker == invoker2);
    Assert.assertTrue(cluster != cluster2);
    // 切到一个没有的分组
    consumerConfig0.getConfigListener().attrUpdated(Collections.singletonMap("uniqueId", "attr2"));
    error = false;
    try {
        proxy.sayHello("11", 11);
    } catch (Exception e) {
        error = true;
    }
    Assert.assertTrue(error);
    // 切到一个有的分组
    consumerConfig0.getConfigListener().attrUpdated(Collections.singletonMap("uniqueId", "attr"));
    error = false;
    try {
        proxy.sayHello("11", 11);
    } catch (Exception e) {
        error = true;
    }
    Assert.assertFalse(error);
}
Also used : ServerConfig(com.alipay.sofa.rpc.config.ServerConfig) Invoker(com.alipay.sofa.rpc.invoke.Invoker) ProviderConfig(com.alipay.sofa.rpc.config.ProviderConfig) HelloService(com.alipay.sofa.rpc.test.HelloService) Cluster(com.alipay.sofa.rpc.client.Cluster) HelloServiceImpl(com.alipay.sofa.rpc.test.HelloServiceImpl) SofaRpcRuntimeException(com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException) Test(org.junit.Test) ActivelyDestroyTest(com.alipay.sofa.rpc.test.ActivelyDestroyTest)

Example 2 with Invoker

use of com.alipay.sofa.rpc.invoke.Invoker in project sofa-rpc by sofastack.

the class BoltServerProcessor method handleRequest.

@Override
public void handleRequest(BizContext bizCtx, AsyncContext asyncCtx, SofaRequest request) {
    // RPC内置上下文
    RpcInternalContext context = RpcInternalContext.getContext();
    context.setProviderSide(true);
    String appName = request.getTargetAppName();
    if (appName == null) {
        // 默认全局appName
        appName = (String) RpcRuntimeContext.get(RpcRuntimeContext.KEY_APPNAME);
    }
    // 是否链路异步化中
    boolean isAsyncChain = false;
    try {
        // 这个 try-finally 为了保证Context一定被清理
        // 统计值加1
        processingCount.incrementAndGet();
        // 远程地址
        context.setRemoteAddress(bizCtx.getRemoteHost(), bizCtx.getRemotePort());
        // 远程返回的通道
        context.setAttachment(RpcConstants.HIDDEN_KEY_ASYNC_CONTEXT, asyncCtx);
        InvokeContext boltInvokeCtx = bizCtx.getInvokeContext();
        if (RpcInternalContext.isAttachmentEnable()) {
            if (boltInvokeCtx != null) {
                // rpc线程池等待时间 Long
                putToContextIfNotNull(boltInvokeCtx, InvokeContext.BOLT_PROCESS_WAIT_TIME, context, RpcConstants.INTERNAL_KEY_PROCESS_WAIT_TIME);
            }
        }
        putToContext(boltInvokeCtx);
        if (EventBus.isEnable(ServerReceiveEvent.class)) {
            EventBus.post(new ServerReceiveEvent(request));
        }
        // 开始处理
        // 响应,用于返回
        SofaResponse response = null;
        // 异常,用于记录
        Throwable throwable = null;
        ProviderConfig providerConfig = null;
        String serviceName = request.getTargetServiceUniqueName();
        try {
            // 这个try-catch 保证一定有Response
            invoke: {
                if (!boltServer.isStarted()) {
                    // 服务端已关闭
                    throwable = new SofaRpcException(RpcErrorType.SERVER_CLOSED, LogCodes.getLog(LogCodes.WARN_PROVIDER_STOPPED, SystemInfo.getLocalHost() + ":" + boltServer.serverConfig.getPort()));
                    response = MessageBuilder.buildSofaErrorResponse(throwable.getMessage());
                    break invoke;
                }
                if (bizCtx.isRequestTimeout()) {
                    // 加上丢弃超时的请求的逻辑
                    throwable = clientTimeoutWhenReceiveRequest(appName, serviceName, bizCtx.getRemoteAddress());
                    break invoke;
                }
                // 查找服务
                Invoker invoker = boltServer.findInvoker(serviceName);
                if (invoker == null) {
                    throwable = cannotFoundService(appName, serviceName);
                    response = MessageBuilder.buildSofaErrorResponse(throwable.getMessage());
                    break invoke;
                }
                if (invoker instanceof ProviderProxyInvoker) {
                    providerConfig = ((ProviderProxyInvoker) invoker).getProviderConfig();
                    // 找到服务后,打印服务的appName
                    appName = providerConfig != null ? providerConfig.getAppName() : null;
                }
                // 查找方法
                String methodName = request.getMethodName();
                Method serviceMethod = ReflectCache.getOverloadMethodCache(serviceName, methodName, request.getMethodArgSigs());
                if (serviceMethod == null) {
                    throwable = cannotFoundServiceMethod(appName, methodName, serviceName);
                    response = MessageBuilder.buildSofaErrorResponse(throwable.getMessage());
                    break invoke;
                } else {
                    request.setMethod(serviceMethod);
                }
                // 真正调用
                response = doInvoke(serviceName, invoker, request);
                if (bizCtx.isRequestTimeout()) {
                    // 加上丢弃超时的响应的逻辑
                    throwable = clientTimeoutWhenSendResponse(appName, serviceName, bizCtx.getRemoteAddress());
                    break invoke;
                }
            }
        } catch (Exception e) {
            // 服务端异常,不管是啥异常
            LOGGER.errorWithApp(appName, "Server Processor Error!", e);
            throwable = e;
            response = MessageBuilder.buildSofaErrorResponse(e.getMessage());
        }
        // Response不为空,代表需要返回给客户端
        if (response != null) {
            RpcInvokeContext invokeContext = RpcInvokeContext.peekContext();
            isAsyncChain = CommonUtils.isTrue(invokeContext != null ? (Boolean) invokeContext.remove(RemotingConstants.INVOKE_CTX_IS_ASYNC_CHAIN) : null);
            // 如果是服务端异步代理模式,特殊处理,因为该模式是在业务代码自主异步返回的
            if (!isAsyncChain) {
                // 其它正常请求
                try {
                    // 这个try-catch 保证一定要记录tracer
                    asyncCtx.sendResponse(response);
                } finally {
                    if (EventBus.isEnable(ServerSendEvent.class)) {
                        EventBus.post(new ServerSendEvent(request, response, throwable));
                    }
                }
            }
        }
    } catch (Throwable e) {
        // 可能有返回时的异常
        if (LOGGER.isErrorEnabled(appName)) {
            LOGGER.errorWithApp(appName, e.getMessage(), e);
        }
    } finally {
        processingCount.decrementAndGet();
        if (!isAsyncChain) {
            if (EventBus.isEnable(ServerEndHandleEvent.class)) {
                EventBus.post(new ServerEndHandleEvent());
            }
        }
        RpcInvokeContext.removeContext();
        RpcInternalContext.removeAllContext();
    }
}
Also used : InvokeContext(com.alipay.remoting.InvokeContext) RpcInvokeContext(com.alipay.sofa.rpc.context.RpcInvokeContext) RpcInvokeContext(com.alipay.sofa.rpc.context.RpcInvokeContext) ServerSendEvent(com.alipay.sofa.rpc.event.ServerSendEvent) ProviderConfig(com.alipay.sofa.rpc.config.ProviderConfig) RpcInternalContext(com.alipay.sofa.rpc.context.RpcInternalContext) ServerEndHandleEvent(com.alipay.sofa.rpc.event.ServerEndHandleEvent) Method(java.lang.reflect.Method) SofaRpcException(com.alipay.sofa.rpc.core.exception.SofaRpcException) SofaRpcException(com.alipay.sofa.rpc.core.exception.SofaRpcException) ProviderProxyInvoker(com.alipay.sofa.rpc.server.ProviderProxyInvoker) Invoker(com.alipay.sofa.rpc.invoke.Invoker) ProviderProxyInvoker(com.alipay.sofa.rpc.server.ProviderProxyInvoker) ServerReceiveEvent(com.alipay.sofa.rpc.event.ServerReceiveEvent) SofaResponse(com.alipay.sofa.rpc.core.response.SofaResponse)

Example 3 with Invoker

use of com.alipay.sofa.rpc.invoke.Invoker in project sofa-rpc by sofastack.

the class JavassistProxy method getProxy.

@Override
@SuppressWarnings("unchecked")
public <T> T getProxy(Class<T> interfaceClass, Invoker proxyInvoker) {
    StringBuilder debug = null;
    if (LOGGER.isDebugEnabled()) {
        debug = new StringBuilder();
    }
    try {
        Class clazz = PROXY_CLASS_MAP.get(interfaceClass);
        if (clazz == null) {
            // 生成代理类
            String interfaceName = ClassTypeUtils.getTypeStr(interfaceClass);
            ClassPool mPool = ClassPool.getDefault();
            mPool.appendClassPath(new LoaderClassPath(ClassLoaderUtils.getClassLoader(JavassistProxy.class)));
            CtClass mCtc = mPool.makeClass(interfaceName + "_proxy_" + counter.getAndIncrement());
            if (interfaceClass.isInterface()) {
                mCtc.addInterface(mPool.get(interfaceName));
            } else {
                throw new IllegalArgumentException(interfaceClass.getName() + " is not an interface");
            }
            // 继承 java.lang.reflect.Proxy
            mCtc.setSuperclass(mPool.get(java.lang.reflect.Proxy.class.getName()));
            CtConstructor constructor = new CtConstructor(null, mCtc);
            constructor.setModifiers(Modifier.PUBLIC);
            constructor.setBody("{super(new " + UselessInvocationHandler.class.getName() + "());}");
            mCtc.addConstructor(constructor);
            List<String> fieldList = new ArrayList<String>();
            List<String> methodList = new ArrayList<String>();
            fieldList.add("public " + Invoker.class.getCanonicalName() + " proxyInvoker = null;");
            createMethod(interfaceClass, fieldList, methodList);
            for (String fieldStr : fieldList) {
                if (LOGGER.isDebugEnabled()) {
                    debug.append(fieldStr).append("\n");
                }
                mCtc.addField(CtField.make(fieldStr, mCtc));
            }
            for (String methodStr : methodList) {
                if (LOGGER.isDebugEnabled()) {
                    debug.append(methodStr).append("\n");
                }
                mCtc.addMethod(CtMethod.make(methodStr, mCtc));
            }
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("javassist proxy of interface: {} \r\n{}", interfaceClass, debug != null ? debug.toString() : "");
            }
            clazz = mCtc.toClass();
            PROXY_CLASS_MAP.put(interfaceClass, clazz);
        }
        Object instance = clazz.newInstance();
        clazz.getField("proxyInvoker").set(instance, proxyInvoker);
        return (T) instance;
    } catch (Exception e) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("javassist proxy of interface: {} \r\n{}", interfaceClass, debug != null ? debug.toString() : "");
        }
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_PROXY_CONSTRUCT, "javassist"), e);
    }
}
Also used : ClassPool(javassist.ClassPool) ArrayList(java.util.ArrayList) LoaderClassPath(javassist.LoaderClassPath) SofaRpcException(com.alipay.sofa.rpc.core.exception.SofaRpcException) SofaRpcRuntimeException(com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException) CtConstructor(javassist.CtConstructor) CtClass(javassist.CtClass) Invoker(com.alipay.sofa.rpc.invoke.Invoker) SofaRpcRuntimeException(com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException) CtClass(javassist.CtClass)

Example 4 with Invoker

use of com.alipay.sofa.rpc.invoke.Invoker in project sofa-rpc by sofastack.

the class ProxyFactoryTest method getInvoker.

@Test
public void getInvoker() {
    Invoker invoke = ProxyFactory.getInvoker(null, "test");
    Assert.assertEquals(invoke, null);
}
Also used : Invoker(com.alipay.sofa.rpc.invoke.Invoker) Test(org.junit.Test)

Example 5 with Invoker

use of com.alipay.sofa.rpc.invoke.Invoker in project sofa-rpc by sofastack.

the class TempClassLoader method testAttrUpdate.

@Test
public void testAttrUpdate() {
    // 发布一个服务
    ServerConfig serverConfig0 = new ServerConfig().setStopTimeout(0).setPort(22224).setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT).setQueues(100).setCoreThreads(5).setMaxThreads(5);
    ProviderConfig<HelloService> providerConfig0 = new ProviderConfig<HelloService>().setId("p-0").setInterfaceId(HelloService.class.getName()).setUniqueId("attr").setRef(new HelloServiceImpl()).setServer(serverConfig0).setRepeatedExportLimit(5);
    providerConfig0.export();
    ConsumerConfig<HelloService> consumerConfig0 = new ConsumerConfig<HelloService>().setInterfaceId(HelloService.class.getName()).setUniqueId("attr").setProxy("jdk").setDirectUrl("bolt://127.0.0.1:22224").setTimeout(500);
    HelloService proxy = consumerConfig0.refer();
    Invoker invoker = JDKProxy.parseInvoker(proxy);
    Cluster cluster = consumerConfig0.getConsumerBootstrap().getCluster();
    boolean error = false;
    try {
        proxy.sayHello("11", 11);
    } catch (Exception e) {
        error = true;
    }
    Assert.assertFalse(error);
    // wrong key
    error = false;
    try {
        providerConfig0.getConfigListener().attrUpdated(Collections.singletonMap("weighttttt", "asdasd"));
    } catch (Exception e) {
        error = true;
    }
    Assert.assertFalse(error);
    // wrong value
    error = false;
    try {
        providerConfig0.getConfigListener().attrUpdated(Collections.singletonMap("weight", "asdasd"));
    } catch (Exception e) {
        error = true;
    }
    Assert.assertFalse(error);
    // 切到一个没有的分组
    providerConfig0.getConfigListener().attrUpdated(Collections.singletonMap("uniqueId", "attr2"));
    // 切到一个有的分组
    error = false;
    try {
        proxy.sayHello("11", 11);
    } catch (Exception e) {
        error = true;
    }
    Assert.assertTrue(error);
    // 切到一个有的分组
    providerConfig0.getConfigListener().attrUpdated(Collections.singletonMap("uniqueId", "attr"));
    error = false;
    try {
        proxy.sayHello("11", 11);
    } catch (Exception e) {
        error = true;
    }
    Assert.assertFalse(error);
}
Also used : ServerConfig(com.alipay.sofa.rpc.config.ServerConfig) Invoker(com.alipay.sofa.rpc.invoke.Invoker) ProviderConfig(com.alipay.sofa.rpc.config.ProviderConfig) HelloService(com.alipay.sofa.rpc.test.HelloService) Cluster(com.alipay.sofa.rpc.client.Cluster) HelloServiceImpl(com.alipay.sofa.rpc.test.HelloServiceImpl) SofaRpcRuntimeException(com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException) Test(org.junit.Test) ActivelyDestroyTest(com.alipay.sofa.rpc.test.ActivelyDestroyTest)

Aggregations

Invoker (com.alipay.sofa.rpc.invoke.Invoker)7 ProviderConfig (com.alipay.sofa.rpc.config.ProviderConfig)4 SofaRpcException (com.alipay.sofa.rpc.core.exception.SofaRpcException)3 SofaRpcRuntimeException (com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException)3 Test (org.junit.Test)3 Cluster (com.alipay.sofa.rpc.client.Cluster)2 ServerConfig (com.alipay.sofa.rpc.config.ServerConfig)2 RpcInternalContext (com.alipay.sofa.rpc.context.RpcInternalContext)2 SofaResponse (com.alipay.sofa.rpc.core.response.SofaResponse)2 ServerEndHandleEvent (com.alipay.sofa.rpc.event.ServerEndHandleEvent)2 ServerReceiveEvent (com.alipay.sofa.rpc.event.ServerReceiveEvent)2 ServerSendEvent (com.alipay.sofa.rpc.event.ServerSendEvent)2 ProviderProxyInvoker (com.alipay.sofa.rpc.server.ProviderProxyInvoker)2 ActivelyDestroyTest (com.alipay.sofa.rpc.test.ActivelyDestroyTest)2 HelloService (com.alipay.sofa.rpc.test.HelloService)2 HelloServiceImpl (com.alipay.sofa.rpc.test.HelloServiceImpl)2 Method (java.lang.reflect.Method)2 InvokeContext (com.alipay.remoting.InvokeContext)1 Serializer (com.alipay.sofa.rpc.codec.Serializer)1 StringSerializer (com.alipay.sofa.rpc.codec.common.StringSerializer)1