Search in sources :

Example 1 with ProviderInfoListener

use of com.alipay.sofa.rpc.listener.ProviderInfoListener in project sofa-rpc by sofastack.

the class ZookeeperRegistry method subscribe.

@Override
public List<ProviderGroup> subscribe(final ConsumerConfig config) {
    String appName = config.getAppName();
    if (!registryConfig.isSubscribe()) {
        // 注册中心不订阅
        if (LOGGER.isInfoEnabled(appName)) {
            LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_REGISTRY_IGNORE));
        }
        return null;
    }
    // 订阅如果有必要
    subscribeConsumerUrls(config);
    if (config.isSubscribe()) {
        List<ProviderInfo> matchProviders;
        // 订阅配置
        if (!INTERFACE_CONFIG_CACHE.containsKey(buildConfigPath(rootPath, config))) {
            // 订阅接口级配置
            subscribeConfig(config, config.getConfigListener());
        }
        if (!INTERFACE_OVERRIDE_CACHE.containsKey(buildOverridePath(rootPath, config))) {
            // 订阅IP级配置
            subscribeOverride(config, config.getConfigListener());
        }
        // 订阅Providers节点
        try {
            if (providerObserver == null) {
                // 初始化
                providerObserver = new ZookeeperProviderObserver();
            }
            final String providerPath = buildProviderPath(rootPath, config);
            if (LOGGER.isInfoEnabled(appName)) {
                LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_ROUTE_REGISTRY_SUB, providerPath));
            }
            PathChildrenCache pathChildrenCache = INTERFACE_PROVIDER_CACHE.get(config);
            if (pathChildrenCache == null) {
                // 监听配置节点下 子节点增加、子节点删除、子节点Data修改事件
                ProviderInfoListener providerInfoListener = config.getProviderInfoListener();
                providerObserver.addProviderListener(config, providerInfoListener);
                // TODO 换成监听父节点变化(只是监听变化了,而不通知变化了什么,然后客户端自己来拉数据的)
                pathChildrenCache = new PathChildrenCache(zkClient, providerPath, true);
                final PathChildrenCache finalPathChildrenCache = pathChildrenCache;
                pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {

                    @Override
                    public void childEvent(CuratorFramework client1, PathChildrenCacheEvent event) throws Exception {
                        if (LOGGER.isDebugEnabled(config.getAppName())) {
                            LOGGER.debugWithApp(config.getAppName(), "Receive zookeeper event: " + "type=[" + event.getType() + "]");
                        }
                        switch(event.getType()) {
                            case // 加了一个provider
                            CHILD_ADDED:
                                providerObserver.addProvider(config, providerPath, event.getData(), finalPathChildrenCache.getCurrentData());
                                break;
                            case // 删了一个provider
                            CHILD_REMOVED:
                                providerObserver.removeProvider(config, providerPath, event.getData(), finalPathChildrenCache.getCurrentData());
                                break;
                            case // 更新一个Provider
                            CHILD_UPDATED:
                                providerObserver.updateProvider(config, providerPath, event.getData(), finalPathChildrenCache.getCurrentData());
                                break;
                            default:
                                break;
                        }
                    }
                });
                pathChildrenCache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
                INTERFACE_PROVIDER_CACHE.put(config, pathChildrenCache);
            }
            List<ProviderInfo> providerInfos = ZookeeperRegistryHelper.convertUrlsToProviders(providerPath, pathChildrenCache.getCurrentData());
            matchProviders = ZookeeperRegistryHelper.matchProviderInfos(config, providerInfos);
        } catch (Exception e) {
            throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_SUB_PROVIDER, EXT_NAME), e);
        }
        if (EventBus.isEnable(ConsumerSubEvent.class)) {
            ConsumerSubEvent event = new ConsumerSubEvent(config);
            EventBus.post(event);
        }
        return Collections.singletonList(new ProviderGroup().addAll(matchProviders));
    }
    return null;
}
Also used : PathChildrenCacheListener(org.apache.curator.framework.recipes.cache.PathChildrenCacheListener) PathChildrenCacheEvent(org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent) ProviderInfoListener(com.alipay.sofa.rpc.listener.ProviderInfoListener) ConsumerSubEvent(com.alipay.sofa.rpc.event.ConsumerSubEvent) KeeperException(org.apache.zookeeper.KeeperException) SofaRpcRuntimeException(com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException) CuratorFramework(org.apache.curator.framework.CuratorFramework) ProviderInfo(com.alipay.sofa.rpc.client.ProviderInfo) SofaRpcRuntimeException(com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException) PathChildrenCache(org.apache.curator.framework.recipes.cache.PathChildrenCache) ProviderGroup(com.alipay.sofa.rpc.client.ProviderGroup)

Example 2 with ProviderInfoListener

use of com.alipay.sofa.rpc.listener.ProviderInfoListener in project sofa-rpc by sofastack.

the class MockTestRegistry method subscribe.

@Override
public List<ProviderGroup> subscribe(ConsumerConfig config) {
    String key = buildKey(config);
    Map<ConsumerConfig, ProviderInfoListener> listeners = notifyListeners.get(key);
    if (listeners == null) {
        listeners = new ConcurrentHashMap<ConsumerConfig, ProviderInfoListener>();
        Map<ConsumerConfig, ProviderInfoListener> old = notifyListeners.putIfAbsent(key, listeners);
        if (old != null) {
            listeners = old;
        }
    }
    final ProviderInfoListener listener = config.getProviderInfoListener();
    listeners.put(config, listener);
    ProviderGroup group = memoryCache.get(key);
    List<ProviderGroup> groups = new ArrayList<ProviderGroup>();
    if (group != null) {
        groups.add(group);
    }
    return doReturn(listener, groups);
}
Also used : ProviderInfoListener(com.alipay.sofa.rpc.listener.ProviderInfoListener) ArrayList(java.util.ArrayList) ConsumerConfig(com.alipay.sofa.rpc.config.ConsumerConfig) ProviderGroup(com.alipay.sofa.rpc.client.ProviderGroup)

Example 3 with ProviderInfoListener

use of com.alipay.sofa.rpc.listener.ProviderInfoListener in project sofa-rpc by sofastack.

the class SofaRegistry method subscribe.

@Override
public List<ProviderGroup> subscribe(ConsumerConfig config) {
    ProviderInfoListener providerInfoListener = config.getProviderInfoListener();
    String appName = config.getAppName();
    if (!registryConfig.isSubscribe()) {
        // 注册中心不订阅
        if (LOGGER.isInfoEnabled(appName)) {
            LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_REGISTRY_IGNORE));
        }
        return null;
    }
    if (!config.isSubscribe()) {
        // 服务不订阅
        return null;
    }
    String serviceName = SofaRegistryHelper.buildListDataId(config, config.getProtocol());
    SofaRegistrySubscribeCallback callback;
    Subscriber listSubscriber = subscribers.get(serviceName);
    Configurator attrSubscriber;
    if (listSubscriber != null && providerInfoListener != null) {
        // 已经有人订阅过这个Key,那么地址已经存在了,
        callback = (SofaRegistrySubscribeCallback) listSubscriber.getDataObserver();
        callback.addProviderInfoListener(serviceName, config, providerInfoListener);
        // 使用旧数据通知下
        callback.handleDataToListener(serviceName, config, providerInfoListener);
    } else {
        callback = new SofaRegistrySubscribeCallback();
        callback.addProviderInfoListener(serviceName, config, providerInfoListener);
        // 生成订阅对象,并添加额外属性
        SubscriberRegistration subscriberRegistration = new SubscriberRegistration(serviceName, callback);
        String groupId = config.getParameter(SofaRegistryConstants.SOFA_GROUP_KEY);
        groupId = groupId == null ? SofaRegistryHelper.SUBSCRIBER_LIST_GROUP_ID : groupId;
        addAttributes(subscriberRegistration, groupId);
        ConfiguratorRegistration configRegistration = new ConfiguratorRegistration(serviceName, callback);
        addAttributes(configRegistration, SofaRegistryHelper.SUBSCRIBER_CONFIG_GROUP_ID);
        // 去配置中心订阅
        // 去注册
        listSubscriber = SofaRegistryClient.getRegistryClient(appName, registryConfig).register(subscriberRegistration);
        attrSubscriber = SofaRegistryClient.getRegistryClient(appName, registryConfig).register(configRegistration);
        // 放入缓存
        subscribers.put(serviceName, listSubscriber);
        configurators.put(serviceName, attrSubscriber);
    }
    // 统一走异步获取地址,所以此处返回null
    return null;
}
Also used : ProviderInfoListener(com.alipay.sofa.rpc.listener.ProviderInfoListener) Subscriber(com.alipay.sofa.registry.client.api.Subscriber) Configurator(com.alipay.sofa.registry.client.api.Configurator) ConfiguratorRegistration(com.alipay.sofa.registry.client.api.registration.ConfiguratorRegistration) SubscriberRegistration(com.alipay.sofa.registry.client.api.registration.SubscriberRegistration)

Example 4 with ProviderInfoListener

use of com.alipay.sofa.rpc.listener.ProviderInfoListener in project sofa-rpc by sofastack.

the class NacosRegistry method subscribe.

@Override
public List<ProviderGroup> subscribe(final ConsumerConfig config) {
    String appName = config.getAppName();
    if (!registryConfig.isSubscribe()) {
        // registry ignored
        if (LOGGER.isInfoEnabled(appName)) {
            LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_REGISTRY_IGNORE));
        }
        return null;
    }
    if (config.isSubscribe()) {
        String serviceName = NacosRegistryHelper.buildServiceName(config, config.getProtocol());
        if (LOGGER.isInfoEnabled()) {
            LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_ROUTE_REGISTRY_SUB, serviceName));
        }
        try {
            if (providerObserver == null) {
                providerObserver = new NacosRegistryProviderObserver();
            }
            ProviderInfoListener providerInfoListener = config.getProviderInfoListener();
            providerObserver.addProviderListener(config, providerInfoListener);
            EventListener eventListener = new EventListener() {

                @Override
                public void onEvent(Event event) {
                    if (event instanceof NamingEvent) {
                        NamingEvent namingEvent = (NamingEvent) event;
                        List<Instance> instances = namingEvent.getInstances();
                        // avoid npe
                        if (null == instances) {
                            instances = new ArrayList<Instance>();
                        }
                        instances.removeIf(i -> !i.isEnabled());
                        providerObserver.updateProviders(config, instances);
                    }
                }
            };
            namingService.subscribe(serviceName, defaultCluster, eventListener);
            consumerListeners.put(config, eventListener);
            List<Instance> allInstances = namingService.getAllInstances(serviceName, defaultCluster);
            List<ProviderInfo> providerInfos = NacosRegistryHelper.convertInstancesToProviders(allInstances);
            List<ProviderInfo> matchProviders = RegistryUtils.matchProviderInfos(config, providerInfos);
            return Collections.singletonList(new ProviderGroup().addAll(matchProviders));
        } catch (SofaRpcRuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_SUB_PROVIDER, EXT_NAME), e);
        }
    }
    return null;
}
Also used : ProviderInfoListener(com.alipay.sofa.rpc.listener.ProviderInfoListener) Instance(com.alibaba.nacos.api.naming.pojo.Instance) NamingEvent(com.alibaba.nacos.api.naming.listener.NamingEvent) NacosException(com.alibaba.nacos.api.exception.NacosException) SofaRpcRuntimeException(com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException) ProviderInfo(com.alipay.sofa.rpc.client.ProviderInfo) SofaRpcRuntimeException(com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException) Event(com.alibaba.nacos.api.naming.listener.Event) NamingEvent(com.alibaba.nacos.api.naming.listener.NamingEvent) ProviderGroup(com.alipay.sofa.rpc.client.ProviderGroup) EventListener(com.alibaba.nacos.api.naming.listener.EventListener)

Example 5 with ProviderInfoListener

use of com.alipay.sofa.rpc.listener.ProviderInfoListener in project sofa-rpc by sofastack.

the class DefaultConsumerBootstrap method subscribeFromRegistries.

/**
 * Subscribe provider list from all registries, the providers will be merged.
 *
 * @return Provider group list
 */
protected List<ProviderGroup> subscribeFromRegistries() {
    List<ProviderGroup> result = new ArrayList<ProviderGroup>();
    List<RegistryConfig> registryConfigs = consumerConfig.getRegistry();
    if (CommonUtils.isEmpty(registryConfigs)) {
        return result;
    }
    // 是否等待结果
    int addressWaitTime = consumerConfig.getAddressWait();
    int maxAddressWaitTime = SofaConfigs.getIntegerValue(consumerConfig.getAppName(), SofaOptions.CONFIG_MAX_ADDRESS_WAIT_TIME, SofaOptions.MAX_ADDRESS_WAIT_TIME);
    addressWaitTime = addressWaitTime < 0 ? maxAddressWaitTime : Math.min(addressWaitTime, maxAddressWaitTime);
    ProviderInfoListener listener = consumerConfig.getProviderInfoListener();
    respondRegistries = addressWaitTime == 0 ? null : new CountDownLatch(registryConfigs.size());
    // 从注册中心订阅 {groupName: ProviderGroup}
    Map<String, ProviderGroup> tmpProviderInfoList = new HashMap<String, ProviderGroup>();
    for (RegistryConfig registryConfig : registryConfigs) {
        Registry registry = RegistryFactory.getRegistry(registryConfig);
        registry.init();
        registry.start();
        try {
            List<ProviderGroup> current;
            try {
                if (respondRegistries != null) {
                    consumerConfig.setProviderInfoListener(new WrapperClusterProviderInfoListener(listener, respondRegistries));
                }
                current = registry.subscribe(consumerConfig);
            } finally {
                if (respondRegistries != null) {
                    consumerConfig.setProviderInfoListener(listener);
                }
            }
            if (current == null) {
                // 未同步返回结果
                continue;
            } else {
                if (respondRegistries != null) {
                    respondRegistries.countDown();
                }
            }
            for (ProviderGroup group : current) {
                // 当前注册中心的
                String groupName = group.getName();
                if (!group.isEmpty()) {
                    ProviderGroup oldGroup = tmpProviderInfoList.get(groupName);
                    if (oldGroup != null) {
                        oldGroup.addAll(group.getProviderInfos());
                    } else {
                        tmpProviderInfoList.put(groupName, group);
                    }
                }
            }
        } catch (SofaRpcRuntimeException e) {
            throw e;
        } catch (Throwable e) {
            String appName = consumerConfig.getAppName();
            if (LOGGER.isWarnEnabled(appName)) {
                LOGGER.warnWithApp(appName, LogCodes.getLog(LogCodes.ERROR_SUBSCRIBE_FROM_REGISTRY, registryConfig.getId()), e);
            }
        }
    }
    if (respondRegistries != null) {
        try {
            respondRegistries.await(addressWaitTime, TimeUnit.MILLISECONDS);
        } catch (Exception ignore) {
        // NOPMD
        }
    }
    return new ArrayList<ProviderGroup>(tmpProviderInfoList.values());
}
Also used : RegistryConfig(com.alipay.sofa.rpc.config.RegistryConfig) ProviderInfoListener(com.alipay.sofa.rpc.listener.ProviderInfoListener) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ArrayList(java.util.ArrayList) Registry(com.alipay.sofa.rpc.registry.Registry) CountDownLatch(java.util.concurrent.CountDownLatch) SofaRpcRuntimeException(com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException) SofaRpcRuntimeException(com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException) ProviderGroup(com.alipay.sofa.rpc.client.ProviderGroup)

Aggregations

ProviderInfoListener (com.alipay.sofa.rpc.listener.ProviderInfoListener)11 ProviderGroup (com.alipay.sofa.rpc.client.ProviderGroup)10 ProviderInfo (com.alipay.sofa.rpc.client.ProviderInfo)5 ConsumerConfig (com.alipay.sofa.rpc.config.ConsumerConfig)4 ArrayList (java.util.ArrayList)4 SofaRpcRuntimeException (com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException)3 Configurator (com.alipay.sofa.registry.client.api.Configurator)2 Subscriber (com.alipay.sofa.registry.client.api.Subscriber)2 ServerConfig (com.alipay.sofa.rpc.config.ServerConfig)2 ConsumerSubEvent (com.alipay.sofa.rpc.event.ConsumerSubEvent)2 List (java.util.List)2 NacosException (com.alibaba.nacos.api.exception.NacosException)1 Event (com.alibaba.nacos.api.naming.listener.Event)1 EventListener (com.alibaba.nacos.api.naming.listener.EventListener)1 NamingEvent (com.alibaba.nacos.api.naming.listener.NamingEvent)1 Instance (com.alibaba.nacos.api.naming.pojo.Instance)1 ConfiguratorRegistration (com.alipay.sofa.registry.client.api.registration.ConfiguratorRegistration)1 SubscriberRegistration (com.alipay.sofa.registry.client.api.registration.SubscriberRegistration)1 RegistryConfig (com.alipay.sofa.rpc.config.RegistryConfig)1 Registry (com.alipay.sofa.rpc.registry.Registry)1