Dubbo 源码阅读(二)getActivateExtension

某些情况下,同一个接口的多个实现需要同时发挥作用,比如filter链。此时需要按条件选择一批实现类来工作。

/**
 * @Activate(group = {"group1","group2"},order = 1,value = "value1")打在某个自定义的Filter上
 */
@Test
public void testActivate() {
    ExtensionLoader extensionLoader = ExtensionLoader.getExtensionLoader(Filter.class);

    URL url = URL.valueOf("test://localhost/test");
    //有了这个,@Activate()里必须有value = "value1"
    url = url.addParameter("value1", "anything");
    //添加a实例,去掉c实例
    url = url.addParameter("myfilter", "a,-c");

    //得到所有的可激活拓展类
    List<Filter> list = extensionLoader.getActivateExtension(url,"myfilter","group1");
    for (Filter filter:list){
        filter.invoke(null,null);
    }
}

在这里插入图片描述
在这里插入图片描述

跟 getActivateExtension:

public List<T> getActivateExtension(URL url, String key, String group) {
    String value = url.getParameter(key);
    return getActivateExtension(url, value == null || value.length() == 0 ? null : Constants.COMMA_SPLIT_PATTERN.split(value), group);
}

跟 getActivateExtension:

public List<T> getActivateExtension(URL url, String[] values, String group) {
    List<T> exts = new ArrayList<T>();
    //示例中,这里为a,-c
    List<String> names = values == null ? new ArrayList<String>(0) : Arrays.asList(values);
    //如果不含有"-default"
    if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) {
    	//loadExtensionClasses()
        getExtensionClasses();
        for (Map.Entry<String, Activate> entry : cachedActivates.entrySet()) {
            String name = entry.getKey();
            Activate activate = entry.getValue();
            if (isMatchGroup(group, activate.group())) {
                T ext = getExtension(name);
                if (!names.contains(name)
                        && !names.contains(Constants.REMOVE_VALUE_PREFIX + name)
                        && isActive(activate, url)) {
                    exts.add(ext);
                }
            }
        }
        Collections.sort(exts, ActivateComparator.COMPARATOR);
    }
    List<T> usrs = new ArrayList<T>();
    for (int i = 0; i < names.size(); i++) {
        String name = names.get(i);
        //name不以-开头且names里没有-name
        if (!name.startsWith(Constants.REMOVE_VALUE_PREFIX)
                && !names.contains(Constants.REMOVE_VALUE_PREFIX + name)) {
            if (Constants.DEFAULT_KEY.equals(name)) {
                if (!usrs.isEmpty()) {
                    exts.addAll(0, usrs);
                    usrs.clear();
                }
            } else {
                T ext = getExtension(name);
                usrs.add(ext);
            }
        }
    }
    if (!usrs.isEmpty()) {
        exts.addAll(usrs);
    }
    return exts;
}
©️2020 CSDN 皮肤主题: 岁月 设计师:pinMode 返回首页