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

The following examples show how to use com.alipay.sofa.rpc.client.ProviderInfo. 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: 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 #2
Source File: TripleClientTransport.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * Get shared channel connection
 */
private ReferenceCountManagedChannel getSharedChannel(ProviderInfo url) {
    String key = url.toString();
    ReferenceCountManagedChannel channel = channelMap.get(key);

    if (channelAvailable(channel)) {
        channel.incrementAndGetCount();
        return channel;
    } else if (channel != null) {
        channel.shutdownNow();
    }

    synchronized (lock) {
        channel = channelMap.get(key);
        // double check
        if (channelAvailable(channel)) {
            channel.incrementAndGetCount();
        } else {
            channel = new ReferenceCountManagedChannel(initChannel(url));
            channelMap.put(key, channel);
        }
    }

    return channel;
}
 
Example #3
Source File: ZookeeperProviderObserver.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
private void notifyListeners(ConsumerConfig config, String providerPath, List<ChildData> currentData, boolean add)
    throws UnsupportedEncodingException {
    List<ProviderInfoListener> providerInfoListeners = providerListenerMap.get(config);
    if (CommonUtils.isNotEmpty(providerInfoListeners)) {
        List<ProviderInfo> providerInfos = ZookeeperRegistryHelper.convertUrlsToProviders(providerPath,
            currentData);
        List<ProviderInfo> providerInfosForProtocol = RegistryUtils.matchProviderInfos(config, providerInfos);
        for (ProviderInfoListener listener : providerInfoListeners) {
            if (add) {
                listener.addProvider(new ProviderGroup(providerInfosForProtocol));
            } else {
                listener.updateProviders(new ProviderGroup(providerInfosForProtocol));
            }
        }
    }
}
 
Example #4
Source File: SofaRpcConsumerInterceptor.java    From skywalking with Apache License 2.0 6 votes vote down vote up
/**
 * Format operation name. e.g. org.apache.skywalking.apm.plugin.test.Test.test(String)
 *
 * @return operation name.
 */
private String generateOperationName(ProviderInfo providerInfo, SofaRequest sofaRequest) {
    StringBuilder operationName = new StringBuilder();
    operationName.append(sofaRequest.getInterfaceName());
    operationName.append("." + sofaRequest.getMethodName() + "(");
    for (String arg : sofaRequest.getMethodArgSigs()) {
        operationName.append(arg + ",");
    }

    if (sofaRequest.getMethodArgs().length > 0) {
        operationName.delete(operationName.length() - 1, operationName.length());
    }

    operationName.append(")");

    return operationName.toString();
}
 
Example #5
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 #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: SofaProtoUtils.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
public static boolean checkIfUseGeneric(ConsumerConfig consumerConfig) {
    Class proxyClass = consumerConfig.getProxyClass();
    Class enclosingClass = proxyClass.getEnclosingClass();
    if (enclosingClass != null) {
        try {
            enclosingClass.getDeclaredMethod("getSofaStub", Channel.class, CallOptions.class,
                ProviderInfo.class, ConsumerConfig.class, int.class);
            return false;
        } catch (NoSuchMethodException e) {
            //ignore
            return true;
        }
    }

    return true;
}
 
Example #8
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 #9
Source File: MeshRegistryHelper.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 转为服务端提供者对象
 *
 * @param config 服务提供者配置
 * @param server 服务端
 * @return 本地服务提供者对象
 */
public static ProviderInfo convertProviderToProviderInfo(ProviderConfig config, ServerConfig server) {
    ProviderInfo providerInfo = new ProviderInfo()
        .setPort(server.getPort())
        .setWeight(config.getWeight())
        .setSerializationType(config.getSerialization())
        .setProtocolType(server.getProtocol())
        .setPath(server.getContextPath())
        .setStaticAttrs(config.getParameters());
    String host = server.getHost();
    if (NetUtils.isLocalHost(host) || NetUtils.isAnyHost(host)) {
        host = SystemInfo.getLocalHost();
    }
    providerInfo.setHost(host);
    return providerInfo;
}
 
