com.alipay.sofa.rpc.client.ProviderInfoAttrs Java Examples

The following examples show how to use com.alipay.sofa.rpc.client.ProviderInfoAttrs. 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: ConsumerNodeChangeListener.java    From sofa-dashboard with Apache License 2.0 6 votes vote down vote up
private RpcConsumer convert2Consumer(String serviceName, String providerData) {

        try {
            providerData = URLDecoder.decode(providerData, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        RpcConsumer rpcConsumer = new RpcConsumer();
        ProviderInfo consumerInfo = ProviderHelper.toProviderInfo(providerData);
        String appName = consumerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_APP_NAME);
        rpcConsumer.setAppName(appName);
        rpcConsumer.setServiceName(serviceName);
        rpcConsumer.setAddress(consumerInfo.getHost());
        rpcConsumer.setPort(consumerInfo.getPort());
        return rpcConsumer;
    }
 
Example #2
Source File: DefaultConsumerBootstrap.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * Subscribe provider list from direct url
 *
 * @param directUrl direct url of consume config
 * @return Provider group list
 */
protected List<ProviderGroup> subscribeFromDirectUrl(String directUrl) {
    List<ProviderGroup> result = new ArrayList<ProviderGroup>();
    List<ProviderInfo> tmpProviderInfoList = new ArrayList<ProviderInfo>();
    String[] providerStrs = StringUtils.splitWithCommaOrSemicolon(directUrl);
    for (String providerStr : providerStrs) {
        ProviderInfo providerInfo = convertToProviderInfo(providerStr);
        if (providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_SOURCE) == null) {
            providerInfo.setStaticAttr(ProviderInfoAttrs.ATTR_SOURCE, "direct");
        }
        tmpProviderInfoList.add(providerInfo);
    }

    result.add(new ProviderGroup(RpcConstants.ADDRESS_DIRECT_GROUP, tmpProviderInfoList));
    return result;
}
 
Example #3
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 #4
Source File: RegistryUtils.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
public static Map<String, String> convertProviderToMap(ProviderConfig providerConfig, ServerConfig server) {
    Map<String, String> metaData = new HashMap<String, String>();
    metaData.put(RpcConstants.CONFIG_KEY_UNIQUEID, providerConfig.getUniqueId());
    metaData.put(RpcConstants.CONFIG_KEY_INTERFACE, providerConfig.getInterfaceId());
    metaData.put(RpcConstants.CONFIG_KEY_TIMEOUT, String.valueOf(providerConfig.getTimeout()));
    metaData.put(RpcConstants.CONFIG_KEY_DELAY, String.valueOf(providerConfig.getDelay()));
    metaData.put(RpcConstants.CONFIG_KEY_ID, providerConfig.getId());
    metaData.put(RpcConstants.CONFIG_KEY_DYNAMIC, String.valueOf(providerConfig.isDynamic()));
    metaData.put(ProviderInfoAttrs.ATTR_WEIGHT, String.valueOf(providerConfig.getWeight()));
    metaData.put(RpcConstants.CONFIG_KEY_ACCEPTS, String.valueOf(server.getAccepts()));
    metaData.put(ProviderInfoAttrs.ATTR_START_TIME, String.valueOf(RpcRuntimeContext.now()));
    metaData.put(RpcConstants.CONFIG_KEY_APP_NAME, providerConfig.getAppName());
    metaData.put(RpcConstants.CONFIG_KEY_SERIALIZATION, providerConfig.getSerialization());
    metaData.put(RpcConstants.CONFIG_KEY_PROTOCOL, server.getProtocol());
    if (null != providerConfig.getParameters()) {
        //noinspection unchecked
        metaData.putAll(providerConfig.getParameters());
    }

    // add common attr
    metaData.put(RpcConstants.CONFIG_KEY_LANGUAGE, JAVA);
    metaData.put(RpcConstants.CONFIG_KEY_PID, RpcRuntimeContext.PID);
    metaData.put(RpcConstants.CONFIG_KEY_RPC_VERSION, String.valueOf(Version.RPC_VERSION));
    return metaData;
}
 
