com.alipay.sofa.rpc.common.RpcConstants Java Examples

The following examples show how to use com.alipay.sofa.rpc.common.RpcConstants. 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: Http2ClientInitializer.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) throws Exception {
    final Http2Connection connection = new DefaultHttp2Connection(false);
    connectionHandler = new HttpToHttp2ConnectionHandlerBuilder()
        .frameListener(
            new DelegatingDecompressorFrameListener(connection, new InboundHttp2ToHttpAdapterBuilder(connection)
                .maxContentLength(transportConfig.getPayload()).propagateSettings(true).build()))
        .connection(connection).build();
    responseHandler = new Http2ClientChannelHandler();
    settingsHandler = new Http2SettingsHandler(ch.newPromise());
    String protocol = transportConfig.getProviderInfo().getProtocolType();
    if (RpcConstants.PROTOCOL_TYPE_H2.equals(protocol)) {
        configureSsl(ch);
    } else if (RpcConstants.PROTOCOL_TYPE_H2C.equals(protocol)) {
        if (!useH2cPriorKnowledge) {
            configureClearTextWithHttpUpgrade(ch);
        } else {
            configureClearTextWithPriorKnowledge(ch);
        }
    }
}
 
Example #2
Source File: SofaRpcSerialization.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 客户端记录响应反序列化大小和响应反序列化耗时
 *
 * @param responseCommand 响应体
 */
private void recordDeserializeResponse(RpcResponseCommand responseCommand, InvokeContext invokeContext) {
    if (!RpcInternalContext.isAttachmentEnable()) {
        return;
    }
    RpcInternalContext context = null;
    if (invokeContext != null) {
        // 客户端异步调用的情况下,上下文会放在InvokeContext中传递
        context = invokeContext.get(RemotingConstants.INVOKE_CTX_RPC_CTX);
    }
    if (context == null) {
        context = RpcInternalContext.getContext();
    }
    int cost = context.getStopWatch().tick().read();
    int respSize = RpcProtocol.getResponseHeaderLength()
        + responseCommand.getClazzLength()
        + responseCommand.getContentLength()
        + responseCommand.getHeaderLength();
    // 记录响应反序列化大小和响应反序列化耗时
    context.setAttachment(RpcConstants.INTERNAL_KEY_RESP_SIZE, respSize);
    context.setAttachment(RpcConstants.INTERNAL_KEY_RESP_DESERIALIZE_TIME, cost);
}
 
Example #3
Source File: BoltClientTransport.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * For convert provider to bolt url.
 *
 * @param transportConfig ClientTransportConfig
 * @param providerInfo    ProviderInfo
 * @return Bolt Url
 */
protected Url convertProviderToUrl(ClientTransportConfig transportConfig, ProviderInfo providerInfo) {
    // Url的第一个参数,如果不用事件的话,其实无所谓
    Url boltUrl = new Url(providerInfo.toString(), providerInfo.getHost(), providerInfo.getPort());

    boltUrl.setConnectTimeout(transportConfig.getConnectTimeout());
    // 默认初始化connNum个长连接,为了slb和vip的情况
    final int connectionNum = transportConfig.getConnectionNum();
    if (connectionNum > 0) {
        boltUrl.setConnNum(connectionNum);
    } else {
        boltUrl.setConnNum(1);
    }
    boltUrl.setConnWarmup(false); // true的话
    if (RpcConstants.PROTOCOL_TYPE_BOLT.equals(providerInfo.getProtocolType())) {
        boltUrl.setProtocol(RemotingConstants.PROTOCOL_BOLT);
    } else {
        boltUrl.setProtocol(RemotingConstants.PROTOCOL_TR);
    }
    return boltUrl;
}
 
Example #4
Source File: AbstractInvokeCallbackTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Test
public void testRecordClientElapseTime() {
    BoltInvokerCallback invokerCallback = new BoltInvokerCallback(null, null,
        null, null, null, null);
    invokerCallback.recordClientElapseTime();
    Long elapse = (Long) RpcInternalContext.getContext().getAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE);
    Assert.assertNull(elapse);

    RpcInternalContext context = RpcInternalContext.getContext();
    invokerCallback = new BoltInvokerCallback(null, null,
        null, null, context, null);
    invokerCallback.recordClientElapseTime();
    elapse = (Long) context.getAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE);
    Assert.assertNull(elapse);

    context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_SEND_TIME, RpcRuntimeContext.now() - 1000);
    invokerCallback.recordClientElapseTime();
    elapse = (Long) context.getAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE);
    Assert.assertNotNull(elapse);
}
 