Example #10
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 #11
Source File: NacosRegistryProviderObserver.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * Update providers.
 *
 * @param config the config 
 * @param instances the instances
 */
void updateProviders(ConsumerConfig config, List<Instance> instances) {
    if (LOGGER.isInfoEnabled(config.getAppName())) {
        LOGGER.infoWithApp(config.getAppName(),
            "Receive update provider: serviceName={}, size={}, data={}",
            NacosRegistryHelper.buildServiceName(config, config.getProtocol()), instances.size(),
            instances);
    }
    List<ProviderInfoListener> providerInfoListeners = providerListenerMap.get(config);
    if (CommonUtils.isNotEmpty(providerInfoListeners)) {
        List<ProviderInfo> providerInfos = NacosRegistryHelper.convertInstancesToProviders(instances);
        List<ProviderInfo> matchProviders = RegistryUtils.matchProviderInfos(config, providerInfos);

        for (ProviderInfoListener providerInfoListener : providerInfoListeners) {
            providerInfoListener
                .updateAllProviders(Collections.singletonList(new ProviderGroup().addAll(matchProviders)));
        }
    }
}
 
Example #12
Source File: ConsistentHashLoadBalancer.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * Instantiates a new Selector.
 *
 * @param interfaceId the interface id
 * @param method      the method
 * @param actualNodes the actual nodes
 * @param hashcode    the hashcode
 */
public Selector(String interfaceId, String method, List<ProviderInfo> actualNodes, int hashcode) {
    this.interfaceId = interfaceId;
    this.method = method;
    this.hashcode = hashcode;
    // 创建虚拟节点环 (默认一个provider共创建128个虚拟节点,较多比较均匀)
    this.virtualNodes = new TreeMap<Long, ProviderInfo>();
    int num = 128;
    for (ProviderInfo providerInfo : actualNodes) {
        for (int i = 0; i < num / 4; i++) {
            byte[] digest = HashUtils.messageDigest(providerInfo.getHost() + providerInfo.getPort() + i);
            for (int h = 0; h < 4; h++) {
                long m = HashUtils.hash(digest, h);
                virtualNodes.put(m, providerInfo);
            }
        }
    }
}
 
Example #13
Source File: SofaRegistrySubscribeCallback.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
private void notifyToListener(ProviderInfoListener listener, ComposeUserData mergedResult) {

        if ("".equalsIgnoreCase(mergedResult.getLocalZone()) ||
            DEFAULT_ZONE.equalsIgnoreCase(mergedResult.getLocalZone())) {
            listener.updateProviders(new ProviderGroup(flatComposeData(mergedResult)));
        } else {
            final Map<String, List<ProviderInfo>> zoneData = mergedResult.getZoneData();

            List<ProviderGroup> result = new ArrayList<ProviderGroup>();

            for (Map.Entry<String, List<ProviderInfo>> dataEntry : zoneData.entrySet()) {

                //localZone 的特殊放到 default 分组一份.为了在目标 zone 不可用的情况下兜底
                if (dataEntry.getKey().equalsIgnoreCase(mergedResult.getLocalZone())) {
                    result.add(new ProviderGroup(dataEntry.getValue()));
                }
                //其他 zone 的正常放
                result.add(new ProviderGroup(dataEntry.getKey(), dataEntry.getValue()));

            }

            listener.updateAllProviders(result);

        }
    }
 
Example #14
Source File: MulticastRegistry.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
private void clean() {
    Map<String, ProviderGroup> allProviderCache = this.allProviderCache;
    for (Map.Entry<String, ProviderGroup> entry : allProviderCache.entrySet()) {
        List<ProviderInfo> providerInfos = entry.getValue().getProviderInfos();
        if (CommonUtils.isNotEmpty(providerInfos)) {
            for (ProviderInfo providerInfo : providerInfos) {
                if (isExpired(providerInfo)) {
                    if (LOGGER.isWarnEnabled()) {
                        LOGGER.warn("Clean expired provider " + providerInfos);
                    }
                    doUnRegister(entry.getKey(), providerInfo);
                }
            }

        }
    }
}
 