Example #5
Source File: ZookeeperRegistryHelperTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoWarmupWeight() throws InterruptedException {
    long now = System.currentTimeMillis();

    ProviderInfo providerInfo = new ProviderInfo()
        .setWeight(600)
        .setStaticAttr(ProviderInfoAttrs.ATTR_WEIGHT, "600")
        .setStaticAttr(ProviderInfoAttrs.ATTR_START_TIME, String.valueOf(now))
        .setStaticAttr(ProviderInfoAttrs.ATTR_WARMUP_TIME, String.valueOf(30));

    ZookeeperRegistryHelper.processWarmUpWeight(providerInfo);

    Assert.assertEquals("600", providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_WEIGHT));
    Assert.assertEquals(now + "", providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_START_TIME));
    Assert.assertEquals(null, providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_WARMUP_TIME));
    Assert.assertEquals(null, providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_WARMUP_WEIGHT));

    Assert.assertEquals(null, providerInfo.getDynamicAttr(ProviderInfoAttrs.ATTR_WARM_UP_END_TIME));
    Assert.assertEquals(null, providerInfo.getDynamicAttr(ProviderInfoAttrs.ATTR_WARMUP_WEIGHT));
    Assert.assertEquals(ProviderStatus.AVAILABLE, providerInfo.getStatus());
    Assert.assertEquals(600, providerInfo.getWeight());
}
 
Example #6
Source File: ZookeeperRegistryHelperTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoWarmupTime() throws InterruptedException {
    long now = System.currentTimeMillis();

    ProviderInfo providerInfo = new ProviderInfo()
        .setWeight(300)
        .setStaticAttr(ProviderInfoAttrs.ATTR_WEIGHT, "300")
        .setStaticAttr(ProviderInfoAttrs.ATTR_START_TIME, String.valueOf(now))
        .setStaticAttr(ProviderInfoAttrs.ATTR_WARMUP_WEIGHT, String.valueOf(800));

    ZookeeperRegistryHelper.processWarmUpWeight(providerInfo);

    Assert.assertEquals("300", providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_WEIGHT));
    Assert.assertEquals(now + "", providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_START_TIME));
    Assert.assertEquals(null, providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_WARMUP_TIME));
    Assert.assertEquals(null, providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_WARMUP_WEIGHT));

    Assert.assertEquals(null, providerInfo.getDynamicAttr(ProviderInfoAttrs.ATTR_WARM_UP_END_TIME));
    Assert.assertEquals(null, providerInfo.getDynamicAttr(ProviderInfoAttrs.ATTR_WARMUP_WEIGHT));
    Assert.assertEquals(ProviderStatus.AVAILABLE, providerInfo.getStatus());
    Assert.assertEquals(300, providerInfo.getWeight());
}
 
Example #7
Source File: LocalRegistryHelper.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
private static Map<String, ProviderGroup> unMarshal(String context) {
    if (StringUtils.isBlank(context)) {
        return null;
    }
    Map<String, ProviderGroup> map = new HashMap<String, ProviderGroup>();
    String[] lines = StringUtils.split(context, FileUtils.LINE_SEPARATOR);
    for (String line : lines) {
        String[] fields = line.split(SEPARATORSTR);
        if (fields.length > 1) {
            String key = fields[0];
            Set<ProviderInfo> values = new HashSet<ProviderInfo>();
            for (int i = 1; i < fields.length; i++) {
                String pstr = fields[i];
                if (StringUtils.isNotEmpty(pstr)) {
                    ProviderInfo providerInfo = ProviderHelper.toProviderInfo(pstr);
                    providerInfo.setStaticAttr(ProviderInfoAttrs.ATTR_SOURCE, "local");
                    values.add(providerInfo);
                }
            }
            map.put(key, new ProviderGroup(new ArrayList<ProviderInfo>(values)));
        }
    }
    return map;
}
 