Example #5
Source File: SofaRpcSerialization.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 客户端记录序列化请求的耗时和
 *
 * @param requestCommand 请求对象
 */
protected void recordSerializeRequest(RequestCommand requestCommand, InvokeContext invokeContext) {
    if (!RpcInternalContext.isAttachmentEnable()) {
        return;
    }
    RpcInternalContext context = null;
    if (invokeContext != null) {
        // 客户端异步调用的情况下,上下文会放在InvokeContext中传递
        context = invokeContext.get(RemotingConstants.INVOKE_CTX_RPC_CTX);
    }
    if (context == null) {
        context = RpcInternalContext.getContext();
    }
    int cost = context.getStopWatch().tick().read();
    int requestSize = RpcProtocol.getRequestHeaderLength()
        + requestCommand.getClazzLength()
        + requestCommand.getContentLength()
        + requestCommand.getHeaderLength();
    // 记录请求序列化大小和请求序列化耗时
    context.setAttachment(RpcConstants.INTERNAL_KEY_REQ_SIZE, requestSize);
    context.setAttachment(RpcConstants.INTERNAL_KEY_REQ_SERIALIZE_TIME, cost);
}
 
Example #6
Source File: SingleGroupAddressHolder.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public void updateAllProviders(List<ProviderGroup> providerGroups) {
    ConcurrentHashSet<ProviderInfo> tmpDirectUrl = new ConcurrentHashSet<ProviderInfo>();
    ConcurrentHashSet<ProviderInfo> tmpRegistry = new ConcurrentHashSet<ProviderInfo>();
    for (ProviderGroup providerGroup : providerGroups) {
        if (!ProviderHelper.isEmpty(providerGroup)) {
            if (RpcConstants.ADDRESS_DIRECT_GROUP.equals(providerGroup.getName())) {
                tmpDirectUrl.addAll(providerGroup.getProviderInfos());
            } else {
                tmpRegistry.addAll(providerGroup.getProviderInfos());
            }
        }
    }
    wLock.lock();
    try {
        this.directUrlGroup.setProviderInfos(new ArrayList<ProviderInfo>(tmpDirectUrl));
        this.registryGroup.setProviderInfos(new ArrayList<ProviderInfo>(tmpRegistry));
    } finally {
        wLock.unlock();
    }
}
 
Example #7
Source File: BoltExceptionTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Test
public void testAll() {

    final String directUrl = "bolt://127.0.0.1:12300";
    final ConsumerConfig<HelloService> consumerConfig = new ConsumerConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setDirectUrl(directUrl)
        .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT)
        .setBootstrap("bolt")
        .setApplication(new ApplicationConfig().setAppName("clientApp"))
        .setReconnectPeriod(1000);

    HelloService helloService = consumerConfig.refer();

    // 关闭后再调用一个抛异常
    try {
        helloService.sayHello("xx", 22);
    } catch (Exception e) {
        // 应该抛出异常
        Assert.assertTrue(e instanceof SofaRouteException);

        Assert.assertTrue(e.getMessage().contains(directUrl));
    }
}
 
Example #8
Source File: Http2ServerTask.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
private void sendHttp2Response0(HttpResponseStatus status, boolean error, ByteBuf data) {
    Http2Headers headers = new DefaultHttp2Headers().status(status.codeAsText());

    if (request.getSerializeType() > 0) {
        String serialization = SerializerFactory.getAliasByCode(request.getSerializeType());
        headers.set(RemotingConstants.HEAD_SERIALIZE_TYPE, serialization);
    } else {
        headers.set(CONTENT_TYPE, "text/plain; charset=" + RpcConstants.DEFAULT_CHARSET.displayName());
    }
    if (error) {
        headers.set(RemotingConstants.HEAD_RESPONSE_ERROR, "true");
    }
    if (data != null) {
        encoder.writeHeaders(ctx, streamId, headers, 0, false, ctx.newPromise());
        encoder.writeData(ctx, streamId, data, 0, true, ctx.newPromise());
    } else {
        encoder.writeHeaders(ctx, streamId, headers, 0, true, ctx.newPromise());
    }
}
 