Example #15
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 #16
Source File: LocalRegistryHelper.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
private static String marshalCache(Map<String, ProviderGroup> memoryCache) {
    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, ProviderGroup> entry : memoryCache.entrySet()) {
        ProviderGroup group = entry.getValue();
        if (group != null) {
            List<ProviderInfo> ps = group.getProviderInfos();
            if (CommonUtils.isNotEmpty(ps)) {
                sb.append(entry.getKey()).append(SEPARATORSTR);
                for (ProviderInfo providerInfo : ps) {
                    sb.append(ProviderHelper.toUrl(providerInfo)).append(SEPARATORSTR);
                }
                sb.append(FileUtils.LINE_SEPARATOR);
            }
        }
    }
    return sb.toString();
}
 
Example #17
Source File: MulticastRegistryHelper.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 转为服务端提供者对象
 *
 * @param config 服务提供者配置
 * @param server 服务端
 * @return 本地服务提供者对象
 */
public static ProviderInfo convertProviderToProviderInfo(ProviderConfig config, ServerConfig server) {
    ProviderInfo providerInfo = new ProviderInfo()
        .setPort(server.getPort())
        .setWeight(config.getWeight())
        .setSerializationType(config.getSerialization())
        .setProtocolType(server.getProtocol())
        .setPath(server.getContextPath())
        .setStaticAttrs(config.getParameters());
    String host = server.getHost();
    if (NetUtils.isLocalHost(host) || NetUtils.isAnyHost(host)) {
        host = SystemInfo.getLocalHost();
    }
    providerInfo.setHost(host);
    return providerInfo;
}
 
Example #18
Source File: LocalRegistry.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 注册单条服务信息
 *
 * @param appName      应用名
 * @param serviceName  服务关键字
 * @param providerInfo 服务提供者数据
 */
protected void doRegister(String appName, String serviceName, ProviderInfo providerInfo) {
    if (LOGGER.isInfoEnabled(appName)) {
        LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_ROUTE_REGISTRY_PUB, serviceName));
    }
    //{service : [provider...]}
    ProviderGroup oldGroup = memoryCache.get(serviceName);
    if (oldGroup != null) { // 存在老的key
        oldGroup.add(providerInfo);
    } else { // 没有老的key,第一次加入
        List<ProviderInfo> news = new ArrayList<ProviderInfo>();
        news.add(providerInfo);
        memoryCache.put(serviceName, new ProviderGroup(news));
    }
    // 备份到文件 改为定时写
    needBackup = true;
    doWriteFile();

    if (subscribe) {
        notifyConsumerListeners(serviceName, memoryCache.get(serviceName));
    }
}
 
Example #19
Source File: LocalPreferenceLoadBalancer.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public ProviderInfo doSelect(SofaRequest invocation, List<ProviderInfo> providerInfos) {
    String localhost = SystemInfo.getLocalHost();
    if (StringUtils.isEmpty(localhost)) {
        return super.doSelect(invocation, providerInfos);
    }
    List<ProviderInfo> localProviderInfo = new ArrayList<ProviderInfo>();
    for (ProviderInfo providerInfo : providerInfos) { // 解析IP,看是否和本地一致
        if (localhost.equals(providerInfo.getHost())) {
            localProviderInfo.add(providerInfo);
        }
    }
    if (CommonUtils.isNotEmpty(localProviderInfo)) { // 命中本机的服务端
        return super.doSelect(invocation, localProviderInfo);
    } else { // 没有命中本机上的服务端
        return super.doSelect(invocation, providerInfos);
    }
}
 