Example #8
Source File: ConsumerTracerFilter.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public SofaResponse invoke(FilterInvoker invoker, SofaRequest request) throws SofaRpcException {

    SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext();
    SofaTracerSpan clientSpan = sofaTraceContext.getCurrentSpan();

    clientSpan.setTag(RpcSpanTags.INVOKE_TYPE, request.getInvokeType());

    RpcInternalContext context = RpcInternalContext.getContext();
    clientSpan.setTag(RpcSpanTags.ROUTE_RECORD,
        (String) context.getAttachment(RpcConstants.INTERNAL_KEY_ROUTER_RECORD));

    ProviderInfo providerInfo = context.getProviderInfo();
    if (providerInfo != null) {
        clientSpan.setTag(RpcSpanTags.REMOTE_APP, providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_APP_NAME));
        clientSpan.setTag(RpcSpanTags.REMOTE_IP, providerInfo.getHost() + ":" + providerInfo.getPort());
    }

    return invoker.invoke(request);
    // 因为异步的场景,所以received不写在这里
}
 
Example #9
Source File: ProviderNodeChangeListener.java    From sofa-dashboard with Apache License 2.0 6 votes vote down vote up
private RpcProvider convert2Provider(String serviceName, String providerData) {

        try {
            providerData = URLDecoder.decode(providerData, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        RpcProvider rpcProvider = new RpcProvider();
        ProviderInfo providerInfo = ProviderHelper.toProviderInfo(providerData);

        rpcProvider.setServiceName(serviceName);
        rpcProvider.setAddress(providerInfo.getHost());
        rpcProvider.setPort(providerInfo.getPort());
        String appName = providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_APP_NAME);
        rpcProvider.setAppName(appName);
        rpcProvider.setWeight(providerInfo.getWeight());
        return rpcProvider;
    }
 
Example #10
Source File: ZookeeperRegistryHelperTest.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Test
public void testWarmup() throws UnsupportedEncodingException, InterruptedException {

    long now = System.currentTimeMillis();

    ProviderInfo providerInfo = new ProviderInfo()
        .setWeight(200)
        .setStaticAttr(ProviderInfoAttrs.ATTR_WEIGHT, "200")
        .setStaticAttr(ProviderInfoAttrs.ATTR_START_TIME, String.valueOf(now))
        .setStaticAttr(ProviderInfoAttrs.ATTR_WARMUP_TIME, String.valueOf(200))
        .setStaticAttr(ProviderInfoAttrs.ATTR_WARMUP_WEIGHT, String.valueOf(700));

    ZookeeperRegistryHelper.processWarmUpWeight(providerInfo);

    Assert.assertEquals("200", providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_WEIGHT));
    Assert.assertEquals(now + "", providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_START_TIME));
    Assert.assertEquals(null, providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_WARMUP_TIME));
    Assert.assertEquals(null, providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_WARMUP_WEIGHT));

    Assert.assertEquals(now + 200, providerInfo.getDynamicAttr(ProviderInfoAttrs.ATTR_WARM_UP_END_TIME));
    Assert.assertEquals(700, providerInfo.getDynamicAttr(ProviderInfoAttrs.ATTR_WARMUP_WEIGHT));
    Assert.assertEquals(ProviderStatus.WARMING_UP, providerInfo.getStatus());
    Assert.assertEquals(700, providerInfo.getWeight());

    long elapsed = System.currentTimeMillis() - now;
    LOGGER.info("elapsed time: " + elapsed + "ms");

    long sleepTime = 300 - elapsed;
    if (sleepTime >= 0) {
        Thread.sleep(sleepTime);
    }

    Assert.assertEquals(ProviderStatus.AVAILABLE, providerInfo.getStatus());
    Assert.assertEquals(200, providerInfo.getWeight());
}
 
Example #11
Source File: SofaRegistrySubscribeCallback.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * merge url
 *
 * @param userDatas
 * @param configDatas
 * @return
 */