Example #9
Source File: LocalRegistryTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
public void notifyConsumerTest() {
    LocalRegistry registry = new LocalRegistry(new RegistryConfig());
    ConsumerConfig<?> consumer = new ConsumerConfig();
    consumer.setInterfaceId("test");
    LocalRegistryTest.MockProviderInfoListener providerInfoListener = new LocalRegistryTest.MockProviderInfoListener();
    consumer.setProviderInfoListener(providerInfoListener);
    registry.subscribe(consumer);
    String key = LocalRegistryHelper.buildListDataId(consumer, consumer.getProtocol());

    registry.memoryCache.put(key, new ProviderGroup());

    Map<String, ProviderGroup> newCache = new HashMap<String, ProviderGroup>();
    ProviderGroup newProviderGroup = new ProviderGroup();
    ProviderInfo providerInfo = new ProviderInfo().setHost("0.0.0.0");
    newProviderGroup.add(providerInfo);
    newCache.put(key, newProviderGroup);

    registry.notifyConsumer(newCache);

    Map<String, ProviderGroup> ps = providerInfoListener.getData();
    Assert.assertTrue(ps.size() > 0);
    Assert.assertNotNull(ps.get(RpcConstants.ADDRESS_DEFAULT_GROUP));
    Assert.assertTrue(ps.get(RpcConstants.ADDRESS_DEFAULT_GROUP).size() == 1);
}
 
Example #10
Source File: NacosRegistryHelper.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
private static String convertInstanceToUrl(Instance instance) {
    Map<String, String> metaData = instance.getMetadata();
    if (metaData == null) {
        metaData = new HashMap<String, String>();
    }
    String uri = "";
    String protocol = metaData.get(RpcConstants.CONFIG_KEY_PROTOCOL);
    if (StringUtils.isNotEmpty(protocol)) {
        uri = protocol + "://";
    }
    uri += instance.getIp() + ":" + instance.getPort();

    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, String> entry : metaData.entrySet()) {
        sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
    }
    if (sb.length() > 0) {
        uri += sb.replace(0, 1, "?").toString();
    }
    return uri;
}
 
Example #11
Source File: InvocationStatDimensionStatTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Test
public void testFuture() throws SofaRpcException, ExecutionException, InterruptedException {

    consumerConfig.setInvokeType(RpcConstants.INVOKER_TYPE_FUTURE);

    consumerConfig.unRefer();
    helloService = consumerConfig.refer();

    for (int i = 0; i < 5; i++) {
        helloService.sayHello("liangen");
        try {
            RpcInvokeContext.getContext().getFuture().get();
        } catch (Exception e) {
            LOGGER.info("future超时");
        }
    }
    Thread.sleep(1000);

    final ProviderInfo providerInfo = getProviderInfoByHost(consumerConfig, "127.0.0.1");
    InvocationStatDimension statDimension = new InvocationStatDimension(providerInfo, consumerConfig);
    InvocationStat invocationStat = InvocationStatFactory.getInvocationStat(statDimension);
    Assert.assertEquals(5, delayGetCount(invocationStat, 5));

    InvocationStatFactory.removeInvocationStat(invocationStat);

}
 
Example #12
Source File: LazyConnectTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void startServer() {

    RpcRunningState.setUnitTestMode(true);
    // 只有2个线程 执行
    serverConfig = new ServerConfig()
        .setStopTimeout(0)
        .setPort(22222)
        .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT)
        .setQueues(100).setCoreThreads(5).setMaxThreads(5);

    // 发布一个服务,每个请求要执行1秒
    ProviderConfig<HelloService> providerConfig = new ProviderConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setRef(new HelloServiceImpl())
        .setServer(serverConfig)
        .setRegister(false);
    providerConfig.export();
}
 
Example #13
Source File: TraceClientRequestFilter.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
    try {

        if (RpcInternalContext.isAttachmentEnable()) {
            // 补充客户端request长度
            RpcInternalContext context = RpcInternalContext.getContext();
            context.setAttachment(RpcConstants.INTERNAL_KEY_REQ_SIZE,
                requestContext.getHeaderString(HttpHeaders.CONTENT_LENGTH));

        }

        RestTracerAdapter.beforeSend(requestContext);
    } catch (Exception e) {
        logger.error(LogCodes.getLog(LogCodes.ERROR_TRACER_UNKNOWN_EXP, "filter", "rest", "client"), e);
    }
}
 
Example #14
Source File: RegistryUtils.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * Convert consumer to url.
 *
 * @param consumerConfig the ConsumerConfig
 * @return the url list
 */