Example #20
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 #21
Source File: DirectUrlRouter.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public List<ProviderInfo> route(SofaRequest request, List<ProviderInfo> providerInfos) {
    AddressHolder addressHolder = consumerBootstrap.getCluster().getAddressHolder();
    if (addressHolder != null) {
        List<ProviderInfo> current = addressHolder.getProviderInfos(RpcConstants.ADDRESS_DIRECT_GROUP);
        if (providerInfos != null) {
            providerInfos.addAll(current);
        } else {
            providerInfos = current;
        }
    }
    recordRouterWay(RPC_DIRECT_URL_ROUTER);
    return providerInfos;
}
 
Example #22
Source File: ClientSyncReceiveEvent.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
public ClientSyncReceiveEvent(ConsumerConfig consumerConfig, ProviderInfo providerInfo,
                              SofaRequest request, SofaResponse response, Throwable throwable) {
    this.consumerConfig = consumerConfig;
    this.providerInfo = providerInfo;
    this.request = request;
    this.response = response;
    this.throwable = throwable;
}
 
Example #23
Source File: ZookeeperRegistryHelper.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
static ProviderInfo convertUrlToProvider(String providerPath,
                                         ChildData childData) throws UnsupportedEncodingException {
    String url = childData.getPath().substring(providerPath.length() + 1); // 去掉头部
    url = URLDecoder.decode(url, "UTF-8");
    ProviderInfo providerInfo = ProviderHelper.toProviderInfo(url);

    processWarmUpWeight(providerInfo);

    return providerInfo;
}
 
Example #24
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 #25
Source File: ClientTransportFactoryTest.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Test
public void doNotReuseTest() {
    ClientTransportConfig config = new ClientTransportConfig();
    config.setProviderInfo(new ProviderInfo().setHost("127.0.0.1").setPort(12222))
        .setContainer("test");

    TestClientTransport clientTransport = (TestClientTransport) ClientTransportFactory.getClientTransport(config);

    ClientTransportConfig config2 = new ClientTransportConfig();
    config2.setProviderInfo(new ProviderInfo().setHost("127.0.0.1").setPort(12222))
        .setContainer("test");
    TestClientTransport clientTransport2 = (TestClientTransport) ClientTransportFactory.getClientTransport(config2);

    Assert.assertTrue(clientTransport != clientTransport2);

    ClientTransportConfig config3 = new ClientTransportConfig();
    config3.setProviderInfo(new ProviderInfo().setHost("127.0.0.1").setPort(12223))
        .setContainer("test");
    TestClientTransport clientTransport3 = (TestClientTransport) ClientTransportFactory.getClientTransport(config3);
    Assert.assertFalse(clientTransport == clientTransport3);

    ClientTransportFactory.releaseTransport(null, 500);

    clientTransport.setRequest(4);
    ClientTransportFactory.releaseTransport(clientTransport, 500);
    Assert.assertEquals(2, ClientTransportFactory.getClientTransportHolder().size());

    clientTransport2.setRequest(0);
    ClientTransportFactory.releaseTransport(clientTransport2, 500);
    Assert.assertEquals(1, ClientTransportFactory.getClientTransportHolder().size());

    ClientTransportFactory.closeAll();

    Assert.assertEquals(0, ClientTransportFactory.getClientTransportHolder().size());
}
 
Example #26
Source File: LocalRegistry.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public void register(ProviderConfig config) {
    String appName = config.getAppName();
    if (!registryConfig.isRegister()) {
        if (LOGGER.isInfoEnabled(appName)) {
            LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_REGISTRY_IGNORE));
        }
        return;
    }
    if (!config.isRegister()) { // 注册中心不注册或者服务不注册
        return;
    }
    List<ServerConfig> serverConfigs = config.getServer();
    if (CommonUtils.isNotEmpty(serverConfigs)) {
        for (ServerConfig server : serverConfigs) {
            String serviceName = LocalRegistryHelper.buildListDataId(config, server.getProtocol());
            ProviderInfo providerInfo = LocalRegistryHelper.convertProviderToProviderInfo(config, server);
            if (LOGGER.isInfoEnabled(appName)) {
                LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_ROUTE_REGISTRY_PUB_START, serviceName));
            }
            doRegister(appName, serviceName, providerInfo);

            if (LOGGER.isInfoEnabled(appName)) {
                LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_ROUTE_REGISTRY_PUB_OVER, serviceName));
            }
        }
        if (EventBus.isEnable(ProviderPubEvent.class)) {
            ProviderPubEvent event = new ProviderPubEvent(config);
            EventBus.post(event);
        }

    }
}
 