List<ProviderInfo> mergeProviderInfo(List<String> userDatas, List<String> configDatas) {
    // 是否自己缓存运算后的结果?? TODO
    List<ProviderInfo> providers = SofaRegistryHelper.parseProviderInfos(userDatas);
    // 交叉比较
    if (CommonUtils.isNotEmpty(providers) && CommonUtils.isNotEmpty(configDatas)) {
        List<ProviderInfo> override = SofaRegistryHelper.parseProviderInfos(configDatas);
        Iterator<ProviderInfo> iterator = providers.iterator();
        while (iterator.hasNext()) {
            ProviderInfo origin = iterator.next();
            for (ProviderInfo over : override) {
                if (PROTOCOL_TYPE_OVERRIDE.equals(over.getProtocolType()) &&
                    StringUtils.equals(origin.getHost(), over.getHost()) && origin.getPort() == over.getPort()) {
                    // host 和 port 相同 认为是一个地址
                    if (over.getWeight() != origin.getWeight()) {
                        origin.setWeight(over.getWeight());
                    }
                    if (CommonUtils.isTrue(over.getAttr(ProviderInfoAttrs.ATTR_DISABLED))) {
                        if (LOGGER.isInfoEnabled()) {
                            LOGGER.info("Provider is disabled by override. {}", origin.toUrl());
                        }
                        iterator.remove(); // 禁用 删掉
                    }
                }
            }
        }
    }
    return providers;
}
 
Example #12
Source File: InvocationStatDimension.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * Gets origin weight.
 *
 * @return the origin weight
 */
public int getOriginWeight() {
    if (originWeight == null) {
        if (providerInfo == null) {
            originWeight = RpcConfigs.getIntValue(RpcOptions.PROVIDER_WEIGHT);
        } else {
            originWeight = CommonUtils.parseInt(providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_WEIGHT),
                RpcConfigs.getIntValue(RpcOptions.PROVIDER_WEIGHT));
        }
    }
    return originWeight;
}
 
Example #13
Source File: RegistryUtils.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
public static List<ProviderInfo> matchProviderInfos(ConsumerConfig consumerConfig, List<ProviderInfo> providerInfos) {
    String protocol = consumerConfig.getProtocol();
    List<ProviderInfo> result = new ArrayList<ProviderInfo>();
    for (ProviderInfo providerInfo : providerInfos) {
        if (providerInfo.getProtocolType().equalsIgnoreCase(protocol)
            && StringUtils.equals(consumerConfig.getUniqueId(),
                providerInfo.getAttr(ProviderInfoAttrs.ATTR_UNIQUEID))) {
            result.add(providerInfo);
        }
    }
    return result;
}
 
Example #14
Source File: RegistryUtils.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * Read the warmUp weight parameter,
 * decide whether to switch the state to the preheating period,
 * and set the corresponding parameters during the preheating period.
 *
 * @param providerInfo the provider info
 */
public static void processWarmUpWeight(ProviderInfo providerInfo) {

    String warmupTimeStr = providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_WARMUP_TIME);
    String warmupWeightStr = providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_WARMUP_WEIGHT);
    String startTimeStr = providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_START_TIME);

    if (StringUtils.isNotBlank(warmupTimeStr) && StringUtils.isNotBlank(warmupWeightStr) &&
        StringUtils.isNotBlank(startTimeStr)) {

        long warmupTime = CommonUtils.parseLong(warmupTimeStr, 0);
        int warmupWeight = CommonUtils.parseInt(warmupWeightStr,
            Integer.parseInt(providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_WEIGHT)));
        long startTime = CommonUtils.parseLong(startTimeStr, 0);
        long warmupEndTime = startTime + warmupTime;

        // set for dynamic
        providerInfo.setDynamicAttr(ProviderInfoAttrs.ATTR_WARMUP_WEIGHT, warmupWeight);
        providerInfo.setDynamicAttr(ProviderInfoAttrs.ATTR_WARM_UP_END_TIME, warmupEndTime);
        providerInfo.setStatus(ProviderStatus.WARMING_UP);
    }

    // remove from static
    providerInfo.getStaticAttrs().remove(ProviderInfoAttrs.ATTR_WARMUP_TIME);
    providerInfo.getStaticAttrs().remove(ProviderInfoAttrs.ATTR_WARMUP_WEIGHT);

}
 
