Search in sources :

Example 11 with RegistryConfig

use of com.alibaba.dubbo.config.RegistryConfig in project dubbo by alibaba.

the class ConfigTest method testAppendFilter.

@Test
public void testAppendFilter() throws Exception {
    ProviderConfig provider = new ProviderConfig();
    provider.setFilter("classloader,monitor");
    ServiceConfig<DemoService> service = new ServiceConfig<DemoService>();
    service.setFilter("accesslog,trace");
    service.setProvider(provider);
    service.setProtocol(new ProtocolConfig("dubbo", 20880));
    service.setApplication(new ApplicationConfig("provider"));
    service.setRegistry(new RegistryConfig(RegistryConfig.NO_AVAILABLE));
    service.setInterface(DemoService.class);
    service.setRef(new DemoServiceImpl());
    try {
        service.export();
        List<URL> urls = service.toUrls();
        assertNotNull(urls);
        assertEquals(1, urls.size());
        assertEquals("classloader,monitor,accesslog,trace", urls.get(0).getParameter("service.filter"));
        ConsumerConfig consumer = new ConsumerConfig();
        consumer.setFilter("classloader,monitor");
        ReferenceConfig<DemoService> reference = new ReferenceConfig<DemoService>();
        reference.setFilter("accesslog,trace");
        reference.setConsumer(consumer);
        reference.setApplication(new ApplicationConfig("consumer"));
        reference.setRegistry(new RegistryConfig(RegistryConfig.NO_AVAILABLE));
        reference.setInterface(DemoService.class);
        reference.setUrl("dubbo://" + NetUtils.getLocalHost() + ":20880?" + DemoService.class.getName() + "?check=false");
        try {
            reference.get();
            urls = reference.toUrls();
            assertNotNull(urls);
            assertEquals(1, urls.size());
            assertEquals("classloader,monitor,accesslog,trace", urls.get(0).getParameter("reference.filter"));
        } finally {
            reference.destroy();
        }
    } finally {
        service.unexport();
    }
}
Also used : RegistryConfig(com.alibaba.dubbo.config.RegistryConfig) ProviderConfig(com.alibaba.dubbo.config.ProviderConfig) DemoService(com.alibaba.dubbo.config.spring.api.DemoService) URL(com.alibaba.dubbo.common.URL) ServiceConfig(com.alibaba.dubbo.config.ServiceConfig) ApplicationConfig(com.alibaba.dubbo.config.ApplicationConfig) ReferenceConfig(com.alibaba.dubbo.config.ReferenceConfig) ConsumerConfig(com.alibaba.dubbo.config.ConsumerConfig) ProtocolConfig(com.alibaba.dubbo.config.ProtocolConfig) DemoServiceImpl(com.alibaba.dubbo.config.spring.impl.DemoServiceImpl) Test(org.junit.Test)

Example 12 with RegistryConfig

use of com.alibaba.dubbo.config.RegistryConfig in project dubbo by alibaba.

the class DubboBeanDefinitionParser method parse.

@SuppressWarnings("unchecked")
private static BeanDefinition parse(Element element, ParserContext parserContext, Class<?> beanClass, boolean required) {
    RootBeanDefinition beanDefinition = new RootBeanDefinition();
    beanDefinition.setBeanClass(beanClass);
    beanDefinition.setLazyInit(false);
    String id = element.getAttribute("id");
    if ((id == null || id.length() == 0) && required) {
        String generatedBeanName = element.getAttribute("name");
        if (generatedBeanName == null || generatedBeanName.length() == 0) {
            if (ProtocolConfig.class.equals(beanClass)) {
                generatedBeanName = "dubbo";
            } else {
                generatedBeanName = element.getAttribute("interface");
            }
        }
        if (generatedBeanName == null || generatedBeanName.length() == 0) {
            generatedBeanName = beanClass.getName();
        }
        id = generatedBeanName;
        int counter = 2;
        while (parserContext.getRegistry().containsBeanDefinition(id)) {
            id = generatedBeanName + (counter++);
        }
    }
    if (id != null && id.length() > 0) {
        if (parserContext.getRegistry().containsBeanDefinition(id)) {
            throw new IllegalStateException("Duplicate spring bean id " + id);
        }
        parserContext.getRegistry().registerBeanDefinition(id, beanDefinition);
        beanDefinition.getPropertyValues().addPropertyValue("id", id);
    }
    if (ProtocolConfig.class.equals(beanClass)) {
        for (String name : parserContext.getRegistry().getBeanDefinitionNames()) {
            BeanDefinition definition = parserContext.getRegistry().getBeanDefinition(name);
            PropertyValue property = definition.getPropertyValues().getPropertyValue("protocol");
            if (property != null) {
                Object value = property.getValue();
                if (value instanceof ProtocolConfig && id.equals(((ProtocolConfig) value).getName())) {
                    definition.getPropertyValues().addPropertyValue("protocol", new RuntimeBeanReference(id));
                }
            }
        }
    } else if (ServiceBean.class.equals(beanClass)) {
        String className = element.getAttribute("class");
        if (className != null && className.length() > 0) {
            RootBeanDefinition classDefinition = new RootBeanDefinition();
            classDefinition.setBeanClass(ReflectUtils.forName(className));
            classDefinition.setLazyInit(false);
            parseProperties(element.getChildNodes(), classDefinition);
            beanDefinition.getPropertyValues().addPropertyValue("ref", new BeanDefinitionHolder(classDefinition, id + "Impl"));
        }
    } else if (ProviderConfig.class.equals(beanClass)) {
        parseNested(element, parserContext, ServiceBean.class, true, "service", "provider", id, beanDefinition);
    } else if (ConsumerConfig.class.equals(beanClass)) {
        parseNested(element, parserContext, ReferenceBean.class, false, "reference", "consumer", id, beanDefinition);
    }
    Set<String> props = new HashSet<String>();
    ManagedMap parameters = null;
    for (Method setter : beanClass.getMethods()) {
        String name = setter.getName();
        if (name.length() > 3 && name.startsWith("set") && Modifier.isPublic(setter.getModifiers()) && setter.getParameterTypes().length == 1) {
            Class<?> type = setter.getParameterTypes()[0];
            String property = StringUtils.camelToSplitName(name.substring(3, 4).toLowerCase() + name.substring(4), "-");
            props.add(property);
            Method getter = null;
            try {
                getter = beanClass.getMethod("get" + name.substring(3), new Class<?>[0]);
            } catch (NoSuchMethodException e) {
                try {
                    getter = beanClass.getMethod("is" + name.substring(3), new Class<?>[0]);
                } catch (NoSuchMethodException e2) {
                }
            }
            if (getter == null || !Modifier.isPublic(getter.getModifiers()) || !type.equals(getter.getReturnType())) {
                continue;
            }
            if ("parameters".equals(property)) {
                parameters = parseParameters(element.getChildNodes(), beanDefinition);
            } else if ("methods".equals(property)) {
                parseMethods(id, element.getChildNodes(), beanDefinition, parserContext);
            } else if ("arguments".equals(property)) {
                parseArguments(id, element.getChildNodes(), beanDefinition, parserContext);
            } else {
                String value = element.getAttribute(property);
                if (value != null) {
                    value = value.trim();
                    if (value.length() > 0) {
                        if ("registry".equals(property) && RegistryConfig.NO_AVAILABLE.equalsIgnoreCase(value)) {
                            RegistryConfig registryConfig = new RegistryConfig();
                            registryConfig.setAddress(RegistryConfig.NO_AVAILABLE);
                            beanDefinition.getPropertyValues().addPropertyValue(property, registryConfig);
                        } else if ("registry".equals(property) && value.indexOf(',') != -1) {
                            parseMultiRef("registries", value, beanDefinition, parserContext);
                        } else if ("provider".equals(property) && value.indexOf(',') != -1) {
                            parseMultiRef("providers", value, beanDefinition, parserContext);
                        } else if ("protocol".equals(property) && value.indexOf(',') != -1) {
                            parseMultiRef("protocols", value, beanDefinition, parserContext);
                        } else {
                            Object reference;
                            if (isPrimitive(type)) {
                                if ("async".equals(property) && "false".equals(value) || "timeout".equals(property) && "0".equals(value) || "delay".equals(property) && "0".equals(value) || "version".equals(property) && "0.0.0".equals(value) || "stat".equals(property) && "-1".equals(value) || "reliable".equals(property) && "false".equals(value)) {
                                    // 兼容旧版本xsd中的default值
                                    value = null;
                                }
                                reference = value;
                            } else if ("protocol".equals(property) && ExtensionLoader.getExtensionLoader(Protocol.class).hasExtension(value) && (!parserContext.getRegistry().containsBeanDefinition(value) || !ProtocolConfig.class.getName().equals(parserContext.getRegistry().getBeanDefinition(value).getBeanClassName()))) {
                                if ("dubbo:provider".equals(element.getTagName())) {
                                    logger.warn("Recommended replace <dubbo:provider protocol=\"" + value + "\" ... /> to <dubbo:protocol name=\"" + value + "\" ... />");
                                }
                                // 兼容旧版本配置
                                ProtocolConfig protocol = new ProtocolConfig();
                                protocol.setName(value);
                                reference = protocol;
                            } else if ("monitor".equals(property) && (!parserContext.getRegistry().containsBeanDefinition(value) || !MonitorConfig.class.getName().equals(parserContext.getRegistry().getBeanDefinition(value).getBeanClassName()))) {
                                // 兼容旧版本配置
                                reference = convertMonitor(value);
                            } else if ("onreturn".equals(property)) {
                                int index = value.lastIndexOf(".");
                                String returnRef = value.substring(0, index);
                                String returnMethod = value.substring(index + 1);
                                reference = new RuntimeBeanReference(returnRef);
                                beanDefinition.getPropertyValues().addPropertyValue("onreturnMethod", returnMethod);
                            } else if ("onthrow".equals(property)) {
                                int index = value.lastIndexOf(".");
                                String throwRef = value.substring(0, index);
                                String throwMethod = value.substring(index + 1);
                                reference = new RuntimeBeanReference(throwRef);
                                beanDefinition.getPropertyValues().addPropertyValue("onthrowMethod", throwMethod);
                            } else {
                                if ("ref".equals(property) && parserContext.getRegistry().containsBeanDefinition(value)) {
                                    BeanDefinition refBean = parserContext.getRegistry().getBeanDefinition(value);
                                    if (!refBean.isSingleton()) {
                                        throw new IllegalStateException("The exported service ref " + value + " must be singleton! Please set the " + value + " bean scope to singleton, eg: <bean id=\"" + value + "\" scope=\"singleton\" ...>");
                                    }
                                }
                                reference = new RuntimeBeanReference(value);
                            }
                            beanDefinition.getPropertyValues().addPropertyValue(property, reference);
                        }
                    }
                }
            }
        }
    }
    NamedNodeMap attributes = element.getAttributes();
    int len = attributes.getLength();
    for (int i = 0; i < len; i++) {
        Node node = attributes.item(i);
        String name = node.getLocalName();
        if (!props.contains(name)) {
            if (parameters == null) {
                parameters = new ManagedMap();
            }
            String value = node.getNodeValue();
            parameters.put(name, new TypedStringValue(value, String.class));
        }
    }
    if (parameters != null) {
        beanDefinition.getPropertyValues().addPropertyValue("parameters", parameters);
    }
    return beanDefinition;
}
Also used : RegistryConfig(com.alibaba.dubbo.config.RegistryConfig) Node(org.w3c.dom.Node) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) ServiceBean(com.alibaba.dubbo.config.spring.ServiceBean) BeanDefinitionHolder(org.springframework.beans.factory.config.BeanDefinitionHolder) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) ConsumerConfig(com.alibaba.dubbo.config.ConsumerConfig) ProtocolConfig(com.alibaba.dubbo.config.ProtocolConfig) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference) Protocol(com.alibaba.dubbo.rpc.Protocol) ManagedMap(org.springframework.beans.factory.support.ManagedMap) HashSet(java.util.HashSet) NamedNodeMap(org.w3c.dom.NamedNodeMap) PropertyValue(org.springframework.beans.PropertyValue) Method(java.lang.reflect.Method) ReferenceBean(com.alibaba.dubbo.config.spring.ReferenceBean) TypedStringValue(org.springframework.beans.factory.config.TypedStringValue)

Example 13 with RegistryConfig

use of com.alibaba.dubbo.config.RegistryConfig in project dubbo by alibaba.

the class CacheTest method testCache.

@Test
public void testCache() throws Exception {
    ServiceConfig<CacheService> service = new ServiceConfig<CacheService>();
    service.setApplication(new ApplicationConfig("cache-provider"));
    service.setRegistry(new RegistryConfig("N/A"));
    service.setProtocol(new ProtocolConfig("dubbo", 29582));
    service.setInterface(CacheService.class.getName());
    service.setRef(new CacheServiceImpl());
    service.export();
    try {
        ReferenceConfig<CacheService> reference = new ReferenceConfig<CacheService>();
        reference.setApplication(new ApplicationConfig("cache-consumer"));
        reference.setInterface(CacheService.class);
        reference.setUrl("dubbo://127.0.0.1:29582?scope=remote&cache=true");
        CacheService cacheService = reference.get();
        try {
            // 测试缓存生效,多次调用返回同样的结果。(服务器端自增长返回值)
            String fix = null;
            for (int i = 0; i < 3; i++) {
                String result = cacheService.findCache("0");
                Assert.assertTrue(fix == null || fix.equals(result));
                fix = result;
                Thread.sleep(100);
            }
            // LRU的缺省cache.size为1000,执行1001次,应有溢出
            for (int n = 0; n < 1001; n++) {
                String pre = null;
                for (int i = 0; i < 10; i++) {
                    String result = cacheService.findCache(String.valueOf(n));
                    Assert.assertTrue(pre == null || pre.equals(result));
                    pre = result;
                }
            }
            // 测试LRU有移除最开始的一个缓存项
            String result = cacheService.findCache("0");
            Assert.assertFalse(fix == null || fix.equals(result));
        } finally {
            reference.destroy();
        }
    } finally {
        service.unexport();
    }
}
Also used : RegistryConfig(com.alibaba.dubbo.config.RegistryConfig) ServiceConfig(com.alibaba.dubbo.config.ServiceConfig) ApplicationConfig(com.alibaba.dubbo.config.ApplicationConfig) ReferenceConfig(com.alibaba.dubbo.config.ReferenceConfig) ProtocolConfig(com.alibaba.dubbo.config.ProtocolConfig) Test(org.junit.Test)

Example 14 with RegistryConfig

use of com.alibaba.dubbo.config.RegistryConfig in project dubbo by alibaba.

the class ConfigTest method testGenericServiceConfig.

@Test
public void testGenericServiceConfig() throws Exception {
    ServiceConfig<GenericService> service = new ServiceConfig<GenericService>();
    service.setApplication(new ApplicationConfig("test"));
    service.setRegistry(new RegistryConfig("mock://localhost"));
    service.setInterface(DemoService.class.getName());
    service.setGeneric(Constants.GENERIC_SERIALIZATION_BEAN);
    service.setRef(new GenericService() {

        public Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException {
            return null;
        }
    });
    try {
        service.export();
        Collection<Registry> collection = MockRegistryFactory.getCachedRegistry();
        MockRegistry registry = (MockRegistry) collection.iterator().next();
        URL url = registry.getRegistered().get(0);
        Assert.assertEquals(Constants.GENERIC_SERIALIZATION_BEAN, url.getParameter(Constants.GENERIC_KEY));
    } finally {
        MockRegistryFactory.cleanCachedRegistry();
        service.unexport();
    }
}
Also used : RegistryConfig(com.alibaba.dubbo.config.RegistryConfig) GenericService(com.alibaba.dubbo.rpc.service.GenericService) MockRegistry(com.alibaba.dubbo.config.spring.registry.MockRegistry) DemoService(com.alibaba.dubbo.config.spring.api.DemoService) JUnitMatchers.containsString(org.junit.matchers.JUnitMatchers.containsString) Registry(com.alibaba.dubbo.registry.Registry) MockRegistry(com.alibaba.dubbo.config.spring.registry.MockRegistry) GenericException(com.alibaba.dubbo.rpc.service.GenericException) URL(com.alibaba.dubbo.common.URL) ServiceConfig(com.alibaba.dubbo.config.ServiceConfig) ApplicationConfig(com.alibaba.dubbo.config.ApplicationConfig) Test(org.junit.Test)

Example 15 with RegistryConfig

use of com.alibaba.dubbo.config.RegistryConfig in project dubbo by alibaba.

the class ConfigTest method testDubboProtocolPortOverride.

@Test
public void testDubboProtocolPortOverride() throws Exception {
    String dubboPort = System.getProperty("dubbo.protocol.dubbo.port");
    int port = 55555;
    System.setProperty("dubbo.protocol.dubbo.port", String.valueOf(port));
    ServiceConfig<DemoService> service = null;
    try {
        ApplicationConfig application = new ApplicationConfig();
        application.setName("dubbo-protocol-port-override");
        RegistryConfig registry = new RegistryConfig();
        registry.setAddress("N/A");
        ProtocolConfig protocol = new ProtocolConfig();
        service = new ServiceConfig<DemoService>();
        service.setInterface(DemoService.class);
        service.setRef(new DemoServiceImpl());
        service.setApplication(application);
        service.setRegistry(registry);
        service.setProtocol(protocol);
        service.export();
        Assert.assertEquals(port, service.getExportedUrls().get(0).getPort());
    } finally {
        if (StringUtils.isNotEmpty(dubboPort)) {
            System.setProperty("dubbo.protocol.dubbo.port", dubboPort);
        }
        if (service != null) {
            service.unexport();
        }
    }
}
Also used : RegistryConfig(com.alibaba.dubbo.config.RegistryConfig) ApplicationConfig(com.alibaba.dubbo.config.ApplicationConfig) DemoService(com.alibaba.dubbo.config.spring.api.DemoService) JUnitMatchers.containsString(org.junit.matchers.JUnitMatchers.containsString) ProtocolConfig(com.alibaba.dubbo.config.ProtocolConfig) DemoServiceImpl(com.alibaba.dubbo.config.spring.impl.DemoServiceImpl) Test(org.junit.Test)

Aggregations

RegistryConfig (com.alibaba.dubbo.config.RegistryConfig)20 ApplicationConfig (com.alibaba.dubbo.config.ApplicationConfig)17 ProtocolConfig (com.alibaba.dubbo.config.ProtocolConfig)15 Test (org.junit.Test)15 ServiceConfig (com.alibaba.dubbo.config.ServiceConfig)11 DemoService (com.alibaba.dubbo.config.spring.api.DemoService)11 ReferenceConfig (com.alibaba.dubbo.config.ReferenceConfig)10 DemoServiceImpl (com.alibaba.dubbo.config.spring.impl.DemoServiceImpl)7 URL (com.alibaba.dubbo.common.URL)5 JUnitMatchers.containsString (org.junit.matchers.JUnitMatchers.containsString)5 RpcException (com.alibaba.dubbo.rpc.RpcException)4 ConsumerConfig (com.alibaba.dubbo.config.ConsumerConfig)3 GenericService (com.alibaba.dubbo.rpc.service.GenericService)3 Date (java.util.Date)3 MethodConfig (com.alibaba.dubbo.config.MethodConfig)2 ProviderConfig (com.alibaba.dubbo.config.ProviderConfig)2 DemoService (com.alibaba.dubbo.config.api.DemoService)2 GenericException (com.alibaba.dubbo.rpc.service.GenericException)2 BeansException (org.springframework.beans.BeansException)2 Service (com.alibaba.dubbo.config.annotation.Service)1