Example #27
Source File: ClientTransportFactoryTest.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Test
public void testReverseClientTransport() {
    ClientTransportConfig config = new ClientTransportConfig();
    config.setProviderInfo(new ProviderInfo().setHost("127.0.0.1").setPort(12222))
        .setContainer("test");
    TestClientTransport clientTransport = (TestClientTransport) ClientTransportFactory.getClientTransport(config);

    TestChannel serverChannel = new TestChannel(clientTransport.localAddress(), clientTransport.remoteAddress());

    TestClientTransport clientTransport2 = (TestClientTransport) ClientTransportFactory.
        getReverseClientTransport("test", serverChannel);

    Assert.assertEquals(serverChannel, clientTransport2.getChannel());

    String key = NetUtils.channelToString(serverChannel.remoteAddress(), serverChannel.localAddress());
    TestClientTransport clientTransport3 = (TestClientTransport)
            ClientTransportFactory.getReverseClientTransport(key);
    Assert.assertEquals(clientTransport2, clientTransport3);

    ClientTransportFactory.removeReverseClientTransport(key);
    TestClientTransport clientTransport4 = (TestClientTransport)
            ClientTransportFactory.getReverseClientTransport(key);
    Assert.assertNull(clientTransport4);

    ClientTransportFactory.closeAll();

    Assert.assertEquals(0, ClientTransportFactory.getClientTransportHolder().size());
}
 
Example #28
Source File: MeshRegistry.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 反注册服务信息
 *
 * @param serviceName  服务关键字
 * @param providerInfo 服务提供者数据
 */
protected void doUnRegister(String serviceName, ProviderInfo providerInfo) {

    UnPublishServiceRequest unPublishServiceRequest = new UnPublishServiceRequest();
    unPublishServiceRequest.setServiceName(serviceName);
    client.unPublishService(unPublishServiceRequest);

}
 
Example #29
Source File: SofaRegistrySubscribeCallback.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
protected List<ProviderInfo> flatComposeData(ComposeUserData userData) {
    List<ProviderInfo> result = new ArrayList<ProviderInfo>();

    Map<String, List<ProviderInfo>> zoneData = userData.getZoneData();

    for (Map.Entry<String, List<ProviderInfo>> entry : zoneData.entrySet()) {
        result.addAll(entry.getValue());
    }

    return result;
}
 
Example #30
Source File: LocalRegistry.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public void unRegister(ProviderConfig config) {
    String appName = config.getAppName();
    if (!registryConfig.isRegister()) { // 注册中心不注册
        if (LOGGER.isInfoEnabled(appName)) {
            LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_REGISTRY_IGNORE));
        }
        return;
    }
    if (!config.isRegister()) { // 服务不注册
        return;
    }
    List<ServerConfig> serverConfigs = config.getServer();
    if (CommonUtils.isNotEmpty(serverConfigs)) {
        for (ServerConfig server : serverConfigs) {
            String serviceName = LocalRegistryHelper.buildListDataId(config, server.getProtocol());
            ProviderInfo providerInfo = LocalRegistryHelper.convertProviderToProviderInfo(config, server);
            try {
                doUnRegister(serviceName, providerInfo);
                if (LOGGER.isInfoEnabled(appName)) {
                    LOGGER.infoWithApp(appName,
                        LogCodes.getLog(LogCodes.INFO_ROUTE_REGISTRY_UNPUB, serviceName, "1"));
                }
            } catch (Exception e) {
                LOGGER.errorWithApp(appName, LogCodes.getLog(LogCodes.INFO_ROUTE_REGISTRY_UNPUB, serviceName, "0"),
                    e);
            }
        }
    }
}