Example #15
Source File: ConsumerInvoker.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public SofaResponse invoke(SofaRequest sofaRequest) throws SofaRpcException {
    // 设置下服务器应用
    ProviderInfo providerInfo = RpcInternalContext.getContext().getProviderInfo();
    String appName = providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_APP_NAME);
    if (StringUtils.isNotEmpty(appName)) {
        sofaRequest.setTargetAppName(appName);
    }

    // 目前只是通过client发送给服务端
    return consumerBootstrap.getCluster().sendMsg(providerInfo, sofaRequest);
}
 
Example #16
Source File: SofaRegistryHelperTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Test
public void convertProviderToUrls() throws Exception {
    ServerConfig serverConfig = new ServerConfig()
        .setHost("0.0.0.0")
        .setPort(22000)
        .setProtocol("bolt");

    ServerConfig serverConfig2 = new ServerConfig()
        .setHost("127.0.0.1")
        .setPort(12200)
        .setProtocol("tr");

    ServerConfig serverConfig3 = new ServerConfig()
        .setHost("192.1.1.1")
        .setPort(8080)
        .setProtocol("xfire");
    ProviderConfig<?> providerConfig = new ProviderConfig();
    providerConfig
        .setInterfaceId("com.alipay.sofa.rpc.test.TestService")
        .setUniqueId("qqqq")
        .setApplication(new ApplicationConfig().setAppName("xxxx"))
        .setTimeout(4444)
        .setWeight(250)
        .setServer(Arrays.asList(serverConfig, serverConfig2));

    MethodConfig methodConfig = new MethodConfig().setName("echo").setTimeout(3333);
    MethodConfig methodConfig2 = new MethodConfig().setName("xx").setTimeout(2222);
    providerConfig.setMethods(Arrays.asList(methodConfig, methodConfig2));

    String s1 = SofaRegistryHelper.convertProviderToUrls(providerConfig, serverConfig);
    Assert.assertNotNull(s1);
    ProviderInfo providerInfo = SofaRegistryHelper.parseProviderInfo(s1);
    Assert.assertEquals(SystemInfo.getLocalHost(), providerInfo.getHost());
    Assert.assertEquals(serverConfig.getPort(), providerInfo.getPort());
    Assert.assertEquals(providerConfig.getAppName(), providerInfo.getAttr(ProviderInfoAttrs.ATTR_APP_NAME));
    Assert.assertEquals(providerConfig.getTimeout(), providerInfo.getDynamicAttr(ProviderInfoAttrs.ATTR_TIMEOUT));

    String s2 = SofaRegistryHelper.convertProviderToUrls(providerConfig, serverConfig2);
    Assert.assertNotNull(s2);
    ProviderInfo providerInfo2 = SofaRegistryHelper.parseProviderInfo(s2);
    Assert.assertEquals(SystemInfo.getLocalHost(), providerInfo.getHost());
    Assert.assertEquals(serverConfig2.getPort(), providerInfo2.getPort());
    Assert.assertEquals(providerConfig.getAppName(), providerInfo2.getAttr(ProviderInfoAttrs.ATTR_APP_NAME));
    Assert.assertEquals(providerConfig.getTimeout(), providerInfo2.getDynamicAttr(ProviderInfoAttrs.ATTR_TIMEOUT));

    String s3 = SofaRegistryHelper.convertProviderToUrls(providerConfig, serverConfig3);
    Assert.assertNotNull(s3);
    ProviderInfo providerInfo3 = SofaRegistryHelper.parseProviderInfo(s3);
    Assert.assertEquals(serverConfig3.getHost(), providerInfo3.getHost());
    Assert.assertEquals(serverConfig3.getPort(), providerInfo3.getPort());
    Assert.assertEquals(providerConfig.getAppName(), providerInfo3.getAttr(ProviderInfoAttrs.ATTR_APP_NAME));
    Assert.assertEquals(providerConfig.getTimeout(), providerInfo3.getDynamicAttr(ProviderInfoAttrs.ATTR_TIMEOUT));
}
 