public static String convertConsumerToUrl(ConsumerConfig consumerConfig) {
    StringBuilder sb = new StringBuilder(200);
    String host = SystemInfo.getLocalHost();
    //noinspection unchecked
    sb.append(consumerConfig.getProtocol()).append("://").append(host).append("?version=1.0")
        .append(getKeyPairs(RpcConstants.CONFIG_KEY_UNIQUEID, consumerConfig.getUniqueId()))
        .append(getKeyPairs(RpcConstants.CONFIG_KEY_PID, RpcRuntimeContext.PID))
        .append(getKeyPairs(RpcConstants.CONFIG_KEY_TIMEOUT, consumerConfig.getTimeout()))
        .append(getKeyPairs(RpcConstants.CONFIG_KEY_ID, consumerConfig.getId()))
        .append(getKeyPairs(RpcConstants.CONFIG_KEY_GENERIC, consumerConfig.isGeneric()))
        .append(getKeyPairs(RpcConstants.CONFIG_KEY_INTERFACE, consumerConfig.getInterfaceId()))
        .append(getKeyPairs(RpcConstants.CONFIG_KEY_APP_NAME, consumerConfig.getAppName()))
        .append(getKeyPairs(RpcConstants.CONFIG_KEY_SERIALIZATION,
            consumerConfig.getSerialization()))
        .append(getKeyPairs(ProviderInfoAttrs.ATTR_START_TIME, RpcRuntimeContext.now()))
        .append(convertMap2Pair(consumerConfig.getParameters()));
    addCommonAttrs(sb);
    return sb.toString();
}
 
Example #15
Source File: SofaRpcMetrics.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
private void onEvent(ClientEndInvokeEvent event) {
    InvokeMeta meta = new InvokeMeta(
        event.getRequest(),
        event.getResponse(),
        getLongAvoidNull(RpcInternalContext.getContext().getAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE))
    );
    RpcInternalContext context = RpcInternalContext.getContext();
    Duration elapsed = meta.elapsed();
    Tags tags = meta.tags(this.common);

    clientTotal.apply(tags).record(elapsed);
    if (!meta.success()) {
        clientFail.apply(tags).record(elapsed);
    }
    requestSize.apply(tags).record(getLongAvoidNull(
        context.getAttachment(RpcConstants.INTERNAL_KEY_REQ_SIZE)));
    responseSize.apply(tags).record(getLongAvoidNull(
        context.getAttachment(RpcConstants.INTERNAL_KEY_RESP_SIZE)));
}
 
Example #16
Source File: RegistryRouter.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public List<ProviderInfo> route(SofaRequest request, List<ProviderInfo> providerInfos) {

    //has  address. FIXME
    if (CommonUtils.isNotEmpty(providerInfos)) {
        return providerInfos;
    }

    AddressHolder addressHolder = consumerBootstrap.getCluster().getAddressHolder();
    if (addressHolder != null) {
        List<ProviderInfo> current = addressHolder.getProviderInfos(RpcConstants.ADDRESS_DEFAULT_GROUP);
        if (providerInfos != null) {
            providerInfos.addAll(current);
        } else {
            providerInfos = current;
        }
    }
    recordRouterWay(RPC_REGISTRY_ROUTER);
    return providerInfos;
}
 
Example #17
Source File: BaseRestTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void before() {
    ServerConfig serverConfig = new ServerConfig()
        .setStopTimeout(60000)
        .setPort(8803)
        .setProtocol(RpcConstants.PROTOCOL_TYPE_REST);

    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:8803")
        .setProtocol("rest")
        .setBootstrap("rest")
        .setTimeout(30000)
        .setRegister(false);
    restService = consumerConfig.refer();
}
 
Example #18
Source File: ConsumerConfig.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public String getInterfaceId() {
    if (StringUtils.equals(RpcConstants.PROTOCOL_TYPE_TRIPLE, this.getProtocol())) {
        Class enclosingClass = this.getProxyClass().getEnclosingClass();
        Method sofaStub = null;
        String serviceName = interfaceId;
        try {
            sofaStub = enclosingClass.getDeclaredMethod("getServiceName");
            serviceName = (String) sofaStub.invoke(null);
        } catch (Throwable e) {
            //ignore
        }
        return serviceName;
    } else {
        return interfaceId;
    }
}
 
Example #19
Source File: RouterChainTest.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Test
public void buildProviderChain() {
    ConsumerConfig config = new ConsumerConfig();
    config.setBootstrap("test");
    ArrayList<Router> list = new ArrayList<Router>();
    config.setRouter(Arrays.asList("testChainRouter0", "-testChainRouter8"));
    list.add(new TestChainRouter1());
    list.add(new TestChainRouter2());
    list.add(new TestChainRouter3());
    list.add(new TestChainRouter4());
    list.add(new ExcludeRouter("-testChainRouter5"));
    config.setRouterRef(list);

    ConsumerBootstrap consumerBootstrap = Bootstraps.from(config);
    RouterChain chain = RouterChain.buildConsumerChain(consumerBootstrap);

    // build test data
    SofaRequest request = new SofaRequest();
    request.setMethodArgs(new String[] { "xxx" });
    request.setInvokeType("sync");
    List<ProviderInfo> providerInfos = new ArrayList<ProviderInfo>();
    ProviderInfo providerInfo = new ProviderInfo();
    providerInfo.setHost("127.0.0.1");
    providerInfo.setPort(12200);
    providerInfos.add(providerInfo);

    chain.route(request, providerInfos);
    Assert.assertEquals("r0>r7>r2>r4",
        RpcInternalContext.getContext().getAttachment(RpcConstants.INTERNAL_KEY_ROUTER_RECORD));
}
 
Example #20
Source File: AbstractHttp2ClientTransport.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 调用后设置一些属性(注意,在异步的情况较多下)
 *
 * @param context RPC上下文
 * @param request 请求对象
 */
protected void afterSend(RpcInternalContext context, SofaRequest request) {
    currentRequests.decrementAndGet();
    int cost = context.getStopWatch().tick().read();
    context.setAttachment(RpcConstants.INTERNAL_KEY_REQ_SERIALIZE_TIME, cost);
    if (EventBus.isEnable(ClientAfterSendEvent.class)) {
        EventBus.post(new ClientAfterSendEvent(request));
    }
}
 
Example #21
Source File: SentinelSofaRpcConsumerFilter.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public SofaResponse invoke(FilterInvoker invoker, SofaRequest request) throws SofaRpcException {
    // Now only support sync invoke.
    if (request.getInvokeType() != null && !RpcConstants.INVOKER_TYPE_SYNC.equals(request.getInvokeType())) {
        return invoker.invoke(request);
    }

    String interfaceResourceName = getInterfaceResourceName(request);
    String methodResourceName = getMethodResourceName(request);

    Entry interfaceEntry = null;
    Entry methodEntry = null;
    try {
        interfaceEntry = SphU.entry(interfaceResourceName, ResourceTypeConstants.COMMON_RPC, EntryType.OUT);
        methodEntry = SphU.entry(methodResourceName, ResourceTypeConstants.COMMON_RPC,
            EntryType.OUT, getMethodArguments(request));

        SofaResponse response = invoker.invoke(request);

        traceResponseException(response, interfaceEntry, methodEntry);
        return response;
    } catch (BlockException e) {
        return SofaRpcFallbackRegistry.getConsumerFallback().handle(invoker, request, e);
    } catch (Throwable t) {
        throw traceOtherException(t, interfaceEntry, methodEntry);
    } finally {
        if (methodEntry != null) {
            methodEntry.exit(1, getMethodArguments(request));
        }

        if (interfaceEntry != null) {
            interfaceEntry.exit();
        }
    }
}
 
Example #22
Source File: DubboConsumerBootstrap.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
private void copyMethods(ConsumerConfig<T> consumerConfig, ReferenceConfig<T> referenceConfig) {
    Map<String, MethodConfig> methodConfigs = consumerConfig.getMethods();
    if (CommonUtils.isNotEmpty(methodConfigs)) {
        List<com.alibaba.dubbo.config.MethodConfig> dubboMethodConfigs =
                new ArrayList<com.alibaba.dubbo.config.MethodConfig>();
        for (Map.Entry<String, MethodConfig> entry : methodConfigs.entrySet()) {
            MethodConfig methodConfig = entry.getValue();
            com.alibaba.dubbo.config.MethodConfig dubboMethodConfig = new com.alibaba.dubbo.config.MethodConfig();
            dubboMethodConfig.setName(methodConfig.getName());
            dubboMethodConfig.setParameters(methodConfig.getParameters());
            dubboMethodConfig.setTimeout(methodConfig.getTimeout());
            dubboMethodConfig.setRetries(methodConfig.getRetries());
            String invokeType = methodConfig.getInvokeType();
            if (invokeType != null) {
                if (RpcConstants.INVOKER_TYPE_ONEWAY.equals(invokeType)) {
                    dubboMethodConfig.setReturn(false);
                }
                if (RpcConstants.INVOKER_TYPE_CALLBACK.equals(invokeType)
                    || RpcConstants.INVOKER_TYPE_FUTURE.equals(invokeType)) {
                    dubboMethodConfig.setAsync(true);
                }
            }
            dubboMethodConfigs.add(dubboMethodConfig);
        }
        referenceConfig.setMethods(dubboMethodConfigs);
    }
}
 
Example #23
Source File: MulticastRegistryHelper.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 服务注册中心的Key
 *
 * @param config   配置
 * @param protocol 协议
 * @return 返回值
 */
public static String buildListDataId(AbstractInterfaceConfig config, String protocol) {
    if (RpcConstants.PROTOCOL_TYPE_BOLT.equals(protocol)
        || RpcConstants.PROTOCOL_TYPE_TR.equals(protocol)) {
        return ConfigUniqueNameGenerator.getUniqueName(config) + "@DEFAULT";
    } else {
        return ConfigUniqueNameGenerator.getUniqueName(config) + "@" + protocol;
    }

}
 
Example #24
Source File: SofaRegistryHelper.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 构建服务列表的DataId, 格式为interface:version[:uniqueId]@protocol
 *
 * @param config   配置
 * @param protocol 协议
 * @return 返回值
 */
public static String buildListDataId(AbstractInterfaceConfig config, String protocol) {
    if (RpcConstants.PROTOCOL_TYPE_BOLT.equals(protocol) || RpcConstants.PROTOCOL_TYPE_TR.equals(protocol)) {
        return ConfigUniqueNameGenerator.getUniqueName(config) + "@DEFAULT";
    } else {
        return ConfigUniqueNameGenerator.getUniqueName(config) + "@" + protocol;
    }
}
 
Example #25
Source File: HttpTransportUtils.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * Parse serialize type from content type
 *
 * @param contentType Content-type of http request
 * @return serialize code
 * @throws SofaRpcException unknown content type
 */
public static byte getSerializeTypeByContentType(String contentType) throws SofaRpcException {
    if (StringUtils.isNotBlank(contentType)) {
        String ct = contentType.toLowerCase();
        if (ct.contains("text/plain") || ct.contains("text/html") || ct.contains("application/json")) {
            return getSerializeTypeByName(RpcConstants.SERIALIZE_JSON);
        } else if (ct.contains(RpcConstants.SERIALIZE_PROTOBUF)) {
            return getSerializeTypeByName(RpcConstants.SERIALIZE_PROTOBUF);
        } else if (ct.contains(RpcConstants.SERIALIZE_HESSIAN)) {
            return getSerializeTypeByName(RpcConstants.SERIALIZE_HESSIAN2);
        }
    }
    throw new SofaRpcException(RpcErrorType.SERVER_DESERIALIZE, LogCodes.getLog(
        LogCodes.ERROR_UNSUPPORTED_CONTENT_TYPE, contentType, RemotingConstants.HEAD_SERIALIZE_TYPE));
}
 
Example #26
Source File: AbstractHttp2ClientTransport.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
protected void doSend(final SofaRequest request, AbstractHttpClientHandler callback, final int timeoutMills) {
    AbstractByteBuf data = null;
    try {
        // 序列化
        byte serializeType = request.getSerializeType();
        Serializer serializer = SerializerFactory.getSerializer(serializeType);
        data = serializer.encode(request, null);
        request.setData(data);
        // 记录请求序列化大小 不是很准,没有记录HTTP头
        RpcInternalContext.getContext().setAttachment(RpcConstants.INTERNAL_KEY_REQ_SIZE, data.readableBytes());

        // 转换请求
        FullHttpRequest httpRequest = convertToHttpRequest(request);

        // 发送请求
        final int requestId = sendHttpRequest(httpRequest, callback);

        if (request.isAsync()) {
            TIMEOUT_TIMER.newTimeout(new TimerTask() {
                @Override
                public void run(Timeout timeout) throws Exception {
                    Map.Entry<ChannelFuture, AbstractHttpClientHandler> entry = responseChannelHandler
                        .removePromise(requestId);
                    if (entry != null) {
                        ClientHandler handler = entry.getValue();
                        Exception e = timeoutException(request, timeoutMills, null);
                        handler.onException(e);
                    }
                }

            }, timeoutMills, TimeUnit.MILLISECONDS);
        }
    } finally {
        if (data != null) {
            data.release();
        }
    }
}
 
Example #27
Source File: RegistryUtils.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
public static String buildUniqueName(AbstractInterfaceConfig config, String protocol) {
    if (RpcConstants.PROTOCOL_TYPE_BOLT.equals(protocol) || RpcConstants.PROTOCOL_TYPE_TR.equals(protocol)) {
        return ConfigUniqueNameGenerator.getUniqueName(config) + "@DEFAULT";
    } else {
        return ConfigUniqueNameGenerator.getUniqueName(config) + "@" + protocol;
    }
}
 
Example #28
Source File: RpcServiceContextFilter.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 {
    RpcServiceContext serviceCtx = new RpcServiceContext();
    RpcInternalContext internalCtx = RpcInternalContext.getContext();
    serviceCtx.setServiceName(request.getTargetServiceUniqueName());
    serviceCtx.setMethodName(request.getMethodName());
    serviceCtx.setTraceId((String) internalCtx.getAttachment(RpcConstants.INTERNAL_KEY_TRACE_ID));
    serviceCtx.setRpcId((String) internalCtx.getAttachment(RpcConstants.INTERNAL_KEY_SPAN_ID));
    serviceCtx.setCallerAppName((String) request.getRequestProp(RemotingConstants.HEAD_APP_NAME));
    serviceCtx.setCallerUrl(internalCtx.getRemoteHostName());

    RpcInvokeContext.getContext().put(RemotingConstants.INVOKE_CTX_RPC_SER_CTX, serviceCtx);

    return invoker.invoke(request);
}
 
Example #29
Source File: AbstractInterfaceConfig.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 接口属性和方法属性加载配置到缓存
 *
 * @param rebuild 是否重建
 * @return Map<String Object> unmodifiableMap
 */
public synchronized Map<String, Object> getConfigValueCache(boolean rebuild) {
    if (configValueCache != null && !rebuild) {
        return configValueCache;
    }
    Map<String, Object> context = new HashMap<String, Object>(32);
    Map<String, String> providerParams = getParameters();
    if (providerParams != null) {
        context.putAll(providerParams); // 复制接口的自定义参数
    }
    Map<String, MethodConfig> methodConfigs = getMethods();
    if (CommonUtils.isNotEmpty(methodConfigs)) {
        for (MethodConfig methodConfig : methodConfigs.values()) {
            String prefix = RpcConstants.HIDE_KEY_PREFIX + methodConfig.getName() + RpcConstants.HIDE_KEY_PREFIX;
            Map<String, String> methodparam = methodConfig.getParameters();
            if (methodparam != null) { // 复制方法级自定义参数
                for (Map.Entry<String, String> entry : methodparam.entrySet()) {
                    context.put(prefix + entry.getKey(), entry.getValue());
                }
            }
            // 复制方法级参数属性
            BeanUtils.copyPropertiesToMap(methodConfig, prefix, context);
        }
    }
    // 复制接口级参数属性
    BeanUtils.copyPropertiesToMap(this, StringUtils.EMPTY, context);
    configValueCache = Collections.unmodifiableMap(context);
    return configValueCache;
}
 
Example #30
Source File: MockTestRegistryTest.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Test
public void testAll() {

    RegistryConfig registryConfig = new RegistryConfig()
        .setProtocol("mocktest");

    ServerConfig serverConfig2 = new ServerConfig()
        .setPort(22222)
        .setDaemon(false);

    // 服务端
    ProviderConfig<HelloService> CProvider = new ProviderConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setRef(new HelloServiceImpl(1000))
        .setRegistry(registryConfig)
        .setServer(serverConfig2);
    CProvider.export();

    // 客户端
    ConsumerConfig<HelloService> BConsumer = new ConsumerConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setInvokeType(RpcConstants.INVOKER_TYPE_SYNC)
        .setTimeout(5000)
        .setRegistry(registryConfig);
    HelloService helloService = BConsumer.refer();

    // 正常
    boolean error = false;
    try {
        String ret = helloService.sayHello("xxx", 22);
        Assert.assertNotNull(ret);
    } catch (Exception e) {
        e.printStackTrace();
        error = true;
    }
    Assert.assertFalse(error);
}