Example #17
Source File: ZookeeperSubscribeObserverTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Test
public void testAll() throws Exception {
    RegistryConfig registryConfig = new RegistryConfig().setProtocol(RpcConstants.REGISTRY_PROTOCOL_ZK)
        .setAddress("127.0.0.1:2181");
    ZookeeperRegistry registry = (ZookeeperRegistry) RegistryFactory
        .getRegistry(registryConfig);
    registry.start();

    ServerConfig serverConfig = new ServerConfig().setPort(22222)
        .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT);
    ProviderConfig<HelloService> providerConfig = new ProviderConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName()).setRef(new HelloServiceImpl(22222))
        .setServer(serverConfig).setRegistry(registryConfig)
        .setParameter(ProviderInfoAttrs.ATTR_WARMUP_TIME, "2000")
        .setParameter(ProviderInfoAttrs.ATTR_WARMUP_WEIGHT, "100").setUniqueId("uniqueIdA")
        .setRepeatedExportLimit(-1).setWeight(0);

    ServerConfig serverConfig2 = new ServerConfig().setPort(22111)
        .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT);
    ProviderConfig<HelloService> providerConfig2 = new ProviderConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName()).setRef(new HelloServiceImpl(22111))
        .setServer(serverConfig2).setRegistry(registryConfig)
        .setUniqueId("uniqueIdB").setRepeatedExportLimit(-1).setWeight(0);

    providerConfig.export();
    providerConfig2.export();

    ConsumerConfig<HelloService> consumerConfig = new ConsumerConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName()).setRegistry(registryConfig)
        .setTimeout(3333).setUniqueId("uniqueIdA").setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT);
    HelloService helloService = consumerConfig.refer();

    AddressHolder addressHolder = consumerConfig.getConsumerBootstrap().getCluster()
        .getAddressHolder();
    Assert.assertTrue(addressHolder.getAllProviderSize() == 1);

    ServerConfig serverConfig3 = new ServerConfig().setPort(22133)
        .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT);
    ProviderConfig<HelloService> providerConfig3 = new ProviderConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName()).setRef(new HelloServiceImpl(22133))
        .setServer(serverConfig3).setRegistry(registryConfig).setRepeatedExportLimit(-1)
        .setUniqueId("uniqueIdB").setRepeatedExportLimit(-1).setWeight(0);

    providerConfig3.export();

    Assert.assertTrue(delayGetSize(addressHolder, 1, 100) == 1);

    ServerConfig serverConfig4 = new ServerConfig().setPort(22244)
        .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT);
    ProviderConfig<HelloService> providerConfig4 = new ProviderConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName()).setRef(new HelloServiceImpl(22244))
        .setServer(serverConfig4).setRegistry(registryConfig).setUniqueId("uniqueIdA")
        .setRepeatedExportLimit(-1).setWeight(0);

    providerConfig4.export();

    Assert.assertTrue(delayGetSize(addressHolder, 1, 100) == 2);
}
 
Example #18
Source File: ZookeeperOverrideObserverTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Test
public void testAll() throws Exception {

    try {
        RegistryConfig registryConfig = new RegistryConfig().setProtocol(RpcConstants.REGISTRY_PROTOCOL_ZK)
            .setAddress("127.0.0.1:2181");
        ZookeeperRegistry registry = (ZookeeperRegistry) RegistryFactory
            .getRegistry(registryConfig);
        registry.start();

        ServerConfig serverConfig = new ServerConfig().setPort(22222)
            .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT);
        ProviderConfig<OverrideService> providerConfig = new ProviderConfig<OverrideService>()
            .setInterfaceId(OverrideService.class.getName()).setRef(new OverrideServiceImpl(22222))
            .setServer(serverConfig).setRegistry(registryConfig)
            .setParameter(ProviderInfoAttrs.ATTR_WARMUP_TIME, "2000")
            .setParameter(ProviderInfoAttrs.ATTR_WARMUP_WEIGHT, "100").setWeight(0);

        ServerConfig serverConfig2 = new ServerConfig().setPort(22111)
            .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT);
        ProviderConfig<OverrideService> providerConfig2 = new ProviderConfig<OverrideService>()
            .setInterfaceId(OverrideService.class.getName()).setRef(new OverrideServiceImpl(22111))
            .setServer(serverConfig2).setRegistry(registryConfig).setRepeatedExportLimit(-1)
            .setWeight(0);

        providerConfig.export();
        providerConfig2.export();

        ConsumerConfig<OverrideService> consumerConfig = new ConsumerConfig<OverrideService>()
            .setInterfaceId(OverrideService.class.getName()).setRegistry(registryConfig)
            .setTimeout(3333).setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT);
        OverrideService overrideService = consumerConfig.refer();

        AddressHolder addressHolder = consumerConfig.getConsumerBootstrap().getCluster()
            .getAddressHolder();
        Assert.assertTrue(addressHolder.getAllProviderSize() == 2);

        providerConfig2.unExport();

        Assert.assertTrue(delayGetSize(addressHolder, 1, 100) == 1);

        List<String> path = registry.getZkClient().getChildren()
            .forPath("/sofa-rpc/" + OverrideService.class.getCanonicalName() + "/providers");
        String url = URLDecoder.decode(path.get(0), "UTF-8");
        ProviderInfo providerInfo = ProviderHelper.toProviderInfo(url);

        // 模拟下发一个override
        String override1 = providerInfo.getProtocolType() + "://" + providerInfo.getHost() + ":"
            + providerInfo.getPort() + "?timeout=2345";
        String overridePath1 = "/sofa-rpc/" + OverrideService.class.getCanonicalName() + "/overrides/"
            + URLEncoder.encode(override1, "UTF-8");
        registry.getZkClient().create().creatingParentContainersIfNeeded()
            .withMode(CreateMode.PERSISTENT).forPath(overridePath1);
        Assert.assertTrue(delayGetTimeout(consumerConfig, 2345, 100) == 2345);

        // 删除目前没有影响
        registry.getZkClient().delete().forPath(overridePath1);
        Thread.sleep(500);
        Assert.assertTrue(delayGetTimeout(consumerConfig, 2345, 100) == 2345);

        // 恢复到3333
        String override2 = providerInfo.getProtocolType() + "://" + providerInfo.getHost() + ":"
            + providerInfo.getPort() + "?timeout=3333";
        String overridePath2 = "/sofa-rpc/" + OverrideService.class.getCanonicalName() + "/overrides/"
            + URLEncoder.encode(override2, "UTF-8");
        registry.getZkClient().create().creatingParentContainersIfNeeded()
            .withMode(CreateMode.PERSISTENT).forPath(overridePath2);
        Assert.assertTrue(delayGetTimeout(consumerConfig, 3333, 100) == 3333);

        // 清除持久化的 path
        registry.getZkClient().delete().forPath(overridePath2);
    } catch (Throwable e) {
        LOGGER.error("ZookeeperOverrideObserver test case failed", e);
        Assert.assertTrue(e.getMessage(), false);
    }
}
 
Example #19
Source File: WarmUpTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Test
public void testWarmUp() throws InterruptedException {

    RegistryConfig registryConfig = new RegistryConfig()
        .setProtocol(RpcConstants.REGISTRY_PROTOCOL_ZK)
        .setAddress("127.0.0.1:2181");

    ServerConfig serverConfig = new ServerConfig()
        .setPort(22222)
        .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT);
    ProviderConfig<WarmUpService> providerConfig = new ProviderConfig<WarmUpService>()
        .setInterfaceId(WarmUpService.class.getName())
        .setRef(new WarmUpServiceImpl(22222))
        .setServer(serverConfig)
        .setRegistry(registryConfig)
        .setParameter(ProviderInfoAttrs.ATTR_WARMUP_TIME, "2000")
        .setParameter(ProviderInfoAttrs.ATTR_WARMUP_WEIGHT, "100")
        .setWeight(0);

    ServerConfig serverConfig2 = new ServerConfig()
        .setPort(22111)
        .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT);
    ProviderConfig<WarmUpService> providerConfig2 = new ProviderConfig<WarmUpService>()
        .setInterfaceId(WarmUpService.class.getName())
        .setRef(new WarmUpServiceImpl(22111))
        .setServer(serverConfig2)
        .setRegistry(registryConfig)
        .setRepeatedExportLimit(-1)
        .setWeight(0);

    providerConfig.export();
    providerConfig2.export();

    long startTime = System.currentTimeMillis();
    ConsumerConfig<WarmUpService> consumerConfig = new ConsumerConfig<WarmUpService>()
        .setInterfaceId(WarmUpService.class.getName())
        .setRegistry(registryConfig)
        .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT);
    WarmUpService warmUpService = consumerConfig.refer();

    // Before the 2000 ms, all the traffic goes to 22222.
    for (int i = 0; i < 10; i++) {
        Assert.assertEquals(22222, warmUpService.getPort());
    }

    long elapsed = System.currentTimeMillis() - startTime;
    LOGGER.info("elapsed " + elapsed + "ms");

    long sleepTime = 2100 - elapsed;
    if (sleepTime >= 0) {
        Thread.sleep(sleepTime);
    }

    // After 2000 ms, all the traffic goes to 22222 && 22111.
    int cnt = 0;
    for (int i = 0; i < 100; i++) {
        if (warmUpService.getPort() == 22111) {
            cnt++;
        }
    }
    Assert.assertTrue(cnt > 0);
}
 
Example #20
Source File: RpcReferenceContextFilter.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Override
public SofaResponse invoke(FilterInvoker invoker, SofaRequest request) throws SofaRpcException {

    ConsumerConfig config = (ConsumerConfig) invoker.getConfig();
    RpcReferenceContext referenceCtx = new RpcReferenceContext();
    referenceCtx.setGeneric(config.isGeneric());
    referenceCtx.setInterfaceName(config.getInterfaceId());
    referenceCtx.setUniqueId(config.getUniqueId());
    referenceCtx.setServiceName(request.getTargetServiceUniqueName());
    referenceCtx.setMethodName(request.getMethodName());

    RpcInternalContext context = RpcInternalContext.getContext();

    ProviderInfo providerInfo = context.getProviderInfo();
    if (providerInfo != null) {
        referenceCtx.setTargetAppName(providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_APP_NAME));
        referenceCtx.setTargetUrl(providerInfo.getHost() + ":" + providerInfo.getPort());
    }

    referenceCtx.setProtocol(config.getProtocol());
    referenceCtx.setInvokeType(request.getInvokeType());
    referenceCtx.setRouteRecord((String) context.getAttachment(RpcConstants.INTERNAL_KEY_ROUTER_RECORD));

    RpcInvokeContext.getContext().put(RemotingConstants.INVOKE_CTX_RPC_REF_CTX, referenceCtx);

    SofaResponse response = invoker.invoke(request);

    // 调用后
    InetSocketAddress local = context.getLocalAddress();
    if (local != null) {
        referenceCtx.setClientIP(NetUtils.toIpString(local));
        referenceCtx.setClientPort(local.getPort());
    }
    Long ct = (Long) context.getAttachment(RpcConstants.INTERNAL_KEY_CONN_CREATE_TIME);
    if (ct != null) {
        referenceCtx.setConnEstablishedSpan(ct);
    }
    Integer qs = (Integer) context.getAttachment(RpcConstants.INTERNAL_KEY_REQ_SIZE);
    if (qs != null) {
        referenceCtx.setRequestSize(qs.longValue());
    }
    Integer ps = (Integer) context.getAttachment(RpcConstants.INTERNAL_KEY_RESP_SIZE);
    if (ps != null) {
        referenceCtx.setResponseSize(ps.longValue());
    }

    referenceCtx.setTraceId((String) context.getAttachment(RpcConstants.INTERNAL_KEY_TRACE_ID));
    referenceCtx.setRpcId((String) context.getAttachment(RpcConstants.INTERNAL_KEY_SPAN_ID));
    Long ce = (Long) context.getAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE);
    if (ce != null) {
        referenceCtx.setCostTime(ce);
    }

    return response;
}