diff --git a/dubbo-compatible/pom.xml b/dubbo-compatible/pom.xml index b96623a137..c72eddeaca 100644 --- a/dubbo-compatible/pom.xml +++ b/dubbo-compatible/pom.xml @@ -68,6 +68,16 @@ dubbo-rpc-thrift ${project.parent.version} + + org.apache.dubbo + dubbo-filter-cache + ${project.parent.version} + + + org.apache.dubbo + dubbo-filter-validation + ${project.parent.version} + org.apache.dubbo dubbo-serialization-hessian2 diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml index 4ccfd67a36..f5cfd34c97 100644 --- a/dubbo-config/dubbo-config-api/pom.xml +++ b/dubbo-config/dubbo-config-api/pom.xml @@ -55,16 +55,6 @@ dubbo-rpc-injvm ${project.parent.version} - - org.apache.dubbo - dubbo-filter-validation - ${project.parent.version} - - - org.apache.dubbo - dubbo-filter-cache - ${project.parent.version} - @@ -231,6 +221,19 @@ test + + org.apache.dubbo + dubbo-filter-cache + ${project.parent.version} + test + + + + org.apache.dubbo + dubbo-filter-validation + ${project.parent.version} + test + diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml b/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml index 26d78efd63..8d3dc0e27c 100644 --- a/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml +++ b/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml @@ -16,12 +16,13 @@ --> 4.0.0 + org.apache.dubbo dubbo-configcenter - ${revision} - ../pom.xml + 2.7.7-SNAPSHOT + dubbo-configcenter-apollo jar ${project.artifactId} diff --git a/dubbo-configcenter/dubbo-configcenter-consul/pom.xml b/dubbo-configcenter/dubbo-configcenter-consul/pom.xml deleted file mode 100644 index c6b23937e9..0000000000 --- a/dubbo-configcenter/dubbo-configcenter-consul/pom.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - org.apache.dubbo - dubbo-configcenter - ${revision} - ../pom.xml - - 4.0.0 - - dubbo-configcenter-consul - - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - com.orbitz.consul - consul-client - - - com.pszymczyk.consul - embedded-consul - - - - - diff --git a/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfiguration.java deleted file mode 100644 index c1e5a44910..0000000000 --- a/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfiguration.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.dubbo.configcenter.consul; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.config.configcenter.ConfigChangeType; -import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; -import org.apache.dubbo.common.config.configcenter.ConfigurationListener; -import org.apache.dubbo.common.config.configcenter.TreePathDynamicConfiguration; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.CollectionUtils; - -import com.google.common.base.Charsets; -import com.google.common.net.HostAndPort; -import com.orbitz.consul.Consul; -import com.orbitz.consul.KeyValueClient; -import com.orbitz.consul.cache.KVCache; -import com.orbitz.consul.model.kv.Value; -import org.apache.dubbo.common.utils.StringUtils; - -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; - -/** - * config center implementation for consul - */ -public class ConsulDynamicConfiguration extends TreePathDynamicConfiguration { - private static final Logger logger = LoggerFactory.getLogger(ConsulDynamicConfiguration.class); - - private static final int DEFAULT_PORT = 8500; - private static final int DEFAULT_WATCH_TIMEOUT = 60 * 1000; - private static final String WATCH_TIMEOUT = "consul-watch-timeout"; - - private final Consul client; - - private final KeyValueClient kvClient; - - private final int watchTimeout; - - private final ConcurrentMap watchers = new ConcurrentHashMap<>(); - - public ConsulDynamicConfiguration(URL url) { - super(url); - watchTimeout = url.getParameter(WATCH_TIMEOUT, DEFAULT_WATCH_TIMEOUT); - String host = url.getHost(); - int port = url.getPort() != 0 ? url.getPort() : DEFAULT_PORT; - Consul.Builder builder = Consul.builder() - .withHostAndPort(HostAndPort.fromParts(host, port)); - String token = url.getParameter("token", (String) null); - if (StringUtils.isNotEmpty(token)) { - builder.withAclToken(token); - } - client = builder.build(); - this.kvClient = client.keyValueClient(); - } - - @Override - public String getInternalProperty(String key) { - logger.info("getting config from: " + key); - return kvClient.getValueAsString(key, Charsets.UTF_8).orElse(null); - } - - @Override - protected boolean doPublishConfig(String pathKey, String content) throws Exception { - return kvClient.putValue(pathKey, content); - } - - @Override - protected String doGetConfig(String pathKey) throws Exception { - return getInternalProperty(pathKey); - } - - @Override - protected boolean doRemoveConfig(String pathKey) throws Exception { - kvClient.deleteKey(pathKey); - return true; - } - - @Override - protected Collection doGetConfigKeys(String groupPath) { - List keys = kvClient.getKeys(groupPath); - List configKeys = new LinkedList<>(); - if (CollectionUtils.isNotEmpty(keys)) { - keys.stream() - .filter(k -> !k.equals(groupPath)) - .map(k -> k.substring(k.lastIndexOf(PATH_SEPARATOR) + 1)) - .forEach(configKeys::add); - } - return configKeys; - } - - @Override - protected void doAddListener(String pathKey, ConfigurationListener listener) { - logger.info("register listener " + listener.getClass() + " for config with key: " + pathKey); - ConsulListener watcher = watchers.computeIfAbsent(pathKey, k -> new ConsulListener(pathKey)); - watcher.addListener(listener); - } - - @Override - protected void doRemoveListener(String pathKey, ConfigurationListener listener) { - logger.info("unregister listener " + listener.getClass() + " for config with key: " + pathKey); - ConsulListener watcher = watchers.get(pathKey); - if (watcher != null) { - watcher.removeListener(listener); - } - } - - @Override - protected void doClose() throws Exception { - client.destroy(); - } - - private class ConsulListener implements KVCache.Listener { - - private KVCache kvCache; - private final Set listeners = new LinkedHashSet<>(); - private final String normalizedKey; - - public ConsulListener(String normalizedKey) { - this.normalizedKey = normalizedKey; - initKVCache(); - } - - private void initKVCache() { - this.kvCache = KVCache.newCache(kvClient, normalizedKey, watchTimeout); - kvCache.addListener(this); - kvCache.start(); - } - - @Override - public void notify(Map newValues) { - // Cache notifies all paths with "foo" the root path - // If you want to watch only "foo" value, you must filter other paths - Optional newValue = newValues.values().stream() - .filter(value -> value.getKey().equals(normalizedKey)) - .findAny(); - - newValue.ifPresent(value -> { - // Values are encoded in key/value store, decode it if needed - Optional decodedValue = newValue.get().getValueAsString(); - decodedValue.ifPresent(v -> listeners.forEach(l -> { - ConfigChangedEvent event = new ConfigChangedEvent(normalizedKey, getGroup(), v, ConfigChangeType.MODIFIED); - l.process(event); - })); - }); - } - - private void addListener(ConfigurationListener listener) { - this.listeners.add(listener); - } - - private void removeListener(ConfigurationListener listener) { - this.listeners.remove(listener); - } - } -} diff --git a/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfigurationFactory.java b/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfigurationFactory.java deleted file mode 100644 index 980a156234..0000000000 --- a/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfigurationFactory.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.dubbo.configcenter.consul; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.config.configcenter.AbstractDynamicConfigurationFactory; -import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; - -/** - * Config center factory for consul - */ -public class ConsulDynamicConfigurationFactory extends AbstractDynamicConfigurationFactory { - @Override - protected DynamicConfiguration createDynamicConfiguration(URL url) { - return new ConsulDynamicConfiguration(url); - } -} diff --git a/dubbo-configcenter/dubbo-configcenter-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory b/dubbo-configcenter/dubbo-configcenter-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory deleted file mode 100644 index b7a5091efa..0000000000 --- a/dubbo-configcenter/dubbo-configcenter-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory +++ /dev/null @@ -1 +0,0 @@ -consul=org.apache.dubbo.configcenter.consul.ConsulDynamicConfigurationFactory diff --git a/dubbo-configcenter/dubbo-configcenter-consul/src/test/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-consul/src/test/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfigurationTest.java deleted file mode 100644 index c54d103414..0000000000 --- a/dubbo-configcenter/dubbo-configcenter-consul/src/test/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfigurationTest.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.configcenter.consul; - -import org.apache.dubbo.common.URL; - -import com.google.common.net.HostAndPort; -import com.orbitz.consul.Consul; -import com.orbitz.consul.KeyValueClient; -import com.orbitz.consul.cache.KVCache; -import com.orbitz.consul.model.kv.Value; -import com.pszymczyk.consul.ConsulProcess; -import com.pszymczyk.consul.ConsulStarterBuilder; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import java.util.Arrays; -import java.util.Optional; -import java.util.TreeSet; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * - */ -public class ConsulDynamicConfigurationTest { - - private static ConsulProcess consul; - private static URL configCenterUrl; - private static ConsulDynamicConfiguration configuration; - - private static Consul client; - private static KeyValueClient kvClient; - - @BeforeAll - public static void setUp() throws Exception { - consul = ConsulStarterBuilder.consulStarter() - .build() - .start(); - configCenterUrl = URL.valueOf("consul://127.0.0.1:" + consul.getHttpPort()); - - configuration = new ConsulDynamicConfiguration(configCenterUrl); - client = Consul.builder().withHostAndPort(HostAndPort.fromParts("127.0.0.1", consul.getHttpPort())).build(); - kvClient = client.keyValueClient(); - } - - @AfterAll - public static void tearDown() throws Exception { - consul.close(); - configuration.close(); - } - - @Test - public void testGetConfig() { - kvClient.putValue("/dubbo/config/dubbo/foo", "bar"); - // test equals - assertEquals("bar", configuration.getConfig("foo", "dubbo")); - // test does not block - assertEquals("bar", configuration.getConfig("foo", "dubbo")); - Assertions.assertNull(configuration.getConfig("not-exist", "dubbo")); - } - - @Test - public void testPublishConfig() { - configuration.publishConfig("value", "metadata", "1"); - // test equals - assertEquals("1", configuration.getConfig("value", "/metadata")); - assertEquals("1", kvClient.getValueAsString("/dubbo/config/metadata/value").get()); - } - - @Test - public void testAddListener() { - KVCache cache = KVCache.newCache(kvClient, "/dubbo/config/dubbo/foo"); - cache.addListener(newValues -> { - // Cache notifies all paths with "foo" the root path - // If you want to watch only "foo" value, you must filter other paths - Optional newValue = newValues.values().stream() - .filter(value -> value.getKey().equals("foo")) - .findAny(); - - newValue.ifPresent(value -> { - // Values are encoded in key/value store, decode it if needed - Optional decodedValue = newValue.get().getValueAsString(); - decodedValue.ifPresent(v -> System.out.println(String.format("Value is: %s", v))); //prints "bar" - }); - }); - cache.start(); - - kvClient.putValue("/dubbo/config/dubbo/foo", "new-value"); - kvClient.putValue("/dubbo/config/dubbo/foo/sub", "sub-value"); - kvClient.putValue("/dubbo/config/dubbo/foo/sub2", "sub-value2"); - kvClient.putValue("/dubbo/config/foo", "parent-value"); - - System.out.println(kvClient.getKeys("/dubbo/config/dubbo/foo")); - System.out.println(kvClient.getKeys("/dubbo/config")); - System.out.println(kvClient.getValues("/dubbo/config/dubbo/foo")); - } - - @Test - public void testGetConfigKeys() { - configuration.publishConfig("v1", "metadata", "1"); - configuration.publishConfig("v2", "metadata", "2"); - configuration.publishConfig("v3", "metadata", "3"); - // test equals - assertEquals(new TreeSet(Arrays.asList("v1", "v2", "v3")), configuration.getConfigKeys("metadata")); - } -} diff --git a/dubbo-configcenter/dubbo-configcenter-etcd/pom.xml b/dubbo-configcenter/dubbo-configcenter-etcd/pom.xml deleted file mode 100644 index 3e8d8f355f..0000000000 --- a/dubbo-configcenter/dubbo-configcenter-etcd/pom.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - - - - org.apache.dubbo - dubbo-configcenter - ${revision} - ../pom.xml - - 4.0.0 - - dubbo-configcenter-etcd - jar - ${project.artifactId} - The etcd implementation of the config-center api - - - true - - - - - io.etcd - jetcd-launcher - test - - - org.testcontainers - testcontainers - test - - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-etcd3 - ${project.parent.version} - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - ${skipIntegrationTests} - - - - - diff --git a/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfiguration.java deleted file mode 100644 index f686e86033..0000000000 --- a/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfiguration.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.dubbo.configcenter.support.etcd; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.config.configcenter.ConfigChangeType; -import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; -import org.apache.dubbo.common.config.configcenter.ConfigurationListener; -import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.remoting.etcd.StateListener; -import org.apache.dubbo.remoting.etcd.jetcd.JEtcdClient; - -import com.google.protobuf.ByteString; -import io.etcd.jetcd.api.Event; -import io.etcd.jetcd.api.WatchCancelRequest; -import io.etcd.jetcd.api.WatchCreateRequest; -import io.etcd.jetcd.api.WatchGrpc; -import io.etcd.jetcd.api.WatchRequest; -import io.etcd.jetcd.api.WatchResponse; -import io.grpc.ManagedChannel; -import io.grpc.stub.StreamObserver; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.dubbo.common.config.configcenter.Constants.CONFIG_NAMESPACE_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; - -/** - * The etcd implementation of {@link DynamicConfiguration} - */ -public class EtcdDynamicConfiguration implements DynamicConfiguration { - - /** - * The final root path would be: /$NAME_SPACE/config - */ - private String rootPath; - - /** - * The etcd client - */ - private final JEtcdClient etcdClient; - - /** - * The map store the key to {@link EtcdConfigWatcher} mapping - */ - private final ConcurrentMap watchListenerMap; - - EtcdDynamicConfiguration(URL url) { - rootPath = PATH_SEPARATOR + url.getParameter(CONFIG_NAMESPACE_KEY, DEFAULT_GROUP) + "/config"; - etcdClient = new JEtcdClient(url); - etcdClient.addStateListener(state -> { - if (state == StateListener.CONNECTED) { - try { - recover(); - } catch (Exception e) { - // ignore - } - } - }); - watchListenerMap = new ConcurrentHashMap<>(); - } - - @Override - public void addListener(String key, String group, ConfigurationListener listener) { - if (watchListenerMap.get(listener) == null) { - EtcdConfigWatcher watcher = new EtcdConfigWatcher(key, group, listener); - watchListenerMap.put(listener, watcher); - watcher.watch(); - } - } - - @Override - public void removeListener(String key, String group, ConfigurationListener listener) { - EtcdConfigWatcher watcher = watchListenerMap.get(listener); - watcher.cancelWatch(); - } - - @Override - public String getConfig(String key, String group, long timeout) throws IllegalStateException { - return (String) getInternalProperty(convertKey(group, key)); - } - -// @Override -// public String getConfigs(String key, String group, long timeout) throws IllegalStateException { -// if (StringUtils.isEmpty(group)) { -// group = DEFAULT_GROUP; -// } -// return (String) getInternalProperty(convertKey(group, key)); -// } - - @Override - public Object getInternalProperty(String key) { - return etcdClient.getKVValue(key); - } - - private String buildPath(String group) { - String actualGroup = StringUtils.isEmpty(group) ? DEFAULT_GROUP : group; - return rootPath + PATH_SEPARATOR + actualGroup; - } - - private String convertKey(String group, String key) { - return buildPath(group) + PATH_SEPARATOR + key; - } - - private void recover() { - for (EtcdConfigWatcher watcher : watchListenerMap.values()) { - watcher.watch(); - } - } - - public class EtcdConfigWatcher implements StreamObserver { - - private ConfigurationListener listener; - protected WatchGrpc.WatchStub watchStub; - private StreamObserver observer; - protected long watchId; - private ManagedChannel channel; - - private final String key; - - private final String group; - - private String normalizedKey; - - public EtcdConfigWatcher(String key, String group, ConfigurationListener listener) { - this.key = key; - this.group = group; - this.normalizedKey = convertKey(group, key); - this.listener = listener; - this.channel = etcdClient.getChannel(); - } - - @Override - public void onNext(WatchResponse watchResponse) { - this.watchId = watchResponse.getWatchId(); - for (Event etcdEvent : watchResponse.getEventsList()) { - ConfigChangeType type = ConfigChangeType.MODIFIED; - if (etcdEvent.getType() == Event.EventType.DELETE) { - type = ConfigChangeType.DELETED; - } - ConfigChangedEvent event = new ConfigChangedEvent(key, group, - etcdEvent.getKv().getValue().toString(UTF_8), type); - listener.process(event); - } - } - - @Override - public void onError(Throwable throwable) { - // ignore - } - - @Override - public void onCompleted() { - // ignore - } - - public long getWatchId() { - return watchId; - } - - private void watch() { - watchStub = WatchGrpc.newStub(channel); - observer = watchStub.watch(this); - WatchCreateRequest.Builder builder = WatchCreateRequest.newBuilder() - .setKey(ByteString.copyFromUtf8(normalizedKey)) - .setProgressNotify(true); - WatchRequest req = WatchRequest.newBuilder().setCreateRequest(builder).build(); - observer.onNext(req); - } - - private void cancelWatch() { - WatchCancelRequest watchCancelRequest = - WatchCancelRequest.newBuilder().setWatchId(watchId).build(); - WatchRequest cancelRequest = WatchRequest.newBuilder() - .setCancelRequest(watchCancelRequest).build(); - observer.onNext(cancelRequest); - } - } -} diff --git a/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationFactory.java b/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationFactory.java deleted file mode 100644 index 269cee6046..0000000000 --- a/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationFactory.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.dubbo.configcenter.support.etcd; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.config.configcenter.AbstractDynamicConfigurationFactory; -import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; - -/** - * The etcd implementation of {@link AbstractDynamicConfigurationFactory} - */ -public class EtcdDynamicConfigurationFactory extends AbstractDynamicConfigurationFactory { - - @Override - protected DynamicConfiguration createDynamicConfiguration(URL url) { - return new EtcdDynamicConfiguration(url); - } -} diff --git a/dubbo-configcenter/dubbo-configcenter-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory b/dubbo-configcenter/dubbo-configcenter-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory deleted file mode 100644 index d84b1ae0e1..0000000000 --- a/dubbo-configcenter/dubbo-configcenter-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory +++ /dev/null @@ -1 +0,0 @@ -etcd=org.apache.dubbo.configcenter.support.etcd.EtcdDynamicConfigurationFactory \ No newline at end of file diff --git a/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java deleted file mode 100644 index 86dd306bf8..0000000000 --- a/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.dubbo.configcenter.support.etcd; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; -import org.apache.dubbo.common.config.configcenter.ConfigurationListener; -import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; - -import io.etcd.jetcd.ByteSequence; -import io.etcd.jetcd.Client; -import io.etcd.jetcd.launcher.EtcdCluster; -import io.etcd.jetcd.launcher.EtcdClusterFactory; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.net.URI; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.dubbo.remoting.etcd.Constants.SESSION_TIMEOUT_KEY; - -/** - * Unit test for etcd config center support - * Integrate with https://github.com/etcd-io/jetcd#launcher - */ -public class EtcdDynamicConfigurationTest { - - private static EtcdDynamicConfiguration config; - - public EtcdCluster etcdCluster = EtcdClusterFactory.buildCluster(getClass().getSimpleName(), 3, false, false); - - private static Client client; - - @Test - public void testGetConfig() { - - put("/dubbo/config/org.apache.dubbo.etcd.testService/configurators", "hello"); - put("/dubbo/config/test/dubbo.properties", "aaa=bbb"); - Assert.assertEquals("hello", config.getConfig("org.apache.dubbo.etcd.testService.configurators", DynamicConfiguration.DEFAULT_GROUP)); - Assert.assertEquals("aaa=bbb", config.getConfig("dubbo.properties", "test")); - } - - @Test - public void testAddListener() throws Exception { - CountDownLatch latch = new CountDownLatch(4); - TestListener listener1 = new TestListener(latch); - TestListener listener2 = new TestListener(latch); - TestListener listener3 = new TestListener(latch); - TestListener listener4 = new TestListener(latch); - config.addListener("AService.configurators", listener1); - config.addListener("AService.configurators", listener2); - config.addListener("testapp.tagrouters", listener3); - config.addListener("testapp.tagrouters", listener4); - - put("/dubbo/config/AService/configurators", "new value1"); - Thread.sleep(200); - put("/dubbo/config/testapp/tagrouters", "new value2"); - Thread.sleep(200); - put("/dubbo/config/testapp", "new value3"); - - Thread.sleep(1000); - - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); - Assert.assertEquals(1, listener1.getCount("/dubbo/config/AService/configurators")); - Assert.assertEquals(1, listener2.getCount("/dubbo/config/AService/configurators")); - Assert.assertEquals(1, listener3.getCount("/dubbo/config/testapp/tagrouters")); - Assert.assertEquals(1, listener4.getCount("/dubbo/config/testapp/tagrouters")); - - Assert.assertEquals("new value1", listener1.getValue()); - Assert.assertEquals("new value1", listener2.getValue()); - Assert.assertEquals("new value2", listener3.getValue()); - Assert.assertEquals("new value2", listener4.getValue()); - } - - private class TestListener implements ConfigurationListener { - private CountDownLatch latch; - private String value; - private Map countMap = new HashMap<>(); - - public TestListener(CountDownLatch latch) { - this.latch = latch; - } - - @Override - public void process(ConfigChangedEvent event) { - Integer count = countMap.computeIfAbsent(event.getKey(), k -> 0); - countMap.put(event.getKey(), ++count); - value = event.getContent(); - latch.countDown(); - } - - public int getCount(String key) { - return countMap.get(key); - } - - public String getValue() { - return value; - } - } - - private void put(String key, String value) { - try { - client.getKVClient().put(ByteSequence.from(key, UTF_8), ByteSequence.from(value, UTF_8)).get(); - } catch (Exception e) { - System.out.println("Error put value to etcd."); - } - } - - @Before - public void setUp() { - - etcdCluster.start(); - - client = Client.builder().endpoints(etcdCluster.getClientEndpoints()).build(); - - List clientEndPoints = etcdCluster.getClientEndpoints(); - - String ipAddress = clientEndPoints.get(0).getHost() + ":" + clientEndPoints.get(0).getPort(); - String urlForDubbo = "etcd3://" + ipAddress + "/org.apache.dubbo.etcd.testService"; - - // timeout in 15 seconds. - URL url = URL.valueOf(urlForDubbo) - .addParameter(SESSION_TIMEOUT_KEY, 15000); - config = new EtcdDynamicConfiguration(url); - } - - @After - public void tearDown() { - etcdCluster.close(); - } - -} diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml b/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml index b54dfc6bce..42dcc69848 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml +++ b/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml @@ -22,8 +22,7 @@ org.apache.dubbo dubbo-configcenter - ${revision} - ../pom.xml + 2.7.7-SNAPSHOT 4.0.0 diff --git a/dubbo-configcenter/pom.xml b/dubbo-configcenter/pom.xml index 869611cb62..f69f389546 100644 --- a/dubbo-configcenter/pom.xml +++ b/dubbo-configcenter/pom.xml @@ -33,8 +33,6 @@ dubbo-configcenter-zookeeper dubbo-configcenter-apollo - dubbo-configcenter-consul - dubbo-configcenter-etcd dubbo-configcenter-nacos diff --git a/dubbo-container/dubbo-container-log4j/pom.xml b/dubbo-container/dubbo-container-log4j/pom.xml deleted file mode 100644 index 949615f73e..0000000000 --- a/dubbo-container/dubbo-container-log4j/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - 4.0.0 - - org.apache.dubbo - dubbo-container - ${revision} - ../pom.xml - - dubbo-container-log4j - jar - ${project.artifactId} - The log4j container module of dubbo project - - false - - - - org.apache.dubbo - dubbo-container-api - ${project.parent.version} - - - \ No newline at end of file diff --git a/dubbo-container/dubbo-container-log4j/src/main/java/org/apache/dubbo/container/log4j/Log4jContainer.java b/dubbo-container/dubbo-container-log4j/src/main/java/org/apache/dubbo/container/log4j/Log4jContainer.java deleted file mode 100644 index 946e4c59eb..0000000000 --- a/dubbo-container/dubbo-container-log4j/src/main/java/org/apache/dubbo/container/log4j/Log4jContainer.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.container.log4j; - -import org.apache.dubbo.common.config.ConfigurationUtils; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.container.Container; - -import org.apache.log4j.Appender; -import org.apache.log4j.FileAppender; -import org.apache.log4j.LogManager; -import org.apache.log4j.PropertyConfigurator; - -import java.util.Enumeration; -import java.util.Properties; - -/** - * Log4jContainer. (SPI, Singleton, ThreadSafe) - * - * The container class implementation for Log4j - */ -public class Log4jContainer implements Container { - - public static final String LOG4J_FILE = "dubbo.log4j.file"; - - public static final String LOG4J_LEVEL = "dubbo.log4j.level"; - - public static final String LOG4J_SUBDIRECTORY = "dubbo.log4j.subdirectory"; - - public static final String DEFAULT_LOG4J_LEVEL = "ERROR"; - - @Override - @SuppressWarnings("unchecked") - public void start() { - String file = ConfigurationUtils.getProperty(LOG4J_FILE); - if (file != null && file.length() > 0) { - String level = ConfigurationUtils.getProperty(LOG4J_LEVEL); - if (StringUtils.isEmpty(level)) { - level = DEFAULT_LOG4J_LEVEL; - } - Properties properties = new Properties(); - properties.setProperty("log4j.rootLogger", level + ",application"); - properties.setProperty("log4j.appender.application", "org.apache.log4j.DailyRollingFileAppender"); - properties.setProperty("log4j.appender.application.File", file); - properties.setProperty("log4j.appender.application.Append", "true"); - properties.setProperty("log4j.appender.application.DatePattern", "'.'yyyy-MM-dd"); - properties.setProperty("log4j.appender.application.layout", "org.apache.log4j.PatternLayout"); - properties.setProperty("log4j.appender.application.layout.ConversionPattern", "%d [%t] %-5p %C{6} (%F:%L) - %m%n"); - PropertyConfigurator.configure(properties); - } - String subdirectory = ConfigurationUtils.getProperty(LOG4J_SUBDIRECTORY); - if (subdirectory != null && subdirectory.length() > 0) { - Enumeration ls = LogManager.getCurrentLoggers(); - while (ls.hasMoreElements()) { - org.apache.log4j.Logger l = ls.nextElement(); - if (l != null) { - Enumeration as = l.getAllAppenders(); - while (as.hasMoreElements()) { - Appender a = as.nextElement(); - if (a instanceof FileAppender) { - FileAppender fa = (FileAppender) a; - String f = fa.getFile(); - if (f != null && f.length() > 0) { - int i = f.replace('\\', '/').lastIndexOf('/'); - String path; - if (i == -1) { - path = subdirectory; - } else { - path = f.substring(0, i); - if (!path.endsWith(subdirectory)) { - path = path + "/" + subdirectory; - } - f = f.substring(i + 1); - } - fa.setFile(path + "/" + f); - fa.activateOptions(); - } - } - } - } - } - } - } - - @Override - public void stop() { - } - -} diff --git a/dubbo-container/dubbo-container-log4j/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.container.Container b/dubbo-container/dubbo-container-log4j/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.container.Container deleted file mode 100644 index 0b4c162a6a..0000000000 --- a/dubbo-container/dubbo-container-log4j/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.container.Container +++ /dev/null @@ -1 +0,0 @@ -log4j=org.apache.dubbo.container.log4j.Log4jContainer \ No newline at end of file diff --git a/dubbo-container/dubbo-container-log4j/src/test/java/org/apache/dubbo/container/log4j/Log4jContainerTest.java b/dubbo-container/dubbo-container-log4j/src/test/java/org/apache/dubbo/container/log4j/Log4jContainerTest.java deleted file mode 100644 index 535a3d5c5a..0000000000 --- a/dubbo-container/dubbo-container-log4j/src/test/java/org/apache/dubbo/container/log4j/Log4jContainerTest.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.container.log4j; - -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.container.Container; - -import org.junit.jupiter.api.Test; - -/** - * StandaloneContainerTest - */ -public class Log4jContainerTest { - - @Test - public void testContainer() { - Log4jContainer container = (Log4jContainer) ExtensionLoader.getExtensionLoader(Container.class).getExtension("log4j"); - container.start(); - container.stop(); - } - -} \ No newline at end of file diff --git a/dubbo-container/dubbo-container-logback/pom.xml b/dubbo-container/dubbo-container-logback/pom.xml deleted file mode 100644 index 0af3164a8b..0000000000 --- a/dubbo-container/dubbo-container-logback/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - 4.0.0 - - org.apache.dubbo - dubbo-container - ${revision} - ../pom.xml - - dubbo-container-logback - jar - ${project.artifactId} - The logback container module of dubbo project - - false - - - - org.apache.dubbo - dubbo-container-api - ${project.parent.version} - - - ch.qos.logback - logback-classic - - - diff --git a/dubbo-container/dubbo-container-logback/src/main/java/org/apache/dubbo/container/logback/LogbackContainer.java b/dubbo-container/dubbo-container-logback/src/main/java/org/apache/dubbo/container/logback/LogbackContainer.java deleted file mode 100644 index 430e2e2191..0000000000 --- a/dubbo-container/dubbo-container-logback/src/main/java/org/apache/dubbo/container/logback/LogbackContainer.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.container.logback; - -import org.apache.dubbo.common.utils.ConfigUtils; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.container.Container; - -import ch.qos.logback.classic.Level; -import ch.qos.logback.classic.Logger; -import ch.qos.logback.classic.LoggerContext; -import ch.qos.logback.classic.encoder.PatternLayoutEncoder; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.rolling.RollingFileAppender; -import ch.qos.logback.core.rolling.TimeBasedRollingPolicy; -import org.slf4j.LoggerFactory; - -/** - * LogbackContainer. (SPI, Singleton, ThreadSafe) - * - * The container class implementation for Logback - */ -public class LogbackContainer implements Container { - - public static final String LOGBACK_FILE = "dubbo.logback.file"; - - public static final String LOGBACK_LEVEL = "dubbo.logback.level"; - - public static final String LOGBACK_MAX_HISTORY = "dubbo.logback.maxhistory"; - - public static final String DEFAULT_LOGBACK_LEVEL = "ERROR"; - - @Override - public void start() { - String file = ConfigUtils.getProperty(LOGBACK_FILE); - if (file != null && file.length() > 0) { - String level = ConfigUtils.getProperty(LOGBACK_LEVEL); - if (StringUtils.isEmpty(level)) { - level = DEFAULT_LOGBACK_LEVEL; - } - // maxHistory=0 Infinite history - int maxHistory = StringUtils.parseInteger(ConfigUtils.getProperty(LOGBACK_MAX_HISTORY)); - - doInitializer(file, level, maxHistory); - } - } - - @Override - public void stop() { - } - - /** - * Initializer logback - * - * @param file - * @param level - * @param maxHistory - */ - private void doInitializer(String file, String level, int maxHistory) { - LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); - Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); - rootLogger.detachAndStopAllAppenders(); - - // appender - RollingFileAppender fileAppender = new RollingFileAppender(); - fileAppender.setContext(loggerContext); - fileAppender.setName("application"); - fileAppender.setFile(file); - fileAppender.setAppend(true); - - // policy - TimeBasedRollingPolicy policy = new TimeBasedRollingPolicy(); - policy.setContext(loggerContext); - policy.setMaxHistory(maxHistory); - policy.setFileNamePattern(file + ".%d{yyyy-MM-dd}"); - policy.setParent(fileAppender); - policy.start(); - fileAppender.setRollingPolicy(policy); - - // encoder - PatternLayoutEncoder encoder = new PatternLayoutEncoder(); - encoder.setContext(loggerContext); - encoder.setPattern("%date [%thread] %-5level %logger (%file:%line\\) - %msg%n"); - encoder.start(); - fileAppender.setEncoder(encoder); - - fileAppender.start(); - - rootLogger.addAppender(fileAppender); - rootLogger.setLevel(Level.toLevel(level)); - rootLogger.setAdditive(false); - } - -} diff --git a/dubbo-container/dubbo-container-logback/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.container.Container b/dubbo-container/dubbo-container-logback/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.container.Container deleted file mode 100644 index 04c4eaa39a..0000000000 --- a/dubbo-container/dubbo-container-logback/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.container.Container +++ /dev/null @@ -1 +0,0 @@ -logback=org.apache.dubbo.container.logback.LogbackContainer \ No newline at end of file diff --git a/dubbo-container/dubbo-container-logback/src/test/java/org/apache/dubbo/container/logback/LogbackContainerTest.java b/dubbo-container/dubbo-container-logback/src/test/java/org/apache/dubbo/container/logback/LogbackContainerTest.java deleted file mode 100644 index d82e8a48a9..0000000000 --- a/dubbo-container/dubbo-container-logback/src/test/java/org/apache/dubbo/container/logback/LogbackContainerTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.container.logback; - -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.container.Container; - -import org.junit.jupiter.api.Test; - -/** - * StandaloneContainerTest - */ -public class LogbackContainerTest { - - private static final Logger logger = LoggerFactory.getLogger(LogbackContainerTest.class); - - @Test - public void testContainer() { - LogbackContainer container = (LogbackContainer) ExtensionLoader.getExtensionLoader(Container.class) - .getExtension("logback"); - container.start(); - - logger.debug("Test debug:" + this.getClass().getName()); - logger.warn("Test warn:" + this.getClass().getName()); - logger.info("Test info:" + this.getClass().getName()); - logger.error("Test error:" + this.getClass().getName()); - - container.stop(); - } - -} \ No newline at end of file diff --git a/dubbo-container/pom.xml b/dubbo-container/pom.xml index d088993ff4..ec2cab09c4 100644 --- a/dubbo-container/pom.xml +++ b/dubbo-container/pom.xml @@ -32,7 +32,5 @@ dubbo-container-api dubbo-container-spring - dubbo-container-log4j - dubbo-container-logback diff --git a/dubbo-all/pom.xml b/dubbo-distribution/dubbo-all/pom.xml similarity index 73% rename from dubbo-all/pom.xml rename to dubbo-distribution/dubbo-all/pom.xml index 050ae24747..5f679306bb 100644 --- a/dubbo-all/pom.xml +++ b/dubbo-distribution/dubbo-all/pom.xml @@ -21,11 +21,11 @@ org.apache.dubbo dubbo-parent ${revision} - ../pom.xml + ../../pom.xml dubbo jar - dubbo-all + dubbo The all in one project of dubbo false @@ -59,20 +59,6 @@ compile true - - org.apache.dubbo - dubbo-filter-cache - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-filter-validation - ${project.version} - compile - true - org.apache.dubbo dubbo-remoting-api @@ -96,35 +82,7 @@ org.apache.dubbo - dubbo-remoting-etcd3 - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-remoting-mina - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-remoting-grizzly - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-remoting-p2p - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-remoting-http + dubbo-remoting-zookeeper ${project.version} compile true @@ -150,62 +108,6 @@ compile true - - org.apache.dubbo - dubbo-rpc-http - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-rpc-rmi - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-rpc-hessian - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-rpc-webservice - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-rpc-thrift - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-rpc-native-thrift - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-rpc-memcached - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-rpc-redis - ${project.version} - compile - true - org.apache.dubbo dubbo-rpc-rest @@ -213,13 +115,6 @@ compile true - - org.apache.dubbo - dubbo-rpc-xml - ${project.version} - compile - true - org.apache.dubbo dubbo-rpc-grpc @@ -234,13 +129,6 @@ compile true - - org.apache.dubbo - dubbo-registry-default - ${project.version} - compile - true - org.apache.dubbo dubbo-registry-multicast @@ -255,44 +143,6 @@ compile true - - org.apache.dubbo - dubbo-registry-redis - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-registry-consul - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-registry-etcd3 - ${project.version} - compile - true - - - io.grpc - grpc-core - - - io.grpc - grpc-netty - - - - - org.apache.dubbo - dubbo-registry-eureka - ${project.version} - compile - true - org.apache.dubbo dubbo-registry-nacos @@ -300,13 +150,6 @@ compile true - - org.apache.dubbo - dubbo-registry-sofa - ${project.version} - compile - true - org.apache.dubbo dubbo-registry-multiple @@ -335,20 +178,6 @@ compile true - - org.apache.dubbo - dubbo-container-log4j - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-container-logback - ${project.version} - compile - true - org.apache.dubbo dubbo-qos @@ -363,20 +192,6 @@ compile true - - org.apache.dubbo - dubbo-serialization-fastjson - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-serialization-fst - ${project.version} - compile - true - org.apache.dubbo dubbo-serialization-hessian2 @@ -384,13 +199,6 @@ compile true - - org.apache.dubbo - dubbo-serialization-native-hession - ${project.version} - compile - true - org.apache.dubbo dubbo-serialization-jdk @@ -398,41 +206,6 @@ compile true - - org.apache.dubbo - dubbo-serialization-kryo - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-serialization-avro - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-serialization-protostuff - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-serialization-gson - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-serialization-protobuf - ${project.version} - compile - true - org.apache.dubbo dubbo-configcenter-zookeeper @@ -454,30 +227,6 @@ compile true - - org.apache.dubbo - dubbo-configcenter-consul - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-configcenter-etcd - ${project.version} - compile - true - - - io.grpc - grpc-core - - - io.grpc - grpc-netty - - - org.apache.dubbo dubbo-compatible @@ -515,31 +264,7 @@ org.apache.dubbo - dubbo-metadata-report-consul - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-metadata-report-etcd - ${project.version} - compile - true - - - io.grpc - grpc-core - - - io.grpc - grpc-netty - - - - - org.apache.dubbo - dubbo-metadata-report-nacos + dubbo-auth ${project.version} compile true @@ -620,71 +345,35 @@ org.apache.dubbo:dubbo-remoting-api org.apache.dubbo:dubbo-remoting-netty org.apache.dubbo:dubbo-remoting-netty4 - org.apache.dubbo:dubbo-remoting-etcd3 - org.apache.dubbo:dubbo-remoting-mina - org.apache.dubbo:dubbo-remoting-grizzly - org.apache.dubbo:dubbo-remoting-p2p - org.apache.dubbo:dubbo-remoting-http org.apache.dubbo:dubbo-remoting-zookeeper org.apache.dubbo:dubbo-rpc-api org.apache.dubbo:dubbo-rpc-dubbo org.apache.dubbo:dubbo-rpc-injvm - org.apache.dubbo:dubbo-rpc-http - org.apache.dubbo:dubbo-rpc-rmi - org.apache.dubbo:dubbo-rpc-hessian - org.apache.dubbo:dubbo-rpc-webservice - org.apache.dubbo:dubbo-rpc-thrift - org.apache.dubbo:dubbo-rpc-native-thrift - org.apache.dubbo:dubbo-rpc-memcached - org.apache.dubbo:dubbo-rpc-redis org.apache.dubbo:dubbo-rpc-rest - org.apache.dubbo:dubbo-rpc-xml org.apache.dubbo:dubbo-rpc-grpc - org.apache.dubbo:dubbo-filter-validation - org.apache.dubbo:dubbo-filter-cache org.apache.dubbo:dubbo-cluster org.apache.dubbo:dubbo-registry-api org.apache.dubbo:dubbo-registry-default org.apache.dubbo:dubbo-registry-multicast org.apache.dubbo:dubbo-registry-zookeeper - org.apache.dubbo:dubbo-registry-redis - org.apache.dubbo:dubbo-registry-consul - org.apache.dubbo:dubbo-registry-etcd3 - org.apache.dubbo:dubbo-registry-eureka org.apache.dubbo:dubbo-registry-nacos - org.apache.dubbo:dubbo-registry-sofa org.apache.dubbo:dubbo-registry-multiple org.apache.dubbo:dubbo-monitor-api org.apache.dubbo:dubbo-monitor-default org.apache.dubbo:dubbo-container-api org.apache.dubbo:dubbo-container-spring - org.apache.dubbo:dubbo-container-log4j - org.apache.dubbo:dubbo-container-logback - org.apache.dubbo:dubbo-qos org.apache.dubbo:dubbo-serialization-api - org.apache.dubbo:dubbo-serialization-fastjson org.apache.dubbo:dubbo-serialization-hessian2 - org.apache.dubbo:dubbo-serialization-fst - org.apache.dubbo:dubbo-serialization-kryo - org.apache.dubbo:dubbo-serialization-avro org.apache.dubbo:dubbo-serialization-jdk - org.apache.dubbo:dubbo-serialization-protostuff - org.apache.dubbo:dubbo-serialization-gson - org.apache.dubbo:dubbo-serialization-protobuf org.apache.dubbo:dubbo-configcenter-api - org.apache.dubbo:dubbo-configcenter-definition org.apache.dubbo:dubbo-configcenter-apollo org.apache.dubbo:dubbo-configcenter-zookeeper - org.apache.dubbo:dubbo-configcenter-consul - org.apache.dubbo:dubbo-configcenter-etcd org.apache.dubbo:dubbo-configcenter-nacos org.apache.dubbo:dubbo-metadata-api org.apache.dubbo:dubbo-metadata-report-redis org.apache.dubbo:dubbo-metadata-report-zookeeper - org.apache.dubbo:dubbo-metadata-report-consul - org.apache.dubbo:dubbo-metadata-report-etcd - org.apache.dubbo:dubbo-metadata-report-nacos - org.apache.dubbo:dubbo-serialization-native-hession + org.apache.dubbo:dubbo-qos + org.apache.dubbo:dubbo-auth @@ -980,6 +669,18 @@ META-INF/services/org.apache.dubbo.common.extension.LoadingStrategy + + + META-INF/dubbo/internal/org.apache.dubbo.auth.spi.AccessKeyStorage + + + + + META-INF/dubbo/internal/org.apache.dubbo.auth.spi.Authenticator + + org.apache.dubbo:dubbo - + com/** org/** diff --git a/dubbo-distribution/dubbo-apache-release/pom.xml b/dubbo-distribution/dubbo-apache-release/pom.xml new file mode 100644 index 0000000000..fd0e67786a --- /dev/null +++ b/dubbo-distribution/dubbo-apache-release/pom.xml @@ -0,0 +1,100 @@ + + + 4.0.0 + + org.apache.dubbo + dubbo-distribution + ${revision} + ../pom.xml + + dubbo-apache-release + pom + dubbo-apache-release + The apache source release + + true + + + + + org.apache.dubbo + dubbo-demo-api-provider + ${project.version} + + + org.apache.dubbo + dubbo-demo-api-consumer + ${project.version} + + + + + + release + + apache-dubbo-${project.version} + + + maven-assembly-plugin + 3.1.0 + + + bin + package + + single + + + + src/assembly/bin-release.xml + + + + + src + package + + single + + + + src/assembly/source-release.xml + + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.6 + + + verify + + sign + + + + + + + + + diff --git a/dubbo-distribution/src/assembly/bin-release.xml b/dubbo-distribution/dubbo-apache-release/src/assembly/bin-release.xml similarity index 95% rename from dubbo-distribution/src/assembly/bin-release.xml rename to dubbo-distribution/dubbo-apache-release/src/assembly/bin-release.xml index 76409930e6..570d190173 100644 --- a/dubbo-distribution/src/assembly/bin-release.xml +++ b/dubbo-distribution/dubbo-apache-release/src/assembly/bin-release.xml @@ -24,7 +24,7 @@ ${project.build.finalName}-bin - ../ + ../../ DISCLAIMER NOTICE @@ -32,7 +32,7 @@ - ../dubbo-demo + ../../dubbo-demo README.md diff --git a/dubbo-distribution/src/assembly/source-release.xml b/dubbo-distribution/dubbo-apache-release/src/assembly/source-release.xml similarity index 98% rename from dubbo-distribution/src/assembly/source-release.xml rename to dubbo-distribution/dubbo-apache-release/src/assembly/source-release.xml index 2f265166b7..68bab41867 100644 --- a/dubbo-distribution/src/assembly/source-release.xml +++ b/dubbo-distribution/dubbo-apache-release/src/assembly/source-release.xml @@ -25,7 +25,7 @@ - ../ + ../../ true **/* diff --git a/dubbo-bom/pom.xml b/dubbo-distribution/dubbo-bom/pom.xml similarity index 89% rename from dubbo-bom/pom.xml rename to dubbo-distribution/dubbo-bom/pom.xml index a5b8b87c98..afd52bddab 100644 --- a/dubbo-bom/pom.xml +++ b/dubbo-distribution/dubbo-bom/pom.xml @@ -23,68 +23,13 @@ org.apache.dubbo dubbo-parent ${revision} - ../pom.xml + ../../pom.xml dubbo-bom pom dubbo-bom - Dubbo dependencies BOM - https://github.com/apache/dubbo - 2011 - - - Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0 - repo - - - - - https://github.com/apache/dubbo - scm:git:https://github.com/apache/dubbo.git - scm:git:https://github.com/apache/dubbo.git - HEAD - - - - Development List - dev-subscribe@dubbo.apache.org - dev-unsubscribe@dubbo.apache.org - dev@dubbo.apache.org - - - Commits List - commits-subscribe@dubbo.apache.org - commits-unsubscribe@dubbo.apache.org - commits@dubbo.apache.org - - - Issues List - issues-subscribe@dubbo.apache.org - issues-unsubscribe@dubbo.apache.org - issues@dubbo.apache.org - - - - - dubbo.io - The Dubbo Project Contributors - dev-subscribe@dubbo.apache.org - http://dubbo.apache.org/ - - - - - The Apache Software Foundation - http://www.apache.org/ - - - - Github Issues - https://github.com/apache/dubbo/issues - diff --git a/dubbo-distribution/dubbo-core-spi/pom.xml b/dubbo-distribution/dubbo-core-spi/pom.xml new file mode 100644 index 0000000000..ad06e629cb --- /dev/null +++ b/dubbo-distribution/dubbo-core-spi/pom.xml @@ -0,0 +1,444 @@ + + + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../../pom.xml + + dubbo-core-spi + jar + dubbo-core-spi + All the SPI definitions of Dubbo + + true + + + + + org.apache.dubbo + dubbo-cluster + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-common + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-remoting-api + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-rpc-api + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-registry-api + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-monitor-api + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-qos + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-serialization-api + ${project.version} + compile + true + + + + org.apache.dubbo + dubbo-metadata-api + ${project.version} + compile + true + + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + package + + shade + + + true + false + + + org.apache.dubbo:dubbo-common + org.apache.dubbo:dubbo-cluster + org.apache.dubbo:dubbo-qos + org.apache.dubbo:dubbo-remoting-api + org.apache.dubbo:dubbo-rpc-api + org.apache.dubbo:dubbo-cluster + org.apache.dubbo:dubbo-registry-api + org.apache.dubbo:dubbo-monitor-api + org.apache.dubbo:dubbo-container-api + org.apache.dubbo:dubbo-serialization-api + org.apache.dubbo:dubbo-metadata-api + + + + + + + META-INF/dubbo/internal/org.apache.dubbo.common.compiler.Compiler + + + + + META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory + + + + + META-INF/dubbo/internal/org.apache.dubbo.common.extension.ExtensionFactory + + + + + META-INF/dubbo/internal/org.apache.dubbo.common.infra.InfraAdapter + + + + + META-INF/dubbo/internal/org.apache.dubbo.common.logger.LoggerAdapter + + + + + META-INF/dubbo/internal/org.apache.dubbo.common.status.StatusChecker + + + + + META-INF/dubbo/internal/org.apache.dubbo.common.store.DataStore + + + + + META-INF/dubbo/internal/org.apache.dubbo.common.threadpool.ThreadPool + + + + + + META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization + + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.Dispatcher + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.Codec2 + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.Transporter + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.exchange.Exchanger + + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.http.HttpBinder + + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.p2p.Networker + + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.telnet.TelnetHandler + + + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter + + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.InvokerListener + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.ExporterListener + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.ProxyFactory + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.Cluster + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.LoadBalance + + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.Merger + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.RouterFactory + + + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.ConfiguratorFactory + + + + META-INF/dubbo/internal/org.apache.dubbo.container.Container + + + META-INF/dubbo/internal/org.apache.dubbo.monitor.MonitorFactory + + + + META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory + + + + META-INF/dubbo/internal/org.apache.dubbo.validation.Validation + + + META-INF/dubbo/internal/org.apache.dubbo.cache.CacheFactory + + + META-INF/dubbo/internal/org.apache.dubbo.qos.command.BaseCommand + + + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory + + + + + META-INF/dubbo/internal/org.apache.dubbo.event.EventDispatcher + + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.MetadataServiceExporter + + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.WritableMetadataService + + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.ServiceNameMapping + + + + + META-INF/dubbo/internal/org.apache.dubbo.registry.client.metadata.proxy.MetadataServiceProxyFactory + + + + + META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscoveryFactory + + + + META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscovery + + + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.definition.builder.TypeBuilder + + + + META-INF/dubbo/internal/org.apache.dubbo.event.EventListener + + + + + META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceInstanceCustomizer + + + + + META-INF/dubbo/internal/org.apache.dubbo.registry.client.metadata.MetadataServiceURLBuilder + + + + + + + + + META-INF/dubbo/internal/org.apache.dubbo.common.convert.Converter + + + + + META-INF/dubbo/internal/org.apache.dubbo.common.convert.multiple.MultiValueConverter + + + + + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor + + + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.ServiceRestMetadataResolver + + + + + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.builder.TypeDefinitionBuilder + + + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor + + + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.rest.ServiceRestMetadataResolver + + + + + + + + + META-INF/services/org.apache.dubbo.common.extension.LoadingStrategy + + + + + + + org.apache.dubbo:dubbo + + + com/** + org/** + + META-INF/dubbo/** + + + + + + + + + + + diff --git a/dubbo-distribution/pom.xml b/dubbo-distribution/pom.xml index 5b18042087..c8995303a8 100644 --- a/dubbo-distribution/pom.xml +++ b/dubbo-distribution/pom.xml @@ -14,86 +14,44 @@ See the License for the specific language governing permissions and limitations under the License. --> - - 4.0.0 + + org.apache.dubbo dubbo-parent ${revision} ../pom.xml + 4.0.0 + dubbo-distribution pom - dubbo-distribution - The binary distribution module for dubbo temporarily - - true - - - - - org.apache.dubbo - dubbo-demo-api-provider - ${project.version} - - - org.apache.dubbo - dubbo-demo-api-consumer - ${project.version} - - release - - apache-dubbo-${project.version} - - - maven-assembly-plugin - 3.1.0 - - - bin - package - - single - - - - src/assembly/bin-release.xml - - - - - src - package - - single - - - - src/assembly/source-release.xml - - - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.6 - - - verify - - sign - - - - - - + + dubbo-all + dubbo-apache-release + dubbo-bom + dubbo-core-spi + + + + dubbo-all + + true + + + dubbo-all + + + + dubbo-core-spi + + dubbo-all + diff --git a/dubbo-filter/dubbo-filter-cache/pom.xml b/dubbo-filter/dubbo-filter-cache/pom.xml index 22c905c579..49f99cff87 100644 --- a/dubbo-filter/dubbo-filter-cache/pom.xml +++ b/dubbo-filter/dubbo-filter-cache/pom.xml @@ -19,8 +19,7 @@ org.apache.dubbo dubbo-filter - ${revision} - ../pom.xml + 2.7.7-SNAPSHOT dubbo-filter-cache jar diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/Cache.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/Cache.java index bba7aca0ee..69ae6710ee 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/Cache.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/Cache.java @@ -1,43 +1,43 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.cache; - -/** - * Cache interface to support storing and retrieval of value against a lookup key. It has two operation get and put. - * put-Storing value against a key. - * get-Retrieval of object. - * @see org.apache.dubbo.cache.support.lru.LruCache - * @see org.apache.dubbo.cache.support.jcache.JCache - * @see org.apache.dubbo.cache.support.expiring.ExpiringCache - * @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCache - */ -public interface Cache { - /** - * API to store value against a key - * @param key Unique identifier for the object being store. - * @param value Value getting store - */ - void put(Object key, Object value); - - /** - * API to return stored value using a key. - * @param key Unique identifier for cache lookup - * @return Return stored object against key - */ - Object get(Object key); - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.cache; + +/** + * Cache interface to support storing and retrieval of value against a lookup key. It has two operation get and put. + * put-Storing value against a key. + * get-Retrieval of object. + * @see org.apache.dubbo.cache.support.lru.LruCache + * @see org.apache.dubbo.cache.support.jcache.JCache + * @see org.apache.dubbo.cache.support.expiring.ExpiringCache + * @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCache + */ +public interface Cache { + /** + * API to store value against a key + * @param key Unique identifier for the object being store. + * @param value Value getting store + */ + void put(Object key, Object value); + + /** + * API to return stored value using a key. + * @param key Unique identifier for cache lookup + * @return Return stored object against key + */ + Object get(Object key); + +} diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/CacheFactory.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/CacheFactory.java index 77256bb5ee..66b5b59e2c 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/CacheFactory.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/CacheFactory.java @@ -1,43 +1,43 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.cache; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.Adaptive; -import org.apache.dubbo.common.extension.SPI; -import org.apache.dubbo.rpc.Invocation; - -/** - * Interface needs to be implemented by all the cache store provider.Along with implementing CacheFactory interface - * entry needs to be added in org.apache.dubbo.cache.CacheFactory file in a classpath META-INF sub directories. - * - * @see Cache - */ -@SPI("lru") -public interface CacheFactory { - - /** - * CacheFactory implementation class needs to implement this return underlying cache instance for method against - * url and invocation. - * @param url - * @param invocation - * @return Instance of Cache containing cached value against method url and invocation. - */ - @Adaptive("cache") - Cache getCache(URL url, Invocation invocation); - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.cache; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.extension.Adaptive; +import org.apache.dubbo.common.extension.SPI; +import org.apache.dubbo.rpc.Invocation; + +/** + * Interface needs to be implemented by all the cache store provider.Along with implementing CacheFactory interface + * entry needs to be added in org.apache.dubbo.cache.CacheFactory file in a classpath META-INF sub directories. + * + * @see Cache + */ +@SPI("lru") +public interface CacheFactory { + + /** + * CacheFactory implementation class needs to implement this return underlying cache instance for method against + * url and invocation. + * @param url + * @param invocation + * @return Instance of Cache containing cached value against method url and invocation. + */ + @Adaptive("cache") + Cache getCache(URL url, Invocation invocation); + +} diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java index 902bf6dcea..02d0e299a0 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java @@ -1,133 +1,133 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.cache.filter; - -import org.apache.dubbo.cache.Cache; -import org.apache.dubbo.cache.CacheFactory; -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.common.utils.ConfigUtils; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.rpc.AsyncRpcResult; -import org.apache.dubbo.rpc.Filter; -import org.apache.dubbo.rpc.Invocation; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Result; -import org.apache.dubbo.rpc.RpcException; - -import java.io.Serializable; - -import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; -import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; -import static org.apache.dubbo.common.constants.FilterConstants.CACHE_KEY; - -/** - * CacheFilter is a core component of dubbo.Enabling cache key of service,method,consumer or provider dubbo will cache method return value. - * Along with cache key we need to configure cache type. Dubbo default implemented cache types are - * lur - * threadlocal - * jcache - * expiring - * - * - * e.g. 1)<dubbo:service cache="lru" /> - * 2)<dubbo:service /> <dubbo:method name="method2" cache="threadlocal" /> <dubbo:service/> - * 3)<dubbo:provider cache="expiring" /> - * 4)<dubbo:consumer cache="jcache" /> - * - *If cache type is defined in method level then method level type will get precedence. According to above provided - *example, if service has two method, method1 and method2, method2 will have cache type as threadlocal where others will - *be backed by lru - * - * - * @see org.apache.dubbo.rpc.Filter - * @see org.apache.dubbo.cache.support.lru.LruCacheFactory - * @see org.apache.dubbo.cache.support.lru.LruCache - * @see org.apache.dubbo.cache.support.jcache.JCacheFactory - * @see org.apache.dubbo.cache.support.jcache.JCache - * @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCacheFactory - * @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCache - * @see org.apache.dubbo.cache.support.expiring.ExpiringCacheFactory - * @see org.apache.dubbo.cache.support.expiring.ExpiringCache - * - */ -@Activate(group = {CONSUMER, PROVIDER}, value = CACHE_KEY) -public class CacheFilter implements Filter { - - private CacheFactory cacheFactory; - - /** - * Dubbo will populate and set the cache factory instance based on service/method/consumer/provider configured - * cache attribute value. Dubbo will search for the class name implementing configured cache in file org.apache.dubbo.cache.CacheFactory - * under META-INF sub folders. - * - * @param cacheFactory instance of CacheFactory based on cache type - */ - public void setCacheFactory(CacheFactory cacheFactory) { - this.cacheFactory = cacheFactory; - } - - /** - * If cache is configured, dubbo will invoke method on each method call. If cache value is returned by cache store - * then it will return otherwise call the remote method and return value. If remote method's return value has error - * then it will not cache the value. - * @param invoker service - * @param invocation invocation. - * @return Cache returned value if found by the underlying cache store. If cache miss it will call target method. - * @throws RpcException - */ - @Override - public Result invoke(Invoker> invoker, Invocation invocation) throws RpcException { - if (cacheFactory != null && ConfigUtils.isNotEmpty(invoker.getUrl().getMethodParameter(invocation.getMethodName(), CACHE_KEY))) { - Cache cache = cacheFactory.getCache(invoker.getUrl(), invocation); - if (cache != null) { - String key = StringUtils.toArgumentString(invocation.getArguments()); - Object value = cache.get(key); - if (value != null) { - if (value instanceof ValueWrapper) { - return AsyncRpcResult.newDefaultAsyncResult(((ValueWrapper) value).get(), invocation); - } else { - return AsyncRpcResult.newDefaultAsyncResult(value, invocation); - } - } - Result result = invoker.invoke(invocation); - if (!result.hasException()) { - cache.put(key, new ValueWrapper(result.getValue())); - } - return result; - } - } - return invoker.invoke(invocation); - } - - /** - * Cache value wrapper. - */ - static class ValueWrapper implements Serializable { - - private static final long serialVersionUID = -1777337318019193256L; - - private final Object value; - - public ValueWrapper (Object value) { - this.value = value; - } - - public Object get() { - return this.value; - } - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.cache.filter; + +import org.apache.dubbo.cache.Cache; +import org.apache.dubbo.cache.CacheFactory; +import org.apache.dubbo.common.extension.Activate; +import org.apache.dubbo.common.utils.ConfigUtils; +import org.apache.dubbo.common.utils.StringUtils; +import org.apache.dubbo.rpc.AsyncRpcResult; +import org.apache.dubbo.rpc.Filter; +import org.apache.dubbo.rpc.Invocation; +import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.Result; +import org.apache.dubbo.rpc.RpcException; + +import java.io.Serializable; + +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; +import static org.apache.dubbo.common.constants.FilterConstants.CACHE_KEY; + +/** + * CacheFilter is a core component of dubbo.Enabling cache key of service,method,consumer or provider dubbo will cache method return value. + * Along with cache key we need to configure cache type. Dubbo default implemented cache types are + * lur + * threadlocal + * jcache + * expiring + * + * + * e.g. 1)<dubbo:service cache="lru" /> + * 2)<dubbo:service /> <dubbo:method name="method2" cache="threadlocal" /> <dubbo:service/> + * 3)<dubbo:provider cache="expiring" /> + * 4)<dubbo:consumer cache="jcache" /> + * + *If cache type is defined in method level then method level type will get precedence. According to above provided + *example, if service has two method, method1 and method2, method2 will have cache type as threadlocal where others will + *be backed by lru + * + * + * @see org.apache.dubbo.rpc.Filter + * @see org.apache.dubbo.cache.support.lru.LruCacheFactory + * @see org.apache.dubbo.cache.support.lru.LruCache + * @see org.apache.dubbo.cache.support.jcache.JCacheFactory + * @see org.apache.dubbo.cache.support.jcache.JCache + * @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCacheFactory + * @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCache + * @see org.apache.dubbo.cache.support.expiring.ExpiringCacheFactory + * @see org.apache.dubbo.cache.support.expiring.ExpiringCache + * + */ +@Activate(group = {CONSUMER, PROVIDER}, value = CACHE_KEY) +public class CacheFilter implements Filter { + + private CacheFactory cacheFactory; + + /** + * Dubbo will populate and set the cache factory instance based on service/method/consumer/provider configured + * cache attribute value. Dubbo will search for the class name implementing configured cache in file org.apache.dubbo.cache.CacheFactory + * under META-INF sub folders. + * + * @param cacheFactory instance of CacheFactory based on cache type + */ + public void setCacheFactory(CacheFactory cacheFactory) { + this.cacheFactory = cacheFactory; + } + + /** + * If cache is configured, dubbo will invoke method on each method call. If cache value is returned by cache store + * then it will return otherwise call the remote method and return value. If remote method's return value has error + * then it will not cache the value. + * @param invoker service + * @param invocation invocation. + * @return Cache returned value if found by the underlying cache store. If cache miss it will call target method. + * @throws RpcException + */ + @Override + public Result invoke(Invoker> invoker, Invocation invocation) throws RpcException { + if (cacheFactory != null && ConfigUtils.isNotEmpty(invoker.getUrl().getMethodParameter(invocation.getMethodName(), CACHE_KEY))) { + Cache cache = cacheFactory.getCache(invoker.getUrl(), invocation); + if (cache != null) { + String key = StringUtils.toArgumentString(invocation.getArguments()); + Object value = cache.get(key); + if (value != null) { + if (value instanceof ValueWrapper) { + return AsyncRpcResult.newDefaultAsyncResult(((ValueWrapper) value).get(), invocation); + } else { + return AsyncRpcResult.newDefaultAsyncResult(value, invocation); + } + } + Result result = invoker.invoke(invocation); + if (!result.hasException()) { + cache.put(key, new ValueWrapper(result.getValue())); + } + return result; + } + } + return invoker.invoke(invocation); + } + + /** + * Cache value wrapper. + */ + static class ValueWrapper implements Serializable { + + private static final long serialVersionUID = -1777337318019193256L; + + private final Object value; + + public ValueWrapper (Object value) { + this.value = value; + } + + public Object get() { + return this.value; + } + } +} diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java index 98ca797b24..966d923a78 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java @@ -1,72 +1,72 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.cache.support; - -import org.apache.dubbo.cache.Cache; -import org.apache.dubbo.cache.CacheFactory; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.rpc.Invocation; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; - -/** - * AbstractCacheFactory is a default implementation of {@link CacheFactory}. It abstract out the key formation from URL along with - * invocation method. It initially check if the value for key already present in own local in-memory store then it won't check underlying storage cache {@link Cache}. - * Internally it used {@link ConcurrentHashMap} to store do level-1 caching. - * - * @see CacheFactory - * @see org.apache.dubbo.cache.support.jcache.JCacheFactory - * @see org.apache.dubbo.cache.support.lru.LruCacheFactory - * @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCacheFactory - * @see org.apache.dubbo.cache.support.expiring.ExpiringCacheFactory - */ -public abstract class AbstractCacheFactory implements CacheFactory { - - /** - * This is used to store factory level-1 cached data. - */ - private final ConcurrentMap caches = new ConcurrentHashMap(); - - /** - * Takes URL and invocation instance and return cache instance for a given url. - * @param url url of the method - * @param invocation invocation context. - * @return Instance of cache store used as storage for caching return values. - */ - @Override - public Cache getCache(URL url, Invocation invocation) { - url = url.addParameter(METHOD_KEY, invocation.getMethodName()); - String key = url.toFullString(); - Cache cache = caches.get(key); - if (cache == null) { - caches.put(key, createCache(url)); - cache = caches.get(key); - } - return cache; - } - - /** - * Takes url as an method argument and return new instance of cache store implemented by AbstractCacheFactory subclass. - * @param url url of the method - * @return Create and return new instance of cache store used as storage for caching return values. - */ - protected abstract Cache createCache(URL url); - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.cache.support; + +import org.apache.dubbo.cache.Cache; +import org.apache.dubbo.cache.CacheFactory; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.rpc.Invocation; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; + +/** + * AbstractCacheFactory is a default implementation of {@link CacheFactory}. It abstract out the key formation from URL along with + * invocation method. It initially check if the value for key already present in own local in-memory store then it won't check underlying storage cache {@link Cache}. + * Internally it used {@link ConcurrentHashMap} to store do level-1 caching. + * + * @see CacheFactory + * @see org.apache.dubbo.cache.support.jcache.JCacheFactory + * @see org.apache.dubbo.cache.support.lru.LruCacheFactory + * @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCacheFactory + * @see org.apache.dubbo.cache.support.expiring.ExpiringCacheFactory + */ +public abstract class AbstractCacheFactory implements CacheFactory { + + /** + * This is used to store factory level-1 cached data. + */ + private final ConcurrentMap caches = new ConcurrentHashMap(); + + /** + * Takes URL and invocation instance and return cache instance for a given url. + * @param url url of the method + * @param invocation invocation context. + * @return Instance of cache store used as storage for caching return values. + */ + @Override + public Cache getCache(URL url, Invocation invocation) { + url = url.addParameter(METHOD_KEY, invocation.getMethodName()); + String key = url.toFullString(); + Cache cache = caches.get(key); + if (cache == null) { + caches.put(key, createCache(url)); + cache = caches.get(key); + } + return cache; + } + + /** + * Takes url as an method argument and return new instance of cache store implemented by AbstractCacheFactory subclass. + * @param url url of the method + * @return Create and return new instance of cache store used as storage for caching return values. + */ + protected abstract Cache createCache(URL url); + +} diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCache.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCache.java index bf4b3d1646..7972a9dd9a 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCache.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCache.java @@ -1,87 +1,87 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.cache.support.jcache; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.StringUtils; - -import javax.cache.Cache; -import javax.cache.CacheException; -import javax.cache.CacheManager; -import javax.cache.Caching; -import javax.cache.configuration.MutableConfiguration; -import javax.cache.expiry.CreatedExpiryPolicy; -import javax.cache.expiry.Duration; -import javax.cache.spi.CachingProvider; -import java.util.concurrent.TimeUnit; - -import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; - -/** - * This class store the cache value per thread. If a service,method,consumer or provided is configured with key cache - * with value jcache, dubbo initialize the instance of this class using {@link JCacheFactory} to store method's returns value - * to server from store without making method call. - * - * @see Cache - * @see JCacheFactory - * @see org.apache.dubbo.cache.support.AbstractCacheFactory - * @see org.apache.dubbo.cache.filter.CacheFilter - */ -public class JCache implements org.apache.dubbo.cache.Cache { - - private final Cache store; - - public JCache(URL url) { - String method = url.getParameter(METHOD_KEY, ""); - String key = url.getAddress() + "." + url.getServiceKey() + "." + method; - // jcache parameter is the full-qualified class name of SPI implementation - String type = url.getParameter("jcache"); - - CachingProvider provider = StringUtils.isEmpty(type) ? Caching.getCachingProvider() : Caching.getCachingProvider(type); - CacheManager cacheManager = provider.getCacheManager(); - Cache cache = cacheManager.getCache(key); - if (cache == null) { - try { - //configure the cache - MutableConfiguration config = - new MutableConfiguration<>() - .setTypes(Object.class, Object.class) - .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MILLISECONDS, url.getMethodParameter(method, "cache.write.expire", 60 * 1000)))) - .setStoreByValue(false) - .setManagementEnabled(true) - .setStatisticsEnabled(true); - cache = cacheManager.createCache(key, config); - } catch (CacheException e) { - // concurrent cache initialization - cache = cacheManager.getCache(key); - } - } - - this.store = cache; - } - - @Override - public void put(Object key, Object value) { - store.put(key, value); - } - - @Override - public Object get(Object key) { - return store.get(key); - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.cache.support.jcache; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.utils.StringUtils; + +import javax.cache.Cache; +import javax.cache.CacheException; +import javax.cache.CacheManager; +import javax.cache.Caching; +import javax.cache.configuration.MutableConfiguration; +import javax.cache.expiry.CreatedExpiryPolicy; +import javax.cache.expiry.Duration; +import javax.cache.spi.CachingProvider; +import java.util.concurrent.TimeUnit; + +import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; + +/** + * This class store the cache value per thread. If a service,method,consumer or provided is configured with key cache + * with value jcache, dubbo initialize the instance of this class using {@link JCacheFactory} to store method's returns value + * to server from store without making method call. + * + * @see Cache + * @see JCacheFactory + * @see org.apache.dubbo.cache.support.AbstractCacheFactory + * @see org.apache.dubbo.cache.filter.CacheFilter + */ +public class JCache implements org.apache.dubbo.cache.Cache { + + private final Cache store; + + public JCache(URL url) { + String method = url.getParameter(METHOD_KEY, ""); + String key = url.getAddress() + "." + url.getServiceKey() + "." + method; + // jcache parameter is the full-qualified class name of SPI implementation + String type = url.getParameter("jcache"); + + CachingProvider provider = StringUtils.isEmpty(type) ? Caching.getCachingProvider() : Caching.getCachingProvider(type); + CacheManager cacheManager = provider.getCacheManager(); + Cache cache = cacheManager.getCache(key); + if (cache == null) { + try { + //configure the cache + MutableConfiguration config = + new MutableConfiguration<>() + .setTypes(Object.class, Object.class) + .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MILLISECONDS, url.getMethodParameter(method, "cache.write.expire", 60 * 1000)))) + .setStoreByValue(false) + .setManagementEnabled(true) + .setStatisticsEnabled(true); + cache = cacheManager.createCache(key, config); + } catch (CacheException e) { + // concurrent cache initialization + cache = cacheManager.getCache(key); + } + } + + this.store = cache; + } + + @Override + public void put(Object key, Object value) { + store.put(key, value); + } + + @Override + public Object get(Object key) { + return store.get(key); + } + +} diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCacheFactory.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCacheFactory.java index c4d713f0b1..aba9a2f9c4 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCacheFactory.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCacheFactory.java @@ -1,48 +1,48 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.cache.support.jcache; - -import org.apache.dubbo.cache.Cache; -import org.apache.dubbo.cache.support.AbstractCacheFactory; -import org.apache.dubbo.common.URL; - -import javax.cache.spi.CachingProvider; - -/** - * JCacheFactory is factory class to provide instance of javax spi cache.Implement {@link org.apache.dubbo.cache.CacheFactory} by - * extending {@link AbstractCacheFactory} and provide - * @see AbstractCacheFactory - * @see JCache - * @see org.apache.dubbo.cache.filter.CacheFilter - * @see Cache - * @see CachingProvider - * @see javax.cache.Cache - * @see javax.cache.CacheManager - */ -public class JCacheFactory extends AbstractCacheFactory { - - /** - * Takes url as an method argument and return new instance of cache store implemented by JCache. - * @param url url of the method - * @return JCache instance of cache - */ - @Override - protected Cache createCache(URL url) { - return new JCache(url); - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.cache.support.jcache; + +import org.apache.dubbo.cache.Cache; +import org.apache.dubbo.cache.support.AbstractCacheFactory; +import org.apache.dubbo.common.URL; + +import javax.cache.spi.CachingProvider; + +/** + * JCacheFactory is factory class to provide instance of javax spi cache.Implement {@link org.apache.dubbo.cache.CacheFactory} by + * extending {@link AbstractCacheFactory} and provide + * @see AbstractCacheFactory + * @see JCache + * @see org.apache.dubbo.cache.filter.CacheFilter + * @see Cache + * @see CachingProvider + * @see javax.cache.Cache + * @see javax.cache.CacheManager + */ +public class JCacheFactory extends AbstractCacheFactory { + + /** + * Takes url as an method argument and return new instance of cache store implemented by JCache. + * @param url url of the method + * @return JCache instance of cache + */ + @Override + protected Cache createCache(URL url) { + return new JCache(url); + } + +} diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCache.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCache.java index bb24fed9b2..1b8022fb78 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCache.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCache.java @@ -1,80 +1,80 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.cache.support.lru; - -import org.apache.dubbo.cache.Cache; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.LRUCache; - -import java.util.Map; - -/** - * This class store the cache value per thread. If a service,method,consumer or provided is configured with key cache - * with value lru, dubbo initialize the instance of this class using {@link LruCacheFactory} to store method's returns value - * to server from store without making method call. - * - * e.g. 1) <dubbo:service cache="lru" cache.size="5000"/> - * 2) <dubbo:consumer cache="lru" /> - * - * - * LruCache uses url's cache.size value for its max store size, if nothing is provided then - * default value will be 1000 - * - * - * @see Cache - * @see LruCacheFactory - * @see org.apache.dubbo.cache.support.AbstractCacheFactory - * @see org.apache.dubbo.cache.filter.CacheFilter - */ -public class LruCache implements Cache { - - /** - * This is used to store cache records - */ - private final Map store; - - /** - * Initialize LruCache, it uses constructor argument cache.size value as its storage max size. - * If nothing is provided then it will use 1000 as default value. - * @param url A valid URL instance - */ - public LruCache(URL url) { - final int max = url.getParameter("cache.size", 1000); - this.store = new LRUCache<>(max); - } - - /** - * API to store value against a key in the calling thread scope. - * @param key Unique identifier for the object being store. - * @param value Value getting store - */ - @Override - public void put(Object key, Object value) { - store.put(key, value); - } - - /** - * API to return stored value using a key against the calling thread specific store. - * @param key Unique identifier for cache lookup - * @return Return stored object against key - */ - @Override - public Object get(Object key) { - return store.get(key); - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.cache.support.lru; + +import org.apache.dubbo.cache.Cache; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.utils.LRUCache; + +import java.util.Map; + +/** + * This class store the cache value per thread. If a service,method,consumer or provided is configured with key cache + * with value lru, dubbo initialize the instance of this class using {@link LruCacheFactory} to store method's returns value + * to server from store without making method call. + * + * e.g. 1) <dubbo:service cache="lru" cache.size="5000"/> + * 2) <dubbo:consumer cache="lru" /> + * + * + * LruCache uses url's cache.size value for its max store size, if nothing is provided then + * default value will be 1000 + * + * + * @see Cache + * @see LruCacheFactory + * @see org.apache.dubbo.cache.support.AbstractCacheFactory + * @see org.apache.dubbo.cache.filter.CacheFilter + */ +public class LruCache implements Cache { + + /** + * This is used to store cache records + */ + private final Map store; + + /** + * Initialize LruCache, it uses constructor argument cache.size value as its storage max size. + * If nothing is provided then it will use 1000 as default value. + * @param url A valid URL instance + */ + public LruCache(URL url) { + final int max = url.getParameter("cache.size", 1000); + this.store = new LRUCache<>(max); + } + + /** + * API to store value against a key in the calling thread scope. + * @param key Unique identifier for the object being store. + * @param value Value getting store + */ + @Override + public void put(Object key, Object value) { + store.put(key, value); + } + + /** + * API to return stored value using a key against the calling thread specific store. + * @param key Unique identifier for cache lookup + * @return Return stored object against key + */ + @Override + public Object get(Object key) { + return store.get(key); + } + +} diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCacheFactory.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCacheFactory.java index cda21292e8..9ec94862a5 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCacheFactory.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCacheFactory.java @@ -1,43 +1,43 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.cache.support.lru; - -import org.apache.dubbo.cache.Cache; -import org.apache.dubbo.cache.support.AbstractCacheFactory; -import org.apache.dubbo.common.URL; - -/** - * Implement {@link org.apache.dubbo.cache.CacheFactory} by extending {@link AbstractCacheFactory} and provide - * instance of new {@link LruCache}. - * - * @see AbstractCacheFactory - * @see LruCache - * @see Cache - */ -public class LruCacheFactory extends AbstractCacheFactory { - - /** - * Takes url as an method argument and return new instance of cache store implemented by LruCache. - * @param url url of the method - * @return ThreadLocalCache instance of cache - */ - @Override - protected Cache createCache(URL url) { - return new LruCache(url); - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.cache.support.lru; + +import org.apache.dubbo.cache.Cache; +import org.apache.dubbo.cache.support.AbstractCacheFactory; +import org.apache.dubbo.common.URL; + +/** + * Implement {@link org.apache.dubbo.cache.CacheFactory} by extending {@link AbstractCacheFactory} and provide + * instance of new {@link LruCache}. + * + * @see AbstractCacheFactory + * @see LruCache + * @see Cache + */ +public class LruCacheFactory extends AbstractCacheFactory { + + /** + * Takes url as an method argument and return new instance of cache store implemented by LruCache. + * @param url url of the method + * @return ThreadLocalCache instance of cache + */ + @Override + protected Cache createCache(URL url) { + return new LruCache(url); + } + +} diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCache.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCache.java index 412e1beae2..12b3b5ca03 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCache.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCache.java @@ -1,77 +1,77 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.cache.support.threadlocal; - -import org.apache.dubbo.cache.Cache; -import org.apache.dubbo.common.URL; - -import java.util.HashMap; -import java.util.Map; - -/** - * This class store the cache value per thread. If a service,method,consumer or provided is configured with key cache - * with value threadlocal, dubbo initialize the instance of this class using {@link ThreadLocalCacheFactory} to store method's returns value - * to server from store without making method call. - * - * e.g. <dubbo:service cache="threadlocal" /> - * - * - * As this ThreadLocalCache stores key-value in memory without any expiry or delete support per thread wise, if number threads and number of key-value are high then jvm should be - * configured with appropriate memory. - * - * - * @see org.apache.dubbo.cache.support.AbstractCacheFactory - * @see org.apache.dubbo.cache.filter.CacheFilter - * @see Cache - */ -public class ThreadLocalCache implements Cache { - - /** - * Thread local variable to store cached data. - */ - private final ThreadLocal> store; - - /** - * Taken URL as an argument to create an instance of ThreadLocalCache. In this version of implementation constructor - * argument is not getting used in the scope of this class. - * @param url - */ - public ThreadLocalCache(URL url) { - this.store = ThreadLocal.withInitial(HashMap::new); - } - - /** - * API to store value against a key in the calling thread scope. - * @param key Unique identifier for the object being store. - * @param value Value getting store - */ - @Override - public void put(Object key, Object value) { - store.get().put(key, value); - } - - /** - * API to return stored value using a key against the calling thread specific store. - * @param key Unique identifier for cache lookup - * @return Return stored object against key - */ - @Override - public Object get(Object key) { - return store.get().get(key); - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.cache.support.threadlocal; + +import org.apache.dubbo.cache.Cache; +import org.apache.dubbo.common.URL; + +import java.util.HashMap; +import java.util.Map; + +/** + * This class store the cache value per thread. If a service,method,consumer or provided is configured with key cache + * with value threadlocal, dubbo initialize the instance of this class using {@link ThreadLocalCacheFactory} to store method's returns value + * to server from store without making method call. + * + * e.g. <dubbo:service cache="threadlocal" /> + * + * + * As this ThreadLocalCache stores key-value in memory without any expiry or delete support per thread wise, if number threads and number of key-value are high then jvm should be + * configured with appropriate memory. + * + * + * @see org.apache.dubbo.cache.support.AbstractCacheFactory + * @see org.apache.dubbo.cache.filter.CacheFilter + * @see Cache + */ +public class ThreadLocalCache implements Cache { + + /** + * Thread local variable to store cached data. + */ + private final ThreadLocal> store; + + /** + * Taken URL as an argument to create an instance of ThreadLocalCache. In this version of implementation constructor + * argument is not getting used in the scope of this class. + * @param url + */ + public ThreadLocalCache(URL url) { + this.store = ThreadLocal.withInitial(HashMap::new); + } + + /** + * API to store value against a key in the calling thread scope. + * @param key Unique identifier for the object being store. + * @param value Value getting store + */ + @Override + public void put(Object key, Object value) { + store.get().put(key, value); + } + + /** + * API to return stored value using a key against the calling thread specific store. + * @param key Unique identifier for cache lookup + * @return Return stored object against key + */ + @Override + public Object get(Object key) { + return store.get().get(key); + } + +} diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactory.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactory.java index bde16f63bd..cdda6cf3e4 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactory.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactory.java @@ -1,43 +1,43 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.cache.support.threadlocal; - -import org.apache.dubbo.cache.Cache; -import org.apache.dubbo.cache.support.AbstractCacheFactory; -import org.apache.dubbo.common.URL; - -/** - * Implement {@link org.apache.dubbo.cache.CacheFactory} by extending {@link AbstractCacheFactory} and provide - * instance of new {@link ThreadLocalCache}. Note about this class is, each thread does not have a local copy of factory. - * - * @see AbstractCacheFactory - * @see ThreadLocalCache - * @see Cache - */ -public class ThreadLocalCacheFactory extends AbstractCacheFactory { - - /** - * Takes url as an method argument and return new instance of cache store implemented by ThreadLocalCache. - * @param url url of the method - * @return ThreadLocalCache instance of cache - */ - @Override - protected Cache createCache(URL url) { - return new ThreadLocalCache(url); - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.cache.support.threadlocal; + +import org.apache.dubbo.cache.Cache; +import org.apache.dubbo.cache.support.AbstractCacheFactory; +import org.apache.dubbo.common.URL; + +/** + * Implement {@link org.apache.dubbo.cache.CacheFactory} by extending {@link AbstractCacheFactory} and provide + * instance of new {@link ThreadLocalCache}. Note about this class is, each thread does not have a local copy of factory. + * + * @see AbstractCacheFactory + * @see ThreadLocalCache + * @see Cache + */ +public class ThreadLocalCacheFactory extends AbstractCacheFactory { + + /** + * Takes url as an method argument and return new instance of cache store implemented by ThreadLocalCache. + * @param url url of the method + * @return ThreadLocalCache instance of cache + */ + @Override + protected Cache createCache(URL url) { + return new ThreadLocalCache(url); + } + +} diff --git a/dubbo-filter/dubbo-filter-cache/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.cache.CacheFactory b/dubbo-filter/dubbo-filter-cache/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.cache.CacheFactory index c849461da1..1ea180adf5 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.cache.CacheFactory +++ b/dubbo-filter/dubbo-filter-cache/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.cache.CacheFactory @@ -1,4 +1,4 @@ -threadlocal=org.apache.dubbo.cache.support.threadlocal.ThreadLocalCacheFactory -lru=org.apache.dubbo.cache.support.lru.LruCacheFactory -jcache=org.apache.dubbo.cache.support.jcache.JCacheFactory +threadlocal=org.apache.dubbo.cache.support.threadlocal.ThreadLocalCacheFactory +lru=org.apache.dubbo.cache.support.lru.LruCacheFactory +jcache=org.apache.dubbo.cache.support.jcache.JCacheFactory expiring=org.apache.dubbo.cache.support.expiring.ExpiringCacheFactory \ No newline at end of file diff --git a/dubbo-filter/dubbo-filter-validation/pom.xml b/dubbo-filter/dubbo-filter-validation/pom.xml index 164653e52c..933f1c97be 100644 --- a/dubbo-filter/dubbo-filter-validation/pom.xml +++ b/dubbo-filter/dubbo-filter-validation/pom.xml @@ -19,8 +19,7 @@ org.apache.dubbo dubbo-filter - ${revision} - ../pom.xml + 2.7.7-SNAPSHOT dubbo-filter-validation jar diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validation.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validation.java index 281346c2ec..73c4cd8cdc 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validation.java +++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validation.java @@ -1,39 +1,39 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.validation; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.Adaptive; -import org.apache.dubbo.common.extension.SPI; - -import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY; - -/** - * Instance of Validation interface provide instance of {@link Validator} based on the value of validation attribute. - */ -@SPI("jvalidation") -public interface Validation { - - /** - * Return the instance of {@link Validator} for a given url. - * @param url Invocation url - * @return Instance of {@link Validator} - */ - @Adaptive(VALIDATION_KEY) - Validator getValidator(URL url); - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.validation; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.extension.Adaptive; +import org.apache.dubbo.common.extension.SPI; + +import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY; + +/** + * Instance of Validation interface provide instance of {@link Validator} based on the value of validation attribute. + */ +@SPI("jvalidation") +public interface Validation { + + /** + * Return the instance of {@link Validator} for a given url. + * @param url Invocation url + * @return Instance of {@link Validator} + */ + @Adaptive(VALIDATION_KEY) + Validator getValidator(URL url); + +} diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validator.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validator.java index b1565ba4b6..c78c62a116 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validator.java +++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validator.java @@ -1,27 +1,27 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.validation; - -/** - * Instance of validator class is an extension to perform validation on method input parameter before the actual method invocation. - * - */ -public interface Validator { - - void validate(String methodName, Class>[] parameterTypes, Object[] arguments) throws Exception; - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.validation; + +/** + * Instance of validator class is an extension to perform validation on method input parameter before the actual method invocation. + * + */ +public interface Validator { + + void validate(String methodName, Class>[] parameterTypes, Object[] arguments) throws Exception; + +} diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java index 774b1debb5..0df27526e1 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java +++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java @@ -1,104 +1,104 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.validation.filter; - -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.common.utils.ConfigUtils; -import org.apache.dubbo.rpc.AsyncRpcResult; -import org.apache.dubbo.rpc.Filter; -import org.apache.dubbo.rpc.Invocation; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Result; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.validation.Validation; -import org.apache.dubbo.validation.Validator; - -import javax.validation.ValidationException; - -import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; -import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; -import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY; - -/** - * ValidationFilter invoke the validation by finding the right {@link Validator} instance based on the - * configured validation attribute value of invoker url before the actual method invocation. - * - * - * e.g. <dubbo:method name="save" validation="jvalidation" /> - * In the above configuration a validation has been configured of type jvalidation. On invocation of method save - * dubbo will invoke {@link org.apache.dubbo.validation.support.jvalidation.JValidator} - * - * - * To add a new type of validation - * - * e.g. <dubbo:method name="save" validation="special" /> - * where "special" is representing a validator for special character. - * - * - * developer needs to do - * - * 1)Implement a SpecialValidation.java class (package name xxx.yyy.zzz) either by implementing {@link Validation} or extending {@link org.apache.dubbo.validation.support.AbstractValidation} - * 2)Implement a SpecialValidator.java class (package name xxx.yyy.zzz) - * 3)Add an entry special=xxx.yyy.zzz.SpecialValidation under META-INF folders org.apache.dubbo.validation.Validation file. - * - * @see Validation - * @see Validator - * @see Filter - * @see org.apache.dubbo.validation.support.AbstractValidation - */ -@Activate(group = {CONSUMER, PROVIDER}, value = VALIDATION_KEY, order = 10000) -public class ValidationFilter implements Filter { - - private Validation validation; - - /** - * Sets the validation instance for ValidationFilter - * @param validation Validation instance injected by dubbo framework based on "validation" attribute value. - */ - public void setValidation(Validation validation) { - this.validation = validation; - } - - /** - * Perform the validation of before invoking the actual method based on validation attribute value. - * @param invoker service - * @param invocation invocation. - * @return Method invocation result - * @throws RpcException Throws RpcException if validation failed or any other runtime exception occurred. - */ - @Override - public Result invoke(Invoker> invoker, Invocation invocation) throws RpcException { - if (validation != null && !invocation.getMethodName().startsWith("$") - && ConfigUtils.isNotEmpty(invoker.getUrl().getMethodParameter(invocation.getMethodName(), VALIDATION_KEY))) { - try { - Validator validator = validation.getValidator(invoker.getUrl()); - if (validator != null) { - validator.validate(invocation.getMethodName(), invocation.getParameterTypes(), invocation.getArguments()); - } - } catch (RpcException e) { - throw e; - } catch (ValidationException e) { - // only use exception's message to avoid potential serialization issue - return AsyncRpcResult.newDefaultAsyncResult(new ValidationException(e.getMessage()), invocation); - } catch (Throwable t) { - return AsyncRpcResult.newDefaultAsyncResult(t, invocation); - } - } - return invoker.invoke(invocation); - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.validation.filter; + +import org.apache.dubbo.common.extension.Activate; +import org.apache.dubbo.common.utils.ConfigUtils; +import org.apache.dubbo.rpc.AsyncRpcResult; +import org.apache.dubbo.rpc.Filter; +import org.apache.dubbo.rpc.Invocation; +import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.Result; +import org.apache.dubbo.rpc.RpcException; +import org.apache.dubbo.validation.Validation; +import org.apache.dubbo.validation.Validator; + +import javax.validation.ValidationException; + +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; +import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY; + +/** + * ValidationFilter invoke the validation by finding the right {@link Validator} instance based on the + * configured validation attribute value of invoker url before the actual method invocation. + * + * + * e.g. <dubbo:method name="save" validation="jvalidation" /> + * In the above configuration a validation has been configured of type jvalidation. On invocation of method save + * dubbo will invoke {@link org.apache.dubbo.validation.support.jvalidation.JValidator} + * + * + * To add a new type of validation + * + * e.g. <dubbo:method name="save" validation="special" /> + * where "special" is representing a validator for special character. + * + * + * developer needs to do + * + * 1)Implement a SpecialValidation.java class (package name xxx.yyy.zzz) either by implementing {@link Validation} or extending {@link org.apache.dubbo.validation.support.AbstractValidation} + * 2)Implement a SpecialValidator.java class (package name xxx.yyy.zzz) + * 3)Add an entry special=xxx.yyy.zzz.SpecialValidation under META-INF folders org.apache.dubbo.validation.Validation file. + * + * @see Validation + * @see Validator + * @see Filter + * @see org.apache.dubbo.validation.support.AbstractValidation + */ +@Activate(group = {CONSUMER, PROVIDER}, value = VALIDATION_KEY, order = 10000) +public class ValidationFilter implements Filter { + + private Validation validation; + + /** + * Sets the validation instance for ValidationFilter + * @param validation Validation instance injected by dubbo framework based on "validation" attribute value. + */ + public void setValidation(Validation validation) { + this.validation = validation; + } + + /** + * Perform the validation of before invoking the actual method based on validation attribute value. + * @param invoker service + * @param invocation invocation. + * @return Method invocation result + * @throws RpcException Throws RpcException if validation failed or any other runtime exception occurred. + */ + @Override + public Result invoke(Invoker> invoker, Invocation invocation) throws RpcException { + if (validation != null && !invocation.getMethodName().startsWith("$") + && ConfigUtils.isNotEmpty(invoker.getUrl().getMethodParameter(invocation.getMethodName(), VALIDATION_KEY))) { + try { + Validator validator = validation.getValidator(invoker.getUrl()); + if (validator != null) { + validator.validate(invocation.getMethodName(), invocation.getParameterTypes(), invocation.getArguments()); + } + } catch (RpcException e) { + throw e; + } catch (ValidationException e) { + // only use exception's message to avoid potential serialization issue + return AsyncRpcResult.newDefaultAsyncResult(new ValidationException(e.getMessage()), invocation); + } catch (Throwable t) { + return AsyncRpcResult.newDefaultAsyncResult(t, invocation); + } + } + return invoker.invoke(invocation); + } + +} diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/AbstractValidation.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/AbstractValidation.java index be161a94d7..a6f9c8eda3 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/AbstractValidation.java +++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/AbstractValidation.java @@ -1,51 +1,51 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.validation.support; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.validation.Validation; -import org.apache.dubbo.validation.Validator; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * AbstractValidation is abstract class for Validation interface. It helps low level Validation implementation classes - * by performing common task e.g. key formation, storing instance of validation class to avoid creation of unnecessary - * copy of validation instance and faster execution. - * - * @see Validation - * @see Validator - */ -public abstract class AbstractValidation implements Validation { - - private final ConcurrentMap validators = new ConcurrentHashMap<>(); - - @Override - public Validator getValidator(URL url) { - String key = url.toFullString(); - Validator validator = validators.get(key); - if (validator == null) { - validators.put(key, createValidator(url)); - validator = validators.get(key); - } - return validator; - } - - protected abstract Validator createValidator(URL url); - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.validation.support; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.validation.Validation; +import org.apache.dubbo.validation.Validator; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * AbstractValidation is abstract class for Validation interface. It helps low level Validation implementation classes + * by performing common task e.g. key formation, storing instance of validation class to avoid creation of unnecessary + * copy of validation instance and faster execution. + * + * @see Validation + * @see Validator + */ +public abstract class AbstractValidation implements Validation { + + private final ConcurrentMap validators = new ConcurrentHashMap<>(); + + @Override + public Validator getValidator(URL url) { + String key = url.toFullString(); + Validator validator = validators.get(key); + if (validator == null) { + validators.put(key, createValidator(url)); + validator = validators.get(key); + } + return validator; + } + + protected abstract Validator createValidator(URL url); + +} diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidation.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidation.java index e0859897f1..e8b48cf1d0 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidation.java +++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidation.java @@ -1,40 +1,40 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.validation.support.jvalidation; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.validation.Validator; -import org.apache.dubbo.validation.support.AbstractValidation; - -/** - * Creates a new instance of {@link Validator} using input argument url. - * @see AbstractValidation - * @see Validator - */ -public class JValidation extends AbstractValidation { - - /** - * Return new instance of {@link JValidator} - * @param url Valid URL instance - * @return Instance of JValidator - */ - @Override - protected Validator createValidator(URL url) { - return new JValidator(url); - } - +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.validation.support.jvalidation; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.validation.Validator; +import org.apache.dubbo.validation.support.AbstractValidation; + +/** + * Creates a new instance of {@link Validator} using input argument url. + * @see AbstractValidation + * @see Validator + */ +public class JValidation extends AbstractValidation { + + /** + * Return new instance of {@link JValidator} + * @param url Valid URL instance + * @return Instance of JValidator + */ + @Override + protected Validator createValidator(URL url) { + return new JValidator(url); + } + } \ No newline at end of file diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java index e3978c6c13..ea8c6dbd4a 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java +++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java @@ -1,330 +1,330 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.validation.support.jvalidation; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.bytecode.ClassGenerator; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.ReflectUtils; -import org.apache.dubbo.validation.MethodValidated; -import org.apache.dubbo.validation.Validator; - -import javassist.ClassPool; -import javassist.CtClass; -import javassist.CtField; -import javassist.CtNewConstructor; -import javassist.Modifier; -import javassist.NotFoundException; -import javassist.bytecode.AnnotationsAttribute; -import javassist.bytecode.ClassFile; -import javassist.bytecode.ConstPool; -import javassist.bytecode.annotation.ArrayMemberValue; -import javassist.bytecode.annotation.BooleanMemberValue; -import javassist.bytecode.annotation.ByteMemberValue; -import javassist.bytecode.annotation.CharMemberValue; -import javassist.bytecode.annotation.ClassMemberValue; -import javassist.bytecode.annotation.DoubleMemberValue; -import javassist.bytecode.annotation.EnumMemberValue; -import javassist.bytecode.annotation.FloatMemberValue; -import javassist.bytecode.annotation.IntegerMemberValue; -import javassist.bytecode.annotation.LongMemberValue; -import javassist.bytecode.annotation.MemberValue; -import javassist.bytecode.annotation.ShortMemberValue; -import javassist.bytecode.annotation.StringMemberValue; - -import javax.validation.Constraint; -import javax.validation.ConstraintViolation; -import javax.validation.ConstraintViolationException; -import javax.validation.Validation; -import javax.validation.ValidatorFactory; -import javax.validation.groups.Default; -import java.lang.annotation.Annotation; -import java.lang.reflect.Array; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Implementation of JValidation. JValidation is invoked if configuration validation attribute value is 'jvalidation'. - * - * e.g. <dubbo:method name="save" validation="jvalidation" /> - * - */ -public class JValidator implements Validator { - - private static final Logger logger = LoggerFactory.getLogger(JValidator.class); - - private final Class> clazz; - - private final Map methodClassMap; - - private final javax.validation.Validator validator; - - @SuppressWarnings({"unchecked", "rawtypes"}) - public JValidator(URL url) { - this.clazz = ReflectUtils.forName(url.getServiceInterface()); - String jvalidation = url.getParameter("jvalidation"); - ValidatorFactory factory; - if (jvalidation != null && jvalidation.length() > 0) { - factory = Validation.byProvider((Class) ReflectUtils.forName(jvalidation)).configure().buildValidatorFactory(); - } else { - factory = Validation.buildDefaultValidatorFactory(); - } - this.validator = factory.getValidator(); - this.methodClassMap = new ConcurrentHashMap<>(); - } - - private static Object getMethodParameterBean(Class> clazz, Method method, Object[] args) { - if (!hasConstraintParameter(method)) { - return null; - } - try { - String parameterClassName = generateMethodParameterClassName(clazz, method); - Class> parameterClass; - try { - parameterClass = Class.forName(parameterClassName, true, clazz.getClassLoader()); - } catch (ClassNotFoundException e) { - parameterClass = generateMethodParameterClass(clazz, method, parameterClassName); - } - Object parameterBean = parameterClass.newInstance(); - for (int i = 0; i < args.length; i++) { - Field field = parameterClass.getField(method.getName() + "Argument" + i); - field.set(parameterBean, args[i]); - } - return parameterBean; - } catch (Throwable e) { - logger.warn(e.getMessage(), e); - return null; - } - } - - /** - * try to generate methodParameterClass. - * - * @param clazz interface class - * @param method invoke method - * @param parameterClassName generated parameterClassName - * @return Class> generated methodParameterClass - * @throws Exception - */ - private static Class> generateMethodParameterClass(Class> clazz, Method method, String parameterClassName) - throws Exception { - ClassPool pool = ClassGenerator.getClassPool(clazz.getClassLoader()); - synchronized (parameterClassName.intern()) { - CtClass ctClass = null; - try { - ctClass = pool.getCtClass(parameterClassName); - } catch (NotFoundException ignore) { - } - - if (null == ctClass) { - ctClass = pool.makeClass(parameterClassName); - ClassFile classFile = ctClass.getClassFile(); - classFile.setVersionToJava5(); - ctClass.addConstructor(CtNewConstructor.defaultConstructor(pool.getCtClass(parameterClassName))); - // parameter fields - Class>[] parameterTypes = method.getParameterTypes(); - Annotation[][] parameterAnnotations = method.getParameterAnnotations(); - for (int i = 0; i < parameterTypes.length; i++) { - Class> type = parameterTypes[i]; - Annotation[] annotations = parameterAnnotations[i]; - AnnotationsAttribute attribute = new AnnotationsAttribute(classFile.getConstPool(), AnnotationsAttribute.visibleTag); - for (Annotation annotation : annotations) { - if (annotation.annotationType().isAnnotationPresent(Constraint.class)) { - javassist.bytecode.annotation.Annotation ja = new javassist.bytecode.annotation.Annotation( - classFile.getConstPool(), pool.getCtClass(annotation.annotationType().getName())); - Method[] members = annotation.annotationType().getMethods(); - for (Method member : members) { - if (Modifier.isPublic(member.getModifiers()) - && member.getParameterTypes().length == 0 - && member.getDeclaringClass() == annotation.annotationType()) { - Object value = member.invoke(annotation); - if (null != value) { - MemberValue memberValue = createMemberValue( - classFile.getConstPool(), pool.get(member.getReturnType().getName()), value); - ja.addMemberValue(member.getName(), memberValue); - } - } - } - attribute.addAnnotation(ja); - } - } - String fieldName = method.getName() + "Argument" + i; - CtField ctField = CtField.make("public " + type.getCanonicalName() + " " + fieldName + ";", pool.getCtClass(parameterClassName)); - ctField.getFieldInfo().addAttribute(attribute); - ctClass.addField(ctField); - } - return ctClass.toClass(clazz.getClassLoader(), null); - } else { - return Class.forName(parameterClassName, true, clazz.getClassLoader()); - } - } - } - - private static String generateMethodParameterClassName(Class> clazz, Method method) { - StringBuilder builder = new StringBuilder().append(clazz.getName()) - .append("_") - .append(toUpperMethodName(method.getName())) - .append("Parameter"); - - Class>[] parameterTypes = method.getParameterTypes(); - for (Class> parameterType : parameterTypes) { - builder.append("_").append(parameterType.getName()); - } - - return builder.toString(); - } - - private static boolean hasConstraintParameter(Method method) { - Annotation[][] parameterAnnotations = method.getParameterAnnotations(); - if (parameterAnnotations != null && parameterAnnotations.length > 0) { - for (Annotation[] annotations : parameterAnnotations) { - for (Annotation annotation : annotations) { - if (annotation.annotationType().isAnnotationPresent(Constraint.class)) { - return true; - } - } - } - } - return false; - } - - private static String toUpperMethodName(String methodName) { - return methodName.substring(0, 1).toUpperCase() + methodName.substring(1); - } - - // Copy from javassist.bytecode.annotation.Annotation.createMemberValue(ConstPool, CtClass); - private static MemberValue createMemberValue(ConstPool cp, CtClass type, Object value) throws NotFoundException { - MemberValue memberValue = javassist.bytecode.annotation.Annotation.createMemberValue(cp, type); - if (memberValue instanceof BooleanMemberValue) { - ((BooleanMemberValue) memberValue).setValue((Boolean) value); - } else if (memberValue instanceof ByteMemberValue) { - ((ByteMemberValue) memberValue).setValue((Byte) value); - } else if (memberValue instanceof CharMemberValue) { - ((CharMemberValue) memberValue).setValue((Character) value); - } else if (memberValue instanceof ShortMemberValue) { - ((ShortMemberValue) memberValue).setValue((Short) value); - } else if (memberValue instanceof IntegerMemberValue) { - ((IntegerMemberValue) memberValue).setValue((Integer) value); - } else if (memberValue instanceof LongMemberValue) { - ((LongMemberValue) memberValue).setValue((Long) value); - } else if (memberValue instanceof FloatMemberValue) { - ((FloatMemberValue) memberValue).setValue((Float) value); - } else if (memberValue instanceof DoubleMemberValue) { - ((DoubleMemberValue) memberValue).setValue((Double) value); - } else if (memberValue instanceof ClassMemberValue) { - ((ClassMemberValue) memberValue).setValue(((Class>) value).getName()); - } else if (memberValue instanceof StringMemberValue) { - ((StringMemberValue) memberValue).setValue((String) value); - } else if (memberValue instanceof EnumMemberValue) { - ((EnumMemberValue) memberValue).setValue(((Enum>) value).name()); - } - /* else if (memberValue instanceof AnnotationMemberValue) */ - else if (memberValue instanceof ArrayMemberValue) { - CtClass arrayType = type.getComponentType(); - int len = Array.getLength(value); - MemberValue[] members = new MemberValue[len]; - for (int i = 0; i < len; i++) { - members[i] = createMemberValue(cp, arrayType, Array.get(value, i)); - } - ((ArrayMemberValue) memberValue).setValue(members); - } - return memberValue; - } - - @Override - public void validate(String methodName, Class>[] parameterTypes, Object[] arguments) throws Exception { - List> groups = new ArrayList<>(); - Class> methodClass = methodClass(methodName); - if (methodClass != null) { - groups.add(methodClass); - } - Set> violations = new HashSet<>(); - Method method = clazz.getMethod(methodName, parameterTypes); - Class>[] methodClasses; - if (method.isAnnotationPresent(MethodValidated.class)){ - methodClasses = method.getAnnotation(MethodValidated.class).value(); - groups.addAll(Arrays.asList(methodClasses)); - } - // add into default group - groups.add(0, Default.class); - groups.add(1, clazz); - - // convert list to array - Class>[] classgroups = groups.toArray(new Class[groups.size()]); - - Object parameterBean = getMethodParameterBean(clazz, method, arguments); - if (parameterBean != null) { - violations.addAll(validator.validate(parameterBean, classgroups )); - } - - for (Object arg : arguments) { - validate(violations, arg, classgroups); - } - - if (!violations.isEmpty()) { - logger.error("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations); - throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations); - } - } - - private Class methodClass(String methodName) { - Class> methodClass = null; - String methodClassName = clazz.getName() + "$" + toUpperMethodName(methodName); - Class cached = methodClassMap.get(methodClassName); - if (cached != null) { - return cached == clazz ? null : cached; - } - try { - methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader()); - methodClassMap.put(methodClassName, methodClass); - } catch (ClassNotFoundException e) { - methodClassMap.put(methodClassName, clazz); - } - return methodClass; - } - - private void validate(Set> violations, Object arg, Class>... groups) { - if (arg != null && !ReflectUtils.isPrimitives(arg.getClass())) { - if (arg instanceof Object[]) { - for (Object item : (Object[]) arg) { - validate(violations, item, groups); - } - } else if (arg instanceof Collection) { - for (Object item : (Collection>) arg) { - validate(violations, item, groups); - } - } else if (arg instanceof Map) { - for (Map.Entry, ?> entry : ((Map, ?>) arg).entrySet()) { - validate(violations, entry.getKey(), groups); - validate(violations, entry.getValue(), groups); - } - } else { - violations.addAll(validator.validate(arg, groups)); - } - } - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dubbo.validation.support.jvalidation; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.bytecode.ClassGenerator; +import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.common.utils.ReflectUtils; +import org.apache.dubbo.validation.MethodValidated; +import org.apache.dubbo.validation.Validator; + +import javassist.ClassPool; +import javassist.CtClass; +import javassist.CtField; +import javassist.CtNewConstructor; +import javassist.Modifier; +import javassist.NotFoundException; +import javassist.bytecode.AnnotationsAttribute; +import javassist.bytecode.ClassFile; +import javassist.bytecode.ConstPool; +import javassist.bytecode.annotation.ArrayMemberValue; +import javassist.bytecode.annotation.BooleanMemberValue; +import javassist.bytecode.annotation.ByteMemberValue; +import javassist.bytecode.annotation.CharMemberValue; +import javassist.bytecode.annotation.ClassMemberValue; +import javassist.bytecode.annotation.DoubleMemberValue; +import javassist.bytecode.annotation.EnumMemberValue; +import javassist.bytecode.annotation.FloatMemberValue; +import javassist.bytecode.annotation.IntegerMemberValue; +import javassist.bytecode.annotation.LongMemberValue; +import javassist.bytecode.annotation.MemberValue; +import javassist.bytecode.annotation.ShortMemberValue; +import javassist.bytecode.annotation.StringMemberValue; + +import javax.validation.Constraint; +import javax.validation.ConstraintViolation; +import javax.validation.ConstraintViolationException; +import javax.validation.Validation; +import javax.validation.ValidatorFactory; +import javax.validation.groups.Default; +import java.lang.annotation.Annotation; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Implementation of JValidation. JValidation is invoked if configuration validation attribute value is 'jvalidation'. + * + * e.g. <dubbo:method name="save" validation="jvalidation" /> + * + */ +public class JValidator implements Validator { + + private static final Logger logger = LoggerFactory.getLogger(JValidator.class); + + private final Class> clazz; + + private final Map methodClassMap; + + private final javax.validation.Validator validator; + + @SuppressWarnings({"unchecked", "rawtypes"}) + public JValidator(URL url) { + this.clazz = ReflectUtils.forName(url.getServiceInterface()); + String jvalidation = url.getParameter("jvalidation"); + ValidatorFactory factory; + if (jvalidation != null && jvalidation.length() > 0) { + factory = Validation.byProvider((Class) ReflectUtils.forName(jvalidation)).configure().buildValidatorFactory(); + } else { + factory = Validation.buildDefaultValidatorFactory(); + } + this.validator = factory.getValidator(); + this.methodClassMap = new ConcurrentHashMap<>(); + } + + private static Object getMethodParameterBean(Class> clazz, Method method, Object[] args) { + if (!hasConstraintParameter(method)) { + return null; + } + try { + String parameterClassName = generateMethodParameterClassName(clazz, method); + Class> parameterClass; + try { + parameterClass = Class.forName(parameterClassName, true, clazz.getClassLoader()); + } catch (ClassNotFoundException e) { + parameterClass = generateMethodParameterClass(clazz, method, parameterClassName); + } + Object parameterBean = parameterClass.newInstance(); + for (int i = 0; i < args.length; i++) { + Field field = parameterClass.getField(method.getName() + "Argument" + i); + field.set(parameterBean, args[i]); + } + return parameterBean; + } catch (Throwable e) { + logger.warn(e.getMessage(), e); + return null; + } + } + + /** + * try to generate methodParameterClass. + * + * @param clazz interface class + * @param method invoke method + * @param parameterClassName generated parameterClassName + * @return Class> generated methodParameterClass + * @throws Exception + */ + private static Class> generateMethodParameterClass(Class> clazz, Method method, String parameterClassName) + throws Exception { + ClassPool pool = ClassGenerator.getClassPool(clazz.getClassLoader()); + synchronized (parameterClassName.intern()) { + CtClass ctClass = null; + try { + ctClass = pool.getCtClass(parameterClassName); + } catch (NotFoundException ignore) { + } + + if (null == ctClass) { + ctClass = pool.makeClass(parameterClassName); + ClassFile classFile = ctClass.getClassFile(); + classFile.setVersionToJava5(); + ctClass.addConstructor(CtNewConstructor.defaultConstructor(pool.getCtClass(parameterClassName))); + // parameter fields + Class>[] parameterTypes = method.getParameterTypes(); + Annotation[][] parameterAnnotations = method.getParameterAnnotations(); + for (int i = 0; i < parameterTypes.length; i++) { + Class> type = parameterTypes[i]; + Annotation[] annotations = parameterAnnotations[i]; + AnnotationsAttribute attribute = new AnnotationsAttribute(classFile.getConstPool(), AnnotationsAttribute.visibleTag); + for (Annotation annotation : annotations) { + if (annotation.annotationType().isAnnotationPresent(Constraint.class)) { + javassist.bytecode.annotation.Annotation ja = new javassist.bytecode.annotation.Annotation( + classFile.getConstPool(), pool.getCtClass(annotation.annotationType().getName())); + Method[] members = annotation.annotationType().getMethods(); + for (Method member : members) { + if (Modifier.isPublic(member.getModifiers()) + && member.getParameterTypes().length == 0 + && member.getDeclaringClass() == annotation.annotationType()) { + Object value = member.invoke(annotation); + if (null != value) { + MemberValue memberValue = createMemberValue( + classFile.getConstPool(), pool.get(member.getReturnType().getName()), value); + ja.addMemberValue(member.getName(), memberValue); + } + } + } + attribute.addAnnotation(ja); + } + } + String fieldName = method.getName() + "Argument" + i; + CtField ctField = CtField.make("public " + type.getCanonicalName() + " " + fieldName + ";", pool.getCtClass(parameterClassName)); + ctField.getFieldInfo().addAttribute(attribute); + ctClass.addField(ctField); + } + return ctClass.toClass(clazz.getClassLoader(), null); + } else { + return Class.forName(parameterClassName, true, clazz.getClassLoader()); + } + } + } + + private static String generateMethodParameterClassName(Class> clazz, Method method) { + StringBuilder builder = new StringBuilder().append(clazz.getName()) + .append("_") + .append(toUpperMethoName(method.getName())) + .append("Parameter"); + + Class>[] parameterTypes = method.getParameterTypes(); + for (Class> parameterType : parameterTypes) { + builder.append("_").append(parameterType.getName()); + } + + return builder.toString(); + } + + private static boolean hasConstraintParameter(Method method) { + Annotation[][] parameterAnnotations = method.getParameterAnnotations(); + if (parameterAnnotations != null && parameterAnnotations.length > 0) { + for (Annotation[] annotations : parameterAnnotations) { + for (Annotation annotation : annotations) { + if (annotation.annotationType().isAnnotationPresent(Constraint.class)) { + return true; + } + } + } + } + return false; + } + + private static String toUpperMethoName(String methodName) { + return methodName.substring(0, 1).toUpperCase() + methodName.substring(1); + } + + // Copy from javassist.bytecode.annotation.Annotation.createMemberValue(ConstPool, CtClass); + private static MemberValue createMemberValue(ConstPool cp, CtClass type, Object value) throws NotFoundException { + MemberValue memberValue = javassist.bytecode.annotation.Annotation.createMemberValue(cp, type); + if (memberValue instanceof BooleanMemberValue) { + ((BooleanMemberValue) memberValue).setValue((Boolean) value); + } else if (memberValue instanceof ByteMemberValue) { + ((ByteMemberValue) memberValue).setValue((Byte) value); + } else if (memberValue instanceof CharMemberValue) { + ((CharMemberValue) memberValue).setValue((Character) value); + } else if (memberValue instanceof ShortMemberValue) { + ((ShortMemberValue) memberValue).setValue((Short) value); + } else if (memberValue instanceof IntegerMemberValue) { + ((IntegerMemberValue) memberValue).setValue((Integer) value); + } else if (memberValue instanceof LongMemberValue) { + ((LongMemberValue) memberValue).setValue((Long) value); + } else if (memberValue instanceof FloatMemberValue) { + ((FloatMemberValue) memberValue).setValue((Float) value); + } else if (memberValue instanceof DoubleMemberValue) { + ((DoubleMemberValue) memberValue).setValue((Double) value); + } else if (memberValue instanceof ClassMemberValue) { + ((ClassMemberValue) memberValue).setValue(((Class>) value).getName()); + } else if (memberValue instanceof StringMemberValue) { + ((StringMemberValue) memberValue).setValue((String) value); + } else if (memberValue instanceof EnumMemberValue) { + ((EnumMemberValue) memberValue).setValue(((Enum>) value).name()); + } + /* else if (memberValue instanceof AnnotationMemberValue) */ + else if (memberValue instanceof ArrayMemberValue) { + CtClass arrayType = type.getComponentType(); + int len = Array.getLength(value); + MemberValue[] members = new MemberValue[len]; + for (int i = 0; i < len; i++) { + members[i] = createMemberValue(cp, arrayType, Array.get(value, i)); + } + ((ArrayMemberValue) memberValue).setValue(members); + } + return memberValue; + } + + @Override + public void validate(String methodName, Class>[] parameterTypes, Object[] arguments) throws Exception { + List> groups = new ArrayList<>(); + Class> methodClass = methodClass(methodName); + if (methodClass != null) { + groups.add(methodClass); + } + Set> violations = new HashSet<>(); + Method method = clazz.getMethod(methodName, parameterTypes); + Class>[] methodClasses; + if (method.isAnnotationPresent(MethodValidated.class)){ + methodClasses = method.getAnnotation(MethodValidated.class).value(); + groups.addAll(Arrays.asList(methodClasses)); + } + // add into default group + groups.add(0, Default.class); + groups.add(1, clazz); + + // convert list to array + Class>[] classgroups = groups.toArray(new Class[groups.size()]); + + Object parameterBean = getMethodParameterBean(clazz, method, arguments); + if (parameterBean != null) { + violations.addAll(validator.validate(parameterBean, classgroups )); + } + + for (Object arg : arguments) { + validate(violations, arg, classgroups); + } + + if (!violations.isEmpty()) { + logger.error("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations); + throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations); + } + } + + private Class methodClass(String methodName) { + Class> methodClass = null; + String methodClassName = clazz.getName() + "$" + toUpperMethoName(methodName); + Class cached = methodClassMap.get(methodClassName); + if (cached != null) { + return cached == clazz ? null : cached; + } + try { + methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader()); + methodClassMap.put(methodClassName, methodClass); + } catch (ClassNotFoundException e) { + methodClassMap.put(methodClassName, clazz); + } + return methodClass; + } + + private void validate(Set> violations, Object arg, Class>... groups) { + if (arg != null && !ReflectUtils.isPrimitives(arg.getClass())) { + if (arg instanceof Object[]) { + for (Object item : (Object[]) arg) { + validate(violations, item, groups); + } + } else if (arg instanceof Collection) { + for (Object item : (Collection>) arg) { + validate(violations, item, groups); + } + } else if (arg instanceof Map) { + for (Map.Entry, ?> entry : ((Map, ?>) arg).entrySet()) { + validate(violations, entry.getKey(), groups); + validate(violations, entry.getValue(), groups); + } + } else { + violations.addAll(validator.validate(arg, groups)); + } + } + } + +} diff --git a/dubbo-metadata/dubbo-metadata-report-consul/pom.xml b/dubbo-metadata/dubbo-metadata-report-consul/pom.xml deleted file mode 100644 index 8a01b72d49..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-consul/pom.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - org.apache.dubbo - dubbo-metadata - ${revision} - ../pom.xml - - 4.0.0 - - dubbo-metadata-report-consul - - - - org.apache.dubbo - dubbo-metadata-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-configcenter-consul - ${project.parent.version} - - - com.ecwid.consul - consul-api - - - - diff --git a/dubbo-metadata/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java b/dubbo-metadata/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java deleted file mode 100644 index e6b7054261..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.dubbo.metadata.store.consul; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.metadata.report.identifier.BaseMetadataIdentifier; -import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum; -import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; -import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier; -import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier; -import org.apache.dubbo.metadata.report.support.AbstractMetadataReport; -import org.apache.dubbo.metadata.report.support.ConfigCenterBasedMetadataReport; -import org.apache.dubbo.rpc.RpcException; - -import com.ecwid.consul.v1.ConsulClient; -import com.ecwid.consul.v1.Response; -import com.ecwid.consul.v1.kv.model.GetValue; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * metadata report impl for consul - * - * @deprecated 2.7.8 This class will be removed in the future, {@link ConfigCenterBasedMetadataReport} as a substitute. - */ -@Deprecated -public class ConsulMetadataReport extends AbstractMetadataReport { - private static final Logger logger = LoggerFactory.getLogger(ConsulMetadataReport.class); - private static final int DEFAULT_PORT = 8500; - - private ConsulClient client; - - public ConsulMetadataReport(URL url) { - super(url); - - String host = url.getHost(); - int port = url.getPort() != 0 ? url.getPort() : DEFAULT_PORT; - client = new ConsulClient(host, port); - } - - @Override - protected void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) { - this.storeMetadata(providerMetadataIdentifier, serviceDefinitions); - } - - @Override - protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, String value) { - this.storeMetadata(consumerMetadataIdentifier, value); - } - - @Override - protected void doSaveMetadata(ServiceMetadataIdentifier serviceMetadataIdentifier, URL url) { - this.storeMetadata(serviceMetadataIdentifier, URL.encode(url.toFullString())); - } - - @Override - protected void doRemoveMetadata(ServiceMetadataIdentifier serviceMetadataIdentifier) { - this.deleteMetadata(serviceMetadataIdentifier); - } - - @Override - protected List doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier) { - //todo encode and decode - String content = getMetadata(metadataIdentifier); - if (StringUtils.isEmpty(content)) { - return Collections.emptyList(); - } - return new ArrayList(Arrays.asList(URL.decode(content))); - } - - @Override - protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urlListStr) { - this.storeMetadata(subscriberMetadataIdentifier, urlListStr); - } - - @Override - protected String doGetSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) { - return getMetadata(subscriberMetadataIdentifier); - } - - private void storeMetadata(BaseMetadataIdentifier identifier, String v) { - try { - client.setKVValue(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), v); - } catch (Throwable t) { - logger.error("Failed to put " + identifier + " to consul " + v + ", cause: " + t.getMessage(), t); - throw new RpcException("Failed to put " + identifier + " to consul " + v + ", cause: " + t.getMessage(), t); - } - } - - private void deleteMetadata(BaseMetadataIdentifier identifier) { - try { - client.deleteKVValue(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY)); - } catch (Throwable t) { - logger.error("Failed to delete " + identifier + " from consul , cause: " + t.getMessage(), t); - throw new RpcException("Failed to delete " + identifier + " from consul , cause: " + t.getMessage(), t); - } - } - - private String getMetadata(BaseMetadataIdentifier identifier) { - try { - Response value = client.getKVValue(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY)); - //FIXME CHECK - if (value != null && value.getValue() != null) { - //todo check decode value and value diff - return value.getValue().getValue(); - } - return null; - } catch (Throwable t) { - logger.error("Failed to get " + identifier + " from consul , cause: " + t.getMessage(), t); - throw new RpcException("Failed to get " + identifier + " from consul , cause: " + t.getMessage(), t); - } - } - - @Override - public String getServiceDefinition(MetadataIdentifier metadataIdentifier) { - return getMetadata(metadataIdentifier); - } -} diff --git a/dubbo-metadata/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReportFactory.java deleted file mode 100644 index 7f5f1901e7..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReportFactory.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.dubbo.metadata.store.consul; - -import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum; -import org.apache.dubbo.metadata.report.support.ConfigCenterBasedMetadataReportFactory; - -/** - * metadata report factory impl for consul - */ -public class ConsulMetadataReportFactory extends ConfigCenterBasedMetadataReportFactory { - - public ConsulMetadataReportFactory() { - super(KeyTypeEnum.UNIQUE_KEY); - } -} diff --git a/dubbo-metadata/dubbo-metadata-report-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory b/dubbo-metadata/dubbo-metadata-report-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory deleted file mode 100644 index 1f27535d44..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory +++ /dev/null @@ -1 +0,0 @@ -consul=org.apache.dubbo.metadata.store.consul.ConsulMetadataReportFactory diff --git a/dubbo-metadata/dubbo-metadata-report-etcd/pom.xml b/dubbo-metadata/dubbo-metadata-report-etcd/pom.xml deleted file mode 100644 index 747dc2a2e0..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-etcd/pom.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - - - org.apache.dubbo - dubbo-metadata - ${revision} - ../pom.xml - - 4.0.0 - - dubbo-metadata-report-etcd - - - true - - - - - org.apache.dubbo - dubbo-metadata-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-etcd3 - ${project.parent.version} - - - io.etcd - jetcd-launcher - test - - - org.testcontainers - testcontainers - test - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - ${skipIntegrationTests} - - - - - diff --git a/dubbo-metadata/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java b/dubbo-metadata/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java deleted file mode 100644 index a80c6e83dd..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.store.etcd; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.metadata.report.identifier.BaseMetadataIdentifier; -import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum; -import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; -import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier; -import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier; -import org.apache.dubbo.metadata.report.support.AbstractMetadataReport; -import org.apache.dubbo.remoting.etcd.jetcd.JEtcdClient; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; - -/** - * Report Metadata to Etcd - */ -public class EtcdMetadataReport extends AbstractMetadataReport { - - private final static Logger logger = LoggerFactory.getLogger(EtcdMetadataReport.class); - - private final String root; - - /** - * The etcd client - */ - private final JEtcdClient etcdClient; - - public EtcdMetadataReport(URL url) { - super(url); - if (url.isAnyHost()) { - throw new IllegalStateException("registry address == null"); - } - String group = url.getParameter(GROUP_KEY, DEFAULT_ROOT); - if (!group.startsWith(PATH_SEPARATOR)) { - group = PATH_SEPARATOR + group; - } - this.root = group; - etcdClient = new JEtcdClient(url); - } - - @Override - protected void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) { - storeMetadata(providerMetadataIdentifier, serviceDefinitions); - } - - @Override - protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, String value) { - storeMetadata(consumerMetadataIdentifier, value); - } - - @Override - protected void doSaveMetadata(ServiceMetadataIdentifier serviceMetadataIdentifier, URL url) { - String key = getNodeKey(serviceMetadataIdentifier); - if (!etcdClient.put(key, URL.encode(url.toFullString()))) { - logger.error("Failed to put " + serviceMetadataIdentifier + " to etcd, value: " + url); - } - } - - @Override - protected void doRemoveMetadata(ServiceMetadataIdentifier serviceMetadataIdentifier) { - etcdClient.delete(getNodeKey(serviceMetadataIdentifier)); - } - - @Override - protected List doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier) { - String content = etcdClient.getKVValue(getNodeKey(metadataIdentifier)); - if (StringUtils.isEmpty(content)) { - return Collections.emptyList(); - } - return new ArrayList(Arrays.asList(URL.decode(content))); - } - - @Override - protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urlListStr) { - String key = getNodeKey(subscriberMetadataIdentifier); - if (!etcdClient.put(key, urlListStr)) { - logger.error("Failed to put " + subscriberMetadataIdentifier + " to etcd, value: " + urlListStr); - } - } - - @Override - protected String doGetSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) { - return etcdClient.getKVValue(getNodeKey(subscriberMetadataIdentifier)); - } - - @Override - public String getServiceDefinition(MetadataIdentifier metadataIdentifier) { - return etcdClient.getKVValue(getNodeKey(metadataIdentifier)); - } - - private void storeMetadata(MetadataIdentifier identifier, String v) { - String key = getNodeKey(identifier); - if (!etcdClient.put(key, v)) { - logger.error("Failed to put " + identifier + " to etcd, value: " + v); - } - } - - String getNodeKey(BaseMetadataIdentifier identifier) { - return toRootDir() + identifier.getUniqueKey(KeyTypeEnum.PATH); - } - - String toRootDir() { - if (root.equals(PATH_SEPARATOR)) { - return root; - } - return root + PATH_SEPARATOR; - } -} diff --git a/dubbo-metadata/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportFactory.java deleted file mode 100644 index 3bb9e92d3e..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportFactory.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.metadata.store.etcd; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.metadata.report.MetadataReport; -import org.apache.dubbo.metadata.report.support.AbstractMetadataReportFactory; - -/** - * MetadataReportFactory to create an Etcd based {@link MetadataReport}. - */ -public class EtcdMetadataReportFactory extends AbstractMetadataReportFactory { - - @Override - public MetadataReport createMetadataReport(URL url) { - return new EtcdMetadataReport(url); - } - -} diff --git a/dubbo-metadata/dubbo-metadata-report-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory b/dubbo-metadata/dubbo-metadata-report-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory deleted file mode 100644 index 9a3c98c82a..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory +++ /dev/null @@ -1 +0,0 @@ -etcd=org.apache.dubbo.metadata.store.etcd.EtcdMetadataReportFactory diff --git a/dubbo-metadata/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadata4TstService.java b/dubbo-metadata/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadata4TstService.java deleted file mode 100644 index 1de21ce565..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadata4TstService.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.dubbo.metadata.store.etcd; - -/** - * Test interface for Etcd metadata report - */ -public interface EtcdMetadata4TstService { - - int getCounter(); - - void printResult(String var); -} diff --git a/dubbo-metadata/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java b/dubbo-metadata/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java deleted file mode 100644 index 2d2efd5a0e..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.dubbo.metadata.store.etcd; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder; -import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; -import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; -import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier; -import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier; - -import com.google.gson.Gson; -import io.etcd.jetcd.ByteSequence; -import io.etcd.jetcd.Client; -import io.etcd.jetcd.kv.GetResponse; -import io.etcd.jetcd.launcher.EtcdCluster; -import io.etcd.jetcd.launcher.EtcdClusterFactory; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; - -import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; -import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; - -/** - * Unit test for etcd metadata report - */ -public class EtcdMetadataReportTest { - - private static final String TEST_SERVICE = "org.apache.dubbo.metadata.store.etcd.EtcdMetadata4TstService"; - - private EtcdCluster etcdCluster = EtcdClusterFactory.buildCluster(getClass().getSimpleName(), 1, false, false); - private Client etcdClientForTest; - private EtcdMetadataReport etcdMetadataReport; - private URL registryUrl; - private EtcdMetadataReportFactory etcdMetadataReportFactory; - - @BeforeEach - public void setUp() { - etcdCluster.start(); - etcdClientForTest = Client.builder().endpoints(etcdCluster.getClientEndpoints()).build(); - List clientEndPoints = etcdCluster.getClientEndpoints(); - this.registryUrl = URL.valueOf("etcd://" + clientEndPoints.get(0).getHost() + ":" + clientEndPoints.get(0).getPort()); - etcdMetadataReportFactory = new EtcdMetadataReportFactory(); - this.etcdMetadataReport = (EtcdMetadataReport) etcdMetadataReportFactory.createMetadataReport(registryUrl); - } - - @AfterEach - public void tearDown() throws Exception { - etcdCluster.close(); - } - - @Test - public void testStoreProvider() throws Exception { - String version = "1.0.0"; - String group = null; - String application = "etcd-metdata-report-test"; - - String r = etcdMetadataReport.getServiceDefinition(new MetadataIdentifier(TEST_SERVICE, version, group, "provider", application)); - Assertions.assertNull(r); - MetadataIdentifier providerIdentifier = - storeProvider(etcdMetadataReport, TEST_SERVICE, version, group, application); - - CompletableFuture response = etcdClientForTest.getKVClient().get(ByteSequence.from( - etcdMetadataReport.getNodeKey(providerIdentifier), StandardCharsets.UTF_8)); - String fileContent = response.get().getKvs().get(0).getValue().toString(StandardCharsets.UTF_8); - Assertions.assertNotNull(fileContent); - - Gson gson = new Gson(); - FullServiceDefinition fullServiceDefinition = gson.fromJson(fileContent, FullServiceDefinition.class); - Assertions.assertEquals(fullServiceDefinition.getParameters().get("paramTest"), "etcdTest"); - - r = etcdMetadataReport.getServiceDefinition(new MetadataIdentifier(TEST_SERVICE, version, group, "provider", application)); - Assertions.assertNotNull(r); - } - - @Test - public void testStoreConsumer() throws Exception { - String version = "1.0.0"; - String group = null; - String application = "etc-metadata-report-consumer-test"; - MetadataIdentifier consumerIdentifier = storeConsumer(etcdMetadataReport, TEST_SERVICE, version, group, application); - - CompletableFuture response = etcdClientForTest.getKVClient().get(ByteSequence.from( - etcdMetadataReport.getNodeKey(consumerIdentifier), StandardCharsets.UTF_8)); - String fileContent = response.get().getKvs().get(0).getValue().toString(StandardCharsets.UTF_8); - Assertions.assertNotNull(fileContent); - Assertions.assertEquals(fileContent, "{\"paramConsumerTest\":\"etcdConsumer\"}"); - } - - @Test - public void testDoSaveMetadata() throws ExecutionException, InterruptedException { - String version = "1.0.0"; - String group = null; - String application = "etc-metadata-report-consumer-test"; - String revision = "90980"; - String protocol = "xxx"; - URL url = generateURL(TEST_SERVICE, version, group, application); - ServiceMetadataIdentifier serviceMetadataIdentifier = new ServiceMetadataIdentifier(TEST_SERVICE, version, - group, "provider", revision, protocol); - etcdMetadataReport.doSaveMetadata(serviceMetadataIdentifier, url); - - CompletableFuture response = etcdClientForTest.getKVClient().get(ByteSequence.from( - etcdMetadataReport.getNodeKey(serviceMetadataIdentifier), StandardCharsets.UTF_8)); - String fileContent = response.get().getKvs().get(0).getValue().toString(StandardCharsets.UTF_8); - Assertions.assertNotNull(fileContent); - - Assertions.assertEquals(fileContent, URL.encode(url.toFullString())); - } - - @Test - public void testDoRemoveMetadata() throws ExecutionException, InterruptedException { - String version = "1.0.0"; - String group = null; - String application = "etc-metadata-report-consumer-test"; - String revision = "90980"; - String protocol = "xxx"; - URL url = generateURL(TEST_SERVICE, version, group, application); - ServiceMetadataIdentifier serviceMetadataIdentifier = new ServiceMetadataIdentifier(TEST_SERVICE, version, - group, "provider", revision, protocol); - etcdMetadataReport.doSaveMetadata(serviceMetadataIdentifier, url); - CompletableFuture response = etcdClientForTest.getKVClient().get(ByteSequence.from( - etcdMetadataReport.getNodeKey(serviceMetadataIdentifier), StandardCharsets.UTF_8)); - String fileContent = response.get().getKvs().get(0).getValue().toString(StandardCharsets.UTF_8); - Assertions.assertNotNull(fileContent); - - - etcdMetadataReport.doRemoveMetadata(serviceMetadataIdentifier); - - response = etcdClientForTest.getKVClient().get(ByteSequence.from( - etcdMetadataReport.getNodeKey(serviceMetadataIdentifier), StandardCharsets.UTF_8)); - Assertions.assertTrue(response.get().getKvs().isEmpty()); - } - - @Test - public void testDoGetExportedURLs() throws ExecutionException, InterruptedException { - String version = "1.0.0"; - String group = null; - String application = "etc-metadata-report-consumer-test"; - String revision = "90980"; - String protocol = "xxx"; - URL url = generateURL(TEST_SERVICE, version, group, application); - ServiceMetadataIdentifier serviceMetadataIdentifier = new ServiceMetadataIdentifier(TEST_SERVICE, version, - group, "provider", revision, protocol); - etcdMetadataReport.doSaveMetadata(serviceMetadataIdentifier, url); - - List r = etcdMetadataReport.doGetExportedURLs(serviceMetadataIdentifier); - Assertions.assertTrue(r.size() == 1); - - String fileContent = r.get(0); - Assertions.assertNotNull(fileContent); - - Assertions.assertEquals(fileContent, url.toFullString()); - } - - @Test - public void testDoSaveSubscriberData() throws ExecutionException, InterruptedException { - String version = "1.0.0"; - String group = null; - String application = "etc-metadata-report-consumer-test"; - String revision = "90980"; - String protocol = "xxx"; - URL url = generateURL(TEST_SERVICE, version, group, application); - SubscriberMetadataIdentifier subscriberMetadataIdentifier = new SubscriberMetadataIdentifier(application, revision); - Gson gson = new Gson(); - String r = gson.toJson(Arrays.asList(url)); - etcdMetadataReport.doSaveSubscriberData(subscriberMetadataIdentifier, r); - - CompletableFuture response = etcdClientForTest.getKVClient().get(ByteSequence.from( - etcdMetadataReport.getNodeKey(subscriberMetadataIdentifier), StandardCharsets.UTF_8)); - String fileContent = response.get().getKvs().get(0).getValue().toString(StandardCharsets.UTF_8); - Assertions.assertNotNull(fileContent); - - Assertions.assertEquals(fileContent, r); - } - - @Test - public void testDoGetSubscribedURLs() throws ExecutionException, InterruptedException { - String version = "1.0.0"; - String group = null; - String application = "etc-metadata-report-consumer-test"; - String revision = "90980"; - String protocol = "xxx"; - URL url = generateURL(TEST_SERVICE, version, group, application); - SubscriberMetadataIdentifier subscriberMetadataIdentifier = new SubscriberMetadataIdentifier(application, revision); - Gson gson = new Gson(); - String r = gson.toJson(Arrays.asList(url)); - etcdMetadataReport.doSaveSubscriberData(subscriberMetadataIdentifier, r); - - CompletableFuture response = etcdClientForTest.getKVClient().get(ByteSequence.from( - etcdMetadataReport.getNodeKey(subscriberMetadataIdentifier), StandardCharsets.UTF_8)); - String fileContent = etcdMetadataReport.doGetSubscribedURLs(subscriberMetadataIdentifier); - Assertions.assertNotNull(fileContent); - - Assertions.assertEquals(fileContent, r); - } - - private MetadataIdentifier storeProvider(EtcdMetadataReport etcdMetadataReport, String interfaceName, String version, - String group, String application) - throws ClassNotFoundException, InterruptedException { - URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + - "?paramTest=etcdTest&version=" + version + "&application=" - + application + (group == null ? "" : "&group=" + group)); - - MetadataIdentifier providerMetadataIdentifier = - new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application); - Class interfaceClass = Class.forName(interfaceName); - FullServiceDefinition fullServiceDefinition = - ServiceDefinitionBuilder.buildFullDefinition(interfaceClass, url.getParameters()); - - etcdMetadataReport.storeProviderMetadata(providerMetadataIdentifier, fullServiceDefinition); - Thread.sleep(1000); - return providerMetadataIdentifier; - } - - private URL generateURL(String interfaceName, String version, String group, String application) { - URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":8989/" + interfaceName + - "?paramTest=etcdTest&version=" + version + "&application=" - + application + (group == null ? "" : "&group=" + group)); - return url; - } - - private MetadataIdentifier storeConsumer(EtcdMetadataReport etcdMetadataReport, String interfaceName, - String version, String group, String application) throws InterruptedException { - - MetadataIdentifier consumerIdentifier = new MetadataIdentifier(interfaceName, version, group, CONSUMER_SIDE, application); - Map tmp = new HashMap<>(); - tmp.put("paramConsumerTest", "etcdConsumer"); - etcdMetadataReport.storeConsumerMetadata(consumerIdentifier, tmp); - Thread.sleep(1000); - return consumerIdentifier; - } -} diff --git a/dubbo-metadata/dubbo-metadata-report-nacos/pom.xml b/dubbo-metadata/dubbo-metadata-report-nacos/pom.xml deleted file mode 100644 index 03211e02ec..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-nacos/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - org.apache.dubbo - dubbo-metadata - ${revision} - ../pom.xml - - 4.0.0 - - dubbo-metadata-report-nacos - - - - org.apache.dubbo - dubbo-metadata-api - ${project.parent.version} - - - - org.apache.dubbo - dubbo-configcenter-nacos - ${project.parent.version} - - - - diff --git a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java b/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java deleted file mode 100644 index 5c413d8fb0..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.dubbo.metadata.store.nacos; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.metadata.report.identifier.BaseMetadataIdentifier; -import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum; -import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; -import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier; -import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier; -import org.apache.dubbo.metadata.report.support.AbstractMetadataReport; -import org.apache.dubbo.metadata.report.support.ConfigCenterBasedMetadataReport; -import org.apache.dubbo.rpc.RpcException; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static java.util.concurrent.TimeUnit.SECONDS; - -/** - * metadata report impl for nacos - * - * @deprecated 2.7.8 This class will be removed in the future, {@link ConfigCenterBasedMetadataReport} as a substitute. - */ -@Deprecated -public class NacosMetadataReport extends AbstractMetadataReport { - - private static final Logger logger = LoggerFactory.getLogger(NacosMetadataReport.class); - - private final DynamicConfiguration dynamicConfiguration; - - /** - * The group used to store metadata in Nacos - */ - private String group; - - public NacosMetadataReport(URL url, DynamicConfiguration dynamicConfiguration) { - super(url); - this.dynamicConfiguration = dynamicConfiguration; - } - - @Override - protected void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) { - this.storeMetadata(providerMetadataIdentifier, serviceDefinitions); - } - - @Override - protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, String value) { - this.storeMetadata(consumerMetadataIdentifier, value); - } - - @Override - protected void doSaveMetadata(ServiceMetadataIdentifier serviceMetadataIdentifier, URL url) { - storeMetadata(serviceMetadataIdentifier, URL.encode(url.toFullString())); - } - - @Override - protected void doRemoveMetadata(ServiceMetadataIdentifier serviceMetadataIdentifier) { - deleteMetadata(serviceMetadataIdentifier); - } - - @Override - protected List doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier) { - String content = getConfig(metadataIdentifier); - if (StringUtils.isEmpty(content)) { - return Collections.emptyList(); - } - return new ArrayList(Arrays.asList(URL.decode(content))); - } - - @Override - protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urlListStr) { - storeMetadata(subscriberMetadataIdentifier, urlListStr); - } - - @Override - protected String doGetSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) { - return getConfig(subscriberMetadataIdentifier); - } - - @Override - public String getServiceDefinition(MetadataIdentifier metadataIdentifier) { - return getConfig(metadataIdentifier); - } - - @Override - public boolean saveExportedURLs(String serviceName, String exportedServicesRevision, String exportedURLsContent) { - return dynamicConfiguration.publishConfig(serviceName, exportedServicesRevision, exportedURLsContent); - } - - @Override - public String getExportedURLsContent(String serviceName, String exportedServicesRevision) { - return dynamicConfiguration.getConfig(serviceName, exportedServicesRevision, SECONDS.toMillis(3)); - } - - private void storeMetadata(BaseMetadataIdentifier identifier, String value) { - try { - boolean publishResult = dynamicConfiguration.publishConfig(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), group, value); - if (!publishResult) { - throw new RuntimeException("publish nacos metadata failed"); - } - } catch (Throwable t) { - logger.error("Failed to put " + identifier + " to nacos " + value + ", cause: " + t.getMessage(), t); - throw new RpcException("Failed to put " + identifier + " to nacos " + value + ", cause: " + t.getMessage(), t); - } - } - - private void deleteMetadata(BaseMetadataIdentifier identifier) { - try { - boolean publishResult = dynamicConfiguration.removeConfig(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), group); - if (!publishResult) { - throw new RuntimeException("remove nacos metadata failed"); - } - } catch (Throwable t) { - logger.error("Failed to remove " + identifier + " from nacos , cause: " + t.getMessage(), t); - throw new RpcException("Failed to remove " + identifier + " from nacos , cause: " + t.getMessage(), t); - } - } - - private String getConfig(BaseMetadataIdentifier identifier) { - try { - return dynamicConfiguration.getConfig(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), group, 300); - } catch (Throwable t) { - logger.error("Failed to get " + identifier + " from nacos , cause: " + t.getMessage(), t); - throw new RpcException("Failed to get " + identifier + " from nacos , cause: " + t.getMessage(), t); - } - } -} diff --git a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java deleted file mode 100644 index 8c8d5a2efa..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.dubbo.metadata.store.nacos; - -import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum; -import org.apache.dubbo.metadata.report.support.ConfigCenterBasedMetadataReportFactory; - -/** - * metadata report factory impl for nacos - */ -public class NacosMetadataReportFactory extends ConfigCenterBasedMetadataReportFactory { - - public NacosMetadataReportFactory() { - super(KeyTypeEnum.UNIQUE_KEY); - } -} diff --git a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory b/dubbo-metadata/dubbo-metadata-report-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory deleted file mode 100644 index de3b50a4b4..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory +++ /dev/null @@ -1 +0,0 @@ -nacos=org.apache.dubbo.metadata.store.nacos.NacosMetadataReportFactory diff --git a/dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadata4TstService.java b/dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadata4TstService.java deleted file mode 100644 index e84efc529c..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadata4TstService.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.dubbo.metadata.store.nacos; - -/** - * Test interface for Nacos metadata report - */ -public interface NacosMetadata4TstService { - - int getCounter(); - - void printResult(String var); -} diff --git a/dubbo-metadata/dubbo-metadata-report-redis/pom.xml b/dubbo-metadata/dubbo-metadata-report-redis/pom.xml index f42424bea5..70bd32d363 100644 --- a/dubbo-metadata/dubbo-metadata-report-redis/pom.xml +++ b/dubbo-metadata/dubbo-metadata-report-redis/pom.xml @@ -18,8 +18,7 @@ org.apache.dubbo dubbo-metadata - ${revision} - ../pom.xml + 2.7.7-SNAPSHOT 4.0.0 diff --git a/dubbo-metadata/pom.xml b/dubbo-metadata/pom.xml index a11277960b..9119e09488 100644 --- a/dubbo-metadata/pom.xml +++ b/dubbo-metadata/pom.xml @@ -29,13 +29,10 @@ pom dubbo-metadata-api - + dubbo-metadata-definition-protobuf + dubbo-metadata-processor dubbo-metadata-report-zookeeper - - - - - + dubbo-metadata-report-redis diff --git a/dubbo-registry/dubbo-registry-consul/pom.xml b/dubbo-registry/dubbo-registry-consul/pom.xml deleted file mode 100644 index e8f863e0e3..0000000000 --- a/dubbo-registry/dubbo-registry-consul/pom.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - dubbo-registry - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 - - dubbo-registry-consul - - - true - - - - - org.apache.dubbo - dubbo-registry-api - ${project.parent.version} - - - com.ecwid.consul - consul-api - - - com.pszymczyk.consul - embedded-consul - test - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - ${skipIntegrationTests} - - - - - - diff --git a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/AbstractConsulRegistry.java b/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/AbstractConsulRegistry.java deleted file mode 100644 index 8a5e6d7871..0000000000 --- a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/AbstractConsulRegistry.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.registry.consul; - -/** - * @author cvictory ON 2019-08-02 - */ -public class AbstractConsulRegistry { - - static final String SERVICE_TAG = "dubbo"; - static final String URL_META_KEY = "url"; - static final String WATCH_TIMEOUT = "consul-watch-timeout"; - static final String CHECK_PASS_INTERVAL = "consul-check-pass-interval"; - static final String DEREGISTER_AFTER = "consul-deregister-critical-service-after"; - - static final int DEFAULT_PORT = 8500; - // default watch timeout in millisecond - static final int DEFAULT_WATCH_TIMEOUT = 60 * 1000; - // default time-to-live in millisecond - static final long DEFAULT_CHECK_PASS_INTERVAL = 16000L; - // default deregister critical server after - static final String DEFAULT_DEREGISTER_TIME = "20s"; - - -} diff --git a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java b/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java deleted file mode 100644 index 990646ae6c..0000000000 --- a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java +++ /dev/null @@ -1,380 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.dubbo.registry.consul; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.URLBuilder; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.CollectionUtils; -import org.apache.dubbo.common.utils.NamedThreadFactory; -import org.apache.dubbo.common.utils.UrlUtils; -import org.apache.dubbo.registry.NotifyListener; -import org.apache.dubbo.registry.support.FailbackRegistry; -import org.apache.dubbo.rpc.RpcException; - -import com.ecwid.consul.v1.ConsulClient; -import com.ecwid.consul.v1.QueryParams; -import com.ecwid.consul.v1.Response; -import com.ecwid.consul.v1.agent.model.NewService; -import com.ecwid.consul.v1.catalog.CatalogServicesRequest; -import com.ecwid.consul.v1.health.HealthServicesRequest; -import com.ecwid.consul.v1.health.model.HealthService; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -import static java.util.concurrent.Executors.newCachedThreadPool; -import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; -import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; -import static org.apache.dubbo.registry.Constants.CONSUMER_PROTOCOL; -import static org.apache.dubbo.registry.Constants.PROVIDER_PROTOCOL; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.CHECK_PASS_INTERVAL; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.DEFAULT_CHECK_PASS_INTERVAL; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.DEFAULT_DEREGISTER_TIME; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.DEFAULT_PORT; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.DEFAULT_WATCH_TIMEOUT; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.DEREGISTER_AFTER; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.SERVICE_TAG; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.URL_META_KEY; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.WATCH_TIMEOUT; -import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; - -/** - * registry center implementation for consul - */ -public class ConsulRegistry extends FailbackRegistry { - private static final Logger logger = LoggerFactory.getLogger(ConsulRegistry.class); - - private ConsulClient client; - private long checkPassInterval; - private ExecutorService notifierExecutor = newCachedThreadPool( - new NamedThreadFactory("dubbo-consul-notifier", true)); - private ConcurrentMap notifiers = new ConcurrentHashMap<>(); - private ScheduledExecutorService ttlConsulCheckExecutor; - /** - * The ACL token - */ - private String token; - - - public ConsulRegistry(URL url) { - super(url); - token = url.getParameter(TOKEN_KEY, (String) null); - String host = url.getHost(); - int port = url.getPort() != 0 ? url.getPort() : DEFAULT_PORT; - client = new ConsulClient(host, port); - checkPassInterval = url.getParameter(CHECK_PASS_INTERVAL, DEFAULT_CHECK_PASS_INTERVAL); - ttlConsulCheckExecutor = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory("Ttl-Consul-Check-Executor", true)); - ttlConsulCheckExecutor.scheduleAtFixedRate(this::checkPass, checkPassInterval / 8, - checkPassInterval / 8, TimeUnit.MILLISECONDS); - } - - @Override - public void register(URL url) { - if (isConsumerSide(url)) { - return; - } - - super.register(url); - } - - @Override - public void doRegister(URL url) { - if (token == null) { - client.agentServiceRegister(buildService(url)); - } else { - client.agentServiceRegister(buildService(url), token); - } - } - - @Override - public void unregister(URL url) { - if (isConsumerSide(url)) { - return; - } - - super.unregister(url); - } - - @Override - public void doUnregister(URL url) { - if (token == null) { - client.agentServiceDeregister(buildId(url)); - } else { - client.agentServiceDeregister(buildId(url), token); - } - } - - @Override - public void subscribe(URL url, NotifyListener listener) { - if (isProviderSide(url)) { - return; - } - - super.subscribe(url, listener); - } - - @Override - public void doSubscribe(URL url, NotifyListener listener) { - Long index; - List urls; - if (ANY_VALUE.equals(url.getServiceInterface())) { - Response>> response = getAllServices(-1, buildWatchTimeout(url)); - index = response.getConsulIndex(); - List services = getHealthServices(response.getValue()); - urls = convert(services, url); - } else { - String service = url.getServiceInterface(); - Response> response = getHealthServices(service, -1, buildWatchTimeout(url)); - index = response.getConsulIndex(); - urls = convert(response.getValue(), url); - } - - notify(url, listener, urls); - ConsulNotifier notifier = notifiers.computeIfAbsent(url, k -> new ConsulNotifier(url, index)); - notifierExecutor.submit(notifier); - } - - @Override - public void unsubscribe(URL url, NotifyListener listener) { - if (isProviderSide(url)) { - return; - } - - super.unsubscribe(url, listener); - } - - @Override - public void doUnsubscribe(URL url, NotifyListener listener) { - ConsulNotifier notifier = notifiers.remove(url); - notifier.stop(); - } - - @Override - public List lookup(URL url) { - if (url == null) { - throw new IllegalArgumentException("lookup url == null"); - } - try { - String service = url.getServiceKey(); - Response> result = getHealthServices(service, -1, buildWatchTimeout(url)); - if (result == null || result.getValue() == null || result.getValue().isEmpty()) { - return new ArrayList<>(); - } else { - return convert(result.getValue(), url); - } - } catch (Throwable e) { - throw new RpcException("Failed to lookup " + url + " from consul " + getUrl() + ", cause: " + e.getMessage(), e); - } - } - - @Override - public boolean isAvailable() { - return client.getAgentSelf() != null; - } - - @Override - public void destroy() { - super.destroy(); - notifierExecutor.shutdown(); - ttlConsulCheckExecutor.shutdown(); - } - - private void checkPass() { - for (URL url : getRegistered()) { - String checkId = buildId(url); - try { - if (token == null) { - client.agentCheckPass("service:" + checkId); - } else { - client.agentCheckPass("service:" + checkId, null, token); - } - if (logger.isDebugEnabled()) { - logger.debug("check pass for url: " + url + " with check id: " + checkId); - } - } catch (Throwable t) { - logger.warn("fail to check pass for url: " + url + ", check id is: " + checkId, t); - } - } - } - - private Response> getHealthServices(String service, long index, int watchTimeout) { - HealthServicesRequest request = HealthServicesRequest.newBuilder() - .setTag(SERVICE_TAG) - .setQueryParams(new QueryParams(watchTimeout, index)) - .setPassing(true) - .setToken(token) - .build(); - return client.getHealthServices(service, request); - } - - private Response>> getAllServices(long index, int watchTimeout) { - CatalogServicesRequest request = CatalogServicesRequest.newBuilder() - .setQueryParams(new QueryParams(watchTimeout, index)) - .setToken(token) - .build(); - return client.getCatalogServices(request); - } - - private List getHealthServices(Map> services) { - return services.entrySet().stream() - .filter(s -> s.getValue().contains(SERVICE_TAG)) - .map(s -> getHealthServices(s.getKey(), -1, -1).getValue()) - .flatMap(Collection::stream) - .collect(Collectors.toList()); - } - - - private boolean isConsumerSide(URL url) { - return url.getProtocol().equals(CONSUMER_PROTOCOL); - } - - private boolean isProviderSide(URL url) { - return url.getProtocol().equals(PROVIDER_PROTOCOL); - } - - private List convert(List services, URL consumerURL) { - if (CollectionUtils.isEmpty(services)) { - return emptyURL(consumerURL); - } - return services.stream() - .map(HealthService::getService) - .filter(Objects::nonNull) - .map(HealthService.Service::getMeta) - .filter(m -> m != null && m.containsKey(URL_META_KEY)) - .map(m -> m.get(URL_META_KEY)) - .map(URL::valueOf) - .filter(url -> UrlUtils.isMatch(consumerURL, url)) - .collect(Collectors.toList()); - } - - private List emptyURL(URL consumerURL) { - // No Category Parameter - URL empty = URLBuilder.from(consumerURL) - .setProtocol(EMPTY_PROTOCOL) - .removeParameter(CATEGORY_KEY) - .build(); - List result = new ArrayList(); - result.add(empty); - return result; - } - - private NewService buildService(URL url) { - NewService service = new NewService(); - service.setAddress(url.getHost()); - service.setPort(url.getPort()); - service.setId(buildId(url)); - service.setName(url.getServiceInterface()); - service.setCheck(buildCheck(url)); - service.setTags(buildTags(url)); - service.setMeta(Collections.singletonMap(URL_META_KEY, url.toFullString())); - return service; - } - - private List buildTags(URL url) { - Map params = url.getParameters(); - List tags = params.entrySet().stream() - .map(k -> k.getKey() + "=" + k.getValue()) - .collect(Collectors.toList()); - tags.add(SERVICE_TAG); - return tags; - } - - private String buildId(URL url) { - // let's simply use url's hashcode to generate unique service id for now - return Integer.toHexString(url.hashCode()); - } - - private NewService.Check buildCheck(URL url) { - NewService.Check check = new NewService.Check(); - check.setTtl((checkPassInterval / 1000) + "s"); - check.setDeregisterCriticalServiceAfter(url.getParameter(DEREGISTER_AFTER, DEFAULT_DEREGISTER_TIME)); - return check; - } - - private int buildWatchTimeout(URL url) { - return url.getParameter(WATCH_TIMEOUT, DEFAULT_WATCH_TIMEOUT) / 1000; - } - - private class ConsulNotifier implements Runnable { - private URL url; - private long consulIndex; - private boolean running; - - ConsulNotifier(URL url, long consulIndex) { - this.url = url; - this.consulIndex = consulIndex; - this.running = true; - } - - @Override - public void run() { - while (this.running) { - if (ANY_VALUE.equals(url.getServiceInterface())) { - processServices(); - } else { - processService(); - } - } - } - - private void processService() { - String service = url.getServiceKey(); - Response> response = getHealthServices(service, consulIndex, buildWatchTimeout(url)); - Long currentIndex = response.getConsulIndex(); - if (currentIndex != null && currentIndex > consulIndex) { - consulIndex = currentIndex; - List services = response.getValue(); - List urls = convert(services, url); - for (NotifyListener listener : getSubscribed().get(url)) { - doNotify(url, listener, urls); - } - } - } - - private void processServices() { - Response>> response = getAllServices(consulIndex, buildWatchTimeout(url)); - Long currentIndex = response.getConsulIndex(); - if (currentIndex != null && currentIndex > consulIndex) { - consulIndex = currentIndex; - List services = getHealthServices(response.getValue()); - List urls = convert(services, url); - for (NotifyListener listener : getSubscribed().get(url)) { - doNotify(url, listener, urls); - } - } - } - - void stop() { - this.running = false; - } - } -} diff --git a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistryFactory.java b/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistryFactory.java deleted file mode 100644 index c36f009c0d..0000000000 --- a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistryFactory.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.dubbo.registry.consul; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.registry.Registry; -import org.apache.dubbo.registry.support.AbstractRegistryFactory; - -/** - * registry center factory implementation for consul - */ -public class ConsulRegistryFactory extends AbstractRegistryFactory { - @Override - protected Registry createRegistry(URL url) { - return new ConsulRegistry(url); - } -} diff --git a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulServiceDiscovery.java b/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulServiceDiscovery.java deleted file mode 100644 index 0c330aab9a..0000000000 --- a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulServiceDiscovery.java +++ /dev/null @@ -1,474 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.registry.consul; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.CollectionUtils; -import org.apache.dubbo.common.utils.NamedThreadFactory; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.event.EventListener; -import org.apache.dubbo.registry.client.DefaultServiceInstance; -import org.apache.dubbo.registry.client.ServiceDiscovery; -import org.apache.dubbo.registry.client.ServiceInstance; -import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent; -import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; - -import com.ecwid.consul.v1.ConsistencyMode; -import com.ecwid.consul.v1.ConsulClient; -import com.ecwid.consul.v1.QueryParams; -import com.ecwid.consul.v1.Response; -import com.ecwid.consul.v1.agent.model.NewService; -import com.ecwid.consul.v1.catalog.CatalogServicesRequest; -import com.ecwid.consul.v1.health.HealthServicesRequest; -import com.ecwid.consul.v1.health.model.HealthService; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Base64; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -import static java.util.concurrent.Executors.newCachedThreadPool; -import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR_CHAR; -import static org.apache.dubbo.common.constants.CommonConstants.SEMICOLON_SPLIT_PATTERN; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.CHECK_PASS_INTERVAL; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.DEFAULT_CHECK_PASS_INTERVAL; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.DEFAULT_DEREGISTER_TIME; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.DEFAULT_PORT; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.DEFAULT_WATCH_TIMEOUT; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.DEREGISTER_AFTER; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.WATCH_TIMEOUT; -import static org.apache.dubbo.registry.consul.ConsulParameter.ACL_TOKEN; -import static org.apache.dubbo.registry.consul.ConsulParameter.CONSISTENCY_MODE; -import static org.apache.dubbo.registry.consul.ConsulParameter.DEFAULT_ZONE_METADATA_NAME; -import static org.apache.dubbo.registry.consul.ConsulParameter.INSTANCE_GROUP; -import static org.apache.dubbo.registry.consul.ConsulParameter.INSTANCE_ZONE; -import static org.apache.dubbo.registry.consul.ConsulParameter.TAGS; - -/** - * 2019-07-31 - */ -public class ConsulServiceDiscovery implements ServiceDiscovery, EventListener { - - private static final Logger logger = LoggerFactory.getLogger(ConsulServiceDiscovery.class); - - private static final String QUERY_TAG = "consul_query_tag"; - private static final String REGISTER_TAG = "consul_register_tag"; - - private List registeringTags = new ArrayList<>(); - private String tag; - private ConsulClient client; - private ExecutorService notifierExecutor = newCachedThreadPool( - new NamedThreadFactory("dubbo-service-discovery-consul-notifier", true)); - private ConsulNotifier notifier; - private TtlScheduler ttlScheduler; - private long checkPassInterval; - private URL url; - - private String aclToken; - - private List tags; - - private ConsistencyMode consistencyMode; - - private String defaultZoneMetadataName; - - /** - * Service instance zone. - */ - private String instanceZone; - - /** - * Service instance group. - */ - private String instanceGroup; - - - @Override - public void onEvent(ServiceInstancesChangedEvent event) { - - } - - @Override - public void initialize(URL registryURL) throws Exception { - this.url = registryURL; - String host = url.getHost(); - int port = url.getPort() != 0 ? url.getPort() : DEFAULT_PORT; - checkPassInterval = url.getParameter(CHECK_PASS_INTERVAL, DEFAULT_CHECK_PASS_INTERVAL); - client = new ConsulClient(host, port); - ttlScheduler = new TtlScheduler(checkPassInterval, client); - this.tag = registryURL.getParameter(QUERY_TAG); - this.registeringTags.addAll(getRegisteringTags(url)); - this.aclToken = ACL_TOKEN.getValue(registryURL); - this.tags = getTags(registryURL); - this.consistencyMode = getConsistencyMode(registryURL); - this.defaultZoneMetadataName = DEFAULT_ZONE_METADATA_NAME.getValue(registryURL); - this.instanceZone = INSTANCE_ZONE.getValue(registryURL); - this.instanceGroup = INSTANCE_GROUP.getValue(registryURL); - } - - /** - * Get the {@link ConsistencyMode} - * - * @param registryURL the {@link URL} of registry - * @return non-null, {@link ConsistencyMode#DEFAULT} as default - * @sine 2.7.8 - */ - private ConsistencyMode getConsistencyMode(URL registryURL) { - String value = CONSISTENCY_MODE.getValue(registryURL); - if (StringUtils.isNotEmpty(value)) { - return ConsistencyMode.valueOf(value); - } - return ConsistencyMode.DEFAULT; - } - - /** - * Get the "tags" from the {@link URL} of registry - * - * @param registryURL the {@link URL} of registry - * @return non-null - * @sine 2.7.8 - */ - private List getTags(URL registryURL) { - String value = TAGS.getValue(registryURL); - return StringUtils.splitToList(value, COMMA_SEPARATOR_CHAR); - } - - @Override - public URL getUrl() { - return url; - } - - private List getRegisteringTags(URL url) { - List tags = new ArrayList<>(); - String rawTag = url.getParameter(REGISTER_TAG); - if (StringUtils.isNotEmpty(rawTag)) { - tags.addAll(Arrays.asList(SEMICOLON_SPLIT_PATTERN.split(rawTag))); - } - return tags; - } - - @Override - public void destroy() { - if (notifier != null) { - notifier.stop(); - } - notifier = null; - notifierExecutor.shutdownNow(); - ttlScheduler.stop(); - } - - @Override - public void register(ServiceInstance serviceInstance) throws RuntimeException { - NewService consulService = buildService(serviceInstance); - ttlScheduler.add(consulService.getId()); - client.agentServiceRegister(consulService, aclToken); - } - - @Override - public void addServiceInstancesChangedListener(ServiceInstancesChangedListener listener) throws NullPointerException, IllegalArgumentException { - if (notifier == null) { - String serviceName = listener.getServiceNames(); - Response> response = getHealthServices(serviceName, -1, buildWatchTimeout()); - Long consulIndex = response.getConsulIndex(); - notifier = new ConsulNotifier(serviceName, consulIndex); - } - notifierExecutor.execute(notifier); - } - - @Override - public void update(ServiceInstance serviceInstance) throws RuntimeException { - // TODO - // client.catalogRegister(buildCatalogService(serviceInstance)); - } - - @Override - public void unregister(ServiceInstance serviceInstance) throws RuntimeException { - String id = buildId(serviceInstance); - ttlScheduler.remove(id); - client.agentServiceDeregister(id, aclToken); - } - - @Override - public Set getServices() { - CatalogServicesRequest request = CatalogServicesRequest.newBuilder() - .setQueryParams(QueryParams.DEFAULT) - .setToken(aclToken) - .build(); - return this.client.getCatalogServices(request).getValue().keySet(); - } - - @Override - public List getInstances(String serviceName) throws NullPointerException { - Response> response = getHealthServices(serviceName, -1, buildWatchTimeout()); - Long consulIndex = response.getConsulIndex(); - if (notifier == null) { - notifier = new ConsulNotifier(serviceName, consulIndex); - } - return convert(response.getValue()); - } - - private List convert(List services) { - return services.stream() - .map(HealthService::getService) - .map(service -> { - ServiceInstance instance = new DefaultServiceInstance( - service.getId(), - service.getService(), - service.getAddress(), - service.getPort()); - instance.getMetadata().putAll(getMetadata(service)); - return instance; - }) - .collect(Collectors.toList()); - } - - private Response> getHealthServices(String service, long index, int watchTimeout) { - HealthServicesRequest request = HealthServicesRequest.newBuilder() - .setTag(tag) - .setQueryParams(new QueryParams(watchTimeout, index)) - .setPassing(true) - .build(); - return client.getHealthServices(service, request); - } - - private Map getMetadata(HealthService.Service service) { - Map metadata = service.getMeta(); - metadata = decodeMetadata(metadata); - if (CollectionUtils.isEmptyMap(metadata)) { - metadata = getScCompatibleMetadata(service.getTags()); - } - return metadata; - } - - private Map getScCompatibleMetadata(List tags) { - LinkedHashMap metadata = new LinkedHashMap<>(); - if (tags != null) { - for (String tag : tags) { - String[] parts = StringUtils.delimitedListToStringArray(tag, "="); - switch (parts.length) { - case 0: - break; - case 1: - metadata.put(parts[0], parts[0]); - break; - case 2: - metadata.put(parts[0], parts[1]); - break; - default: - String[] end = Arrays.copyOfRange(parts, 1, parts.length); - metadata.put(parts[0], StringUtils.arrayToDelimitedString(end, "=")); - break; - } - - } - } - - return metadata; - } - - private NewService buildService(ServiceInstance serviceInstance) { - NewService service = new NewService(); - service.setAddress(serviceInstance.getHost()); - service.setPort(serviceInstance.getPort()); - service.setId(buildId(serviceInstance)); - service.setName(serviceInstance.getServiceName()); - service.setCheck(buildCheck(serviceInstance)); - service.setTags(buildTags(serviceInstance)); - return service; - } - - private String buildId(ServiceInstance serviceInstance) { - return Integer.toHexString(serviceInstance.hashCode()); - } - - private List buildTags(ServiceInstance serviceInstance) { - List tags = new LinkedList<>(this.tags); - - if (StringUtils.isNotEmpty(instanceZone)) { - tags.add(defaultZoneMetadataName + "=" + instanceZone); - } - - if (StringUtils.isNotEmpty(instanceGroup)) { - tags.add("group=" + instanceGroup); - } - - Map params = serviceInstance.getMetadata(); - params.keySet().stream() - .map(k -> k + "=" + params.get(k)) - .forEach(tags::add); - - tags.addAll(registeringTags); - return tags; - } - - private Map buildMetadata(ServiceInstance serviceInstance) { - Map metadata = new LinkedHashMap<>(); - metadata.putAll(getScCompatibleMetadata(registeringTags)); - if (CollectionUtils.isNotEmptyMap(serviceInstance.getMetadata())) { - metadata.putAll(serviceInstance.getMetadata()); - } - metadata = encodeMetadata(metadata); - return metadata; - } - - private Map encodeMetadata(Map metadata) { - if (metadata == null) { - return metadata; - } - Map encoded = new HashMap<>(metadata.size()); - metadata.forEach((k, v) -> encoded.put(Base64.getEncoder().encodeToString(k.getBytes()), v)); - return encoded; - } - - private Map decodeMetadata(Map metadata) { - if (metadata == null) { - return metadata; - } - Map decoded = new HashMap<>(metadata.size()); - metadata.forEach((k, v) -> decoded.put(new String(Base64.getDecoder().decode(k)), v)); - return decoded; - } - - private NewService.Check buildCheck(ServiceInstance serviceInstance) { - NewService.Check check = new NewService.Check(); - check.setTtl((checkPassInterval / 1000) + "s"); - String deregister = serviceInstance.getMetadata().get(DEREGISTER_AFTER); - check.setDeregisterCriticalServiceAfter(deregister == null ? DEFAULT_DEREGISTER_TIME : deregister); - return check; - } - - private int buildWatchTimeout() { - return url.getParameter(WATCH_TIMEOUT, DEFAULT_WATCH_TIMEOUT) / 1000; - } - - private class ConsulNotifier implements Runnable { - private String serviceName; - private long consulIndex; - private boolean running; - - ConsulNotifier(String serviceName, long consulIndex) { - this.serviceName = serviceName; - this.consulIndex = consulIndex; - this.running = true; - } - - @Override - public void run() { - while (this.running) { - processService(); - } - } - - private void processService() { - Response> response = getHealthServices(serviceName, consulIndex, Integer.MAX_VALUE); - Long currentIndex = response.getConsulIndex(); - if (currentIndex != null && currentIndex > consulIndex) { - consulIndex = currentIndex; - List services = response.getValue(); - List serviceInstances = convert(services); - dispatchServiceInstancesChangedEvent(serviceName, serviceInstances); - } - } - - void stop() { - this.running = false; - } - } - - private static class TtlScheduler { - - private static final Logger logger = LoggerFactory.getLogger(TtlScheduler.class); - - private final Map serviceHeartbeats = new ConcurrentHashMap<>(); - - private ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); - - private long checkInterval; - - private ConsulClient client; - - public TtlScheduler(long checkInterval, ConsulClient client) { - this.checkInterval = checkInterval; - this.client = client; - } - - /** - * Add a service to the checks loop. - * - * @param instanceId instance id - */ - public void add(String instanceId) { - ScheduledFuture task = this.scheduler.scheduleAtFixedRate( - new ConsulHeartbeatTask(instanceId), - checkInterval / 8, - checkInterval / 8, - TimeUnit.MILLISECONDS); - ScheduledFuture previousTask = this.serviceHeartbeats.put(instanceId, task); - if (previousTask != null) { - previousTask.cancel(true); - } - } - - public void remove(String instanceId) { - ScheduledFuture task = this.serviceHeartbeats.get(instanceId); - if (task != null) { - task.cancel(true); - } - this.serviceHeartbeats.remove(instanceId); - } - - private class ConsulHeartbeatTask implements Runnable { - - private String checkId; - - ConsulHeartbeatTask(String serviceId) { - this.checkId = serviceId; - if (!this.checkId.startsWith("service:")) { - this.checkId = "service:" + this.checkId; - } - } - - @Override - public void run() { - TtlScheduler.this.client.agentCheckPass(this.checkId); - if (logger.isDebugEnabled()) { - logger.debug("Sending consul heartbeat for: " + this.checkId); - } - } - - } - - public void stop() { - scheduler.shutdownNow(); - } - - } -} diff --git a/dubbo-registry/dubbo-registry-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory b/dubbo-registry/dubbo-registry-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory deleted file mode 100644 index 7aea18f4d8..0000000000 --- a/dubbo-registry/dubbo-registry-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory +++ /dev/null @@ -1 +0,0 @@ -consul=org.apache.dubbo.registry.consul.ConsulRegistryFactory diff --git a/dubbo-registry/dubbo-registry-consul/src/test/java/org/apache/dubbo/registry/consul/ConsulRegistryTest.java b/dubbo-registry/dubbo-registry-consul/src/test/java/org/apache/dubbo/registry/consul/ConsulRegistryTest.java deleted file mode 100644 index f0a3db923c..0000000000 --- a/dubbo-registry/dubbo-registry-consul/src/test/java/org/apache/dubbo/registry/consul/ConsulRegistryTest.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.registry.consul; - -import com.pszymczyk.consul.ConsulProcess; -import com.pszymczyk.consul.ConsulStarterBuilder; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.status.Status; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.registry.NotifyListener; -import org.apache.dubbo.registry.Registry; -import org.apache.dubbo.registry.status.RegistryStatusChecker; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Mockito.mock; - -public class ConsulRegistryTest { - - private static ConsulProcess consul; - private ConsulRegistry consulRegistry; - private String service = "org.apache.dubbo.test.injvmServie"; - private URL serviceUrl = URL.valueOf("consul://127.0.0.1:" + NetUtils.getAvailablePort() + "/" + service + "?notify=false&methods=test1,test2"); - private URL registryUrl; - private ConsulRegistryFactory consulRegistryFactory; - - @BeforeEach - public void setUp() throws Exception { - this.consul = ConsulStarterBuilder.consulStarter() - .build() - .start(); - this.registryUrl = URL.valueOf("consul://localhost:" + consul.getHttpPort()); - - consulRegistryFactory = new ConsulRegistryFactory(); - this.consulRegistry = (ConsulRegistry) consulRegistryFactory.createRegistry(registryUrl); - } - - @AfterEach - public void tearDown() throws Exception { - consul.close(); - this.consulRegistry.destroy(); - } - - @Test - public void testRegister() { - Set registered; - - for (int i = 0; i < 2; i++) { - consulRegistry.register(serviceUrl); - registered = consulRegistry.getRegistered(); - assertThat(registered.contains(serviceUrl), is(true)); - } - - registered = consulRegistry.getRegistered(); - - assertThat(registered.size(), is(1)); - } - - @Test - public void testSubscribe() { - NotifyListener listener = mock(NotifyListener.class); - consulRegistry.subscribe(serviceUrl, listener); - - Map> subscribed = consulRegistry.getSubscribed(); - assertThat(subscribed.size(), is(1)); - assertThat(subscribed.get(serviceUrl).size(), is(1)); - - consulRegistry.unsubscribe(serviceUrl, listener); - subscribed = consulRegistry.getSubscribed(); - assertThat(subscribed.size(), is(1)); - assertThat(subscribed.get(serviceUrl).size(), is(0)); - } - - @Test - public void testAvailable() { - consulRegistry.register(serviceUrl); - assertThat(consulRegistry.isAvailable(), is(true)); - -// consulRegistry.destroy(); -// assertThat(consulRegistry.isAvailable(), is(false)); - } - - @Test - public void testLookup() throws InterruptedException { - List lookup = consulRegistry.lookup(serviceUrl); - assertThat(lookup.size(), is(0)); - - consulRegistry.register(serviceUrl); - Thread.sleep(5000); - lookup = consulRegistry.lookup(serviceUrl); - assertThat(lookup.size(), is(1)); - } - - @Test - public void testStatusChecker() { - RegistryStatusChecker registryStatusChecker = new RegistryStatusChecker(); - Status status = registryStatusChecker.check(); - assertThat(status.getLevel(), is(Status.Level.UNKNOWN)); - - Registry registry = consulRegistryFactory.getRegistry(registryUrl); - assertThat(registry, not(nullValue())); - - status = registryStatusChecker.check(); - assertThat(status.getLevel(), is(Status.Level.OK)); - - registry.register(serviceUrl); - status = registryStatusChecker.check(); - assertThat(status.getLevel(), is(Status.Level.OK)); - } - -} diff --git a/dubbo-registry/dubbo-registry-consul/src/test/java/org/apache/dubbo/registry/consul/ConsulServiceDiscoveryTest.java b/dubbo-registry/dubbo-registry-consul/src/test/java/org/apache/dubbo/registry/consul/ConsulServiceDiscoveryTest.java deleted file mode 100644 index 9f10d0ab16..0000000000 --- a/dubbo-registry/dubbo-registry-consul/src/test/java/org/apache/dubbo/registry/consul/ConsulServiceDiscoveryTest.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.registry.consul; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.registry.client.DefaultServiceInstance; -import org.apache.dubbo.registry.client.ServiceInstance; - -import com.pszymczyk.consul.ConsulProcess; -import com.pszymczyk.consul.ConsulStarterBuilder; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.List; - -import static java.lang.String.valueOf; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class ConsulServiceDiscoveryTest { - - private URL url; - private ConsulServiceDiscovery consulServiceDiscovery; - private ConsulProcess consul; - private static final String SERVICE_NAME = "A"; - private static final String LOCALHOST = "127.0.0.1"; - - @BeforeEach - public void init() throws Exception { - this.consul = ConsulStarterBuilder.consulStarter() - .build() - .start(); - url = URL.valueOf("consul://localhost:" + consul.getHttpPort()); - consulServiceDiscovery = new ConsulServiceDiscovery(); - consulServiceDiscovery.initialize(url); - } - - @AfterEach - public void close() { - consulServiceDiscovery.destroy(); - consul.close(); - } - - @Test - public void testRegistration() throws InterruptedException { - DefaultServiceInstance serviceInstance = createServiceInstance(SERVICE_NAME, LOCALHOST, NetUtils.getAvailablePort()); - consulServiceDiscovery.register(serviceInstance); - Thread.sleep(5000); - - List serviceInstances = consulServiceDiscovery.getInstances(SERVICE_NAME); - assertEquals(serviceInstances.size(), 1); - assertEquals(serviceInstances.get(0).getId(), Integer.toHexString(serviceInstance.hashCode())); - assertEquals(serviceInstances.get(0).getHost(), serviceInstance.getHost()); - assertEquals(serviceInstances.get(0).getServiceName(), serviceInstance.getServiceName()); - assertEquals(serviceInstances.get(0).getPort(), serviceInstance.getPort()); - - consulServiceDiscovery.unregister(serviceInstance); - Thread.sleep(5000); - serviceInstances = consulServiceDiscovery.getInstances(SERVICE_NAME); - System.out.println(serviceInstances.size()); - assertTrue(serviceInstances.isEmpty()); - } - - private DefaultServiceInstance createServiceInstance(String serviceName, String host, int port) { - return new DefaultServiceInstance(host + ":" + port, serviceName, host, port); - } - - @Test - public void testGetInstances() throws Exception { - String serviceName = "ConsulTest77Service"; - assertTrue(consulServiceDiscovery.getInstances(serviceName).isEmpty()); - int portA = NetUtils.getAvailablePort(); - int portB = NetUtils.getAvailablePort(); - consulServiceDiscovery.register(new DefaultServiceInstance(valueOf(System.nanoTime()), serviceName, "127.0.0.1", portA)); - consulServiceDiscovery.register(new DefaultServiceInstance(valueOf(System.nanoTime()), serviceName, "127.0.0.1", portB)); - Thread.sleep(5000); - Assertions.assertFalse(consulServiceDiscovery.getInstances(serviceName).isEmpty()); - List r = convertToIpPort(consulServiceDiscovery.getInstances(serviceName)); - assertTrue(r.contains("127.0.0.1:" + portA)); - assertTrue(r.contains("127.0.0.1:" + portB)); - } - - private List convertToIpPort(List serviceInstances) { - List result = new ArrayList<>(); - for (ServiceInstance serviceInstance : serviceInstances) { - result.add(serviceInstance.getHost() + ":" + serviceInstance.getPort()); - } - return result; - } -} \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-default/pom.xml b/dubbo-registry/dubbo-registry-default/pom.xml deleted file mode 100644 index b2eeecb1cb..0000000000 --- a/dubbo-registry/dubbo-registry-default/pom.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - - 4.0.0 - - org.apache.dubbo - dubbo-registry - ${revision} - ../pom.xml - - dubbo-registry-default - jar - ${project.artifactId} - The default registry module of dubbo project - - false - - - - org.apache.dubbo - dubbo-registry-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-rpc-injvm - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.parent.version} - test - - - org.apache.commons - commons-lang3 - test - - - \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistry.java b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistry.java deleted file mode 100644 index ef9238ee04..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistry.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.registry.dubbo; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.Version; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.ExecutorUtil; -import org.apache.dubbo.common.utils.NamedThreadFactory; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.registry.NotifyListener; -import org.apache.dubbo.registry.RegistryService; -import org.apache.dubbo.registry.support.FailbackRegistry; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.rpc.Invoker; - -import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.ReentrantLock; - -import static org.apache.dubbo.registry.Constants.REGISTRY_RECONNECT_PERIOD_KEY; - -/** - * DubboRegistry - */ -public class DubboRegistry extends FailbackRegistry { - - private final static Logger logger = LoggerFactory.getLogger(DubboRegistry.class); - - // Reconnecting detection cycle: 3 seconds (unit:millisecond) - private static final int RECONNECT_PERIOD_DEFAULT = 3 * 1000; - - // Scheduled executor service - private final ScheduledExecutorService reconnectTimer = Executors.newScheduledThreadPool(1, new NamedThreadFactory("DubboRegistryReconnectTimer", true)); - - // Reconnection timer, regular check connection is available. If unavailable, unlimited reconnection. - private final ScheduledFuture> reconnectFuture; - - // The lock for client acquisition process, lock the creation process of the client instance to prevent repeated clients - private final ReentrantLock clientLock = new ReentrantLock(); - - private final Invoker registryInvoker; - - private final RegistryService registryService; - - /** - * The time in milliseconds the reconnectTimer will wait - */ - private final int reconnectPeriod; - - public DubboRegistry(Invoker registryInvoker, RegistryService registryService) { - super(registryInvoker.getUrl()); - this.registryInvoker = registryInvoker; - this.registryService = registryService; - // Start reconnection timer - this.reconnectPeriod = registryInvoker.getUrl().getParameter(REGISTRY_RECONNECT_PERIOD_KEY, RECONNECT_PERIOD_DEFAULT); - reconnectFuture = reconnectTimer.scheduleWithFixedDelay(() -> { - // Check and connect to the registry - try { - connect(); - } catch (Throwable t) { // Defensive fault tolerance - logger.error("Unexpected error occur at reconnect, cause: " + t.getMessage(), t); - } - }, reconnectPeriod, reconnectPeriod, TimeUnit.MILLISECONDS); - } - - protected final void connect() { - try { - // Check whether or not it is connected - if (isAvailable()) { - return; - } - if (logger.isInfoEnabled()) { - logger.info("Reconnect to registry " + getUrl()); - } - clientLock.lock(); - try { - // Double check whether or not it is connected - if (isAvailable()) { - return; - } - recover(); - } finally { - clientLock.unlock(); - } - } catch (Throwable t) { // Ignore all the exceptions and wait for the next retry - if (getUrl().getParameter(Constants.CHECK_KEY, true)) { - if (t instanceof RuntimeException) { - throw (RuntimeException) t; - } - throw new RuntimeException(t.getMessage(), t); - } - logger.error("Failed to connect to registry " + getUrl().getAddress() + " from provider/consumer " + NetUtils.getLocalHost() + " use dubbo " + Version.getVersion() + ", cause: " + t.getMessage(), t); - } - } - - @Override - public boolean isAvailable() { - if (registryInvoker == null) { - return false; - } - return registryInvoker.isAvailable(); - } - - @Override - public void destroy() { - super.destroy(); - try { - // Cancel the reconnection timer - ExecutorUtil.cancelScheduledFuture(reconnectFuture); - } catch (Throwable t) { - logger.warn("Failed to cancel reconnect timer", t); - } - registryInvoker.destroy(); - ExecutorUtil.gracefulShutdown(reconnectTimer, reconnectPeriod); - } - - @Override - public void doRegister(URL url) { - registryService.register(url); - } - - @Override - public void doUnregister(URL url) { - registryService.unregister(url); - } - - @Override - public void doSubscribe(URL url, NotifyListener listener) { - registryService.subscribe(url, listener); - } - - @Override - public void doUnsubscribe(URL url, NotifyListener listener) { - registryService.unsubscribe(url, listener); - } - - @Override - public List lookup(URL url) { - return registryService.lookup(url); - } - -} diff --git a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java deleted file mode 100644 index bc669c6609..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.registry.dubbo; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.URLBuilder; -import org.apache.dubbo.common.bytecode.Wrapper; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.registry.Registry; -import org.apache.dubbo.registry.RegistryService; -import org.apache.dubbo.registry.integration.RegistryDirectory; -import org.apache.dubbo.registry.support.AbstractRegistryFactory; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Protocol; -import org.apache.dubbo.rpc.ProxyFactory; -import org.apache.dubbo.rpc.cluster.Cluster; -import org.apache.dubbo.rpc.cluster.RouterChain; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; - -import static org.apache.dubbo.common.constants.CommonConstants.CALLBACK_INSTANCES_LIMIT_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; -import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.LAZY_CONNECT_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; -import static org.apache.dubbo.registry.Constants.CONSUMER_PROTOCOL; -import static org.apache.dubbo.remoting.Constants.CONNECT_TIMEOUT_KEY; -import static org.apache.dubbo.remoting.Constants.RECONNECT_KEY; -import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_STICKY_KEY; -import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY; -import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; - -/** - * DubboRegistryFactory - * - */ -public class DubboRegistryFactory extends AbstractRegistryFactory { - - private Protocol protocol; - private ProxyFactory proxyFactory; - private Cluster cluster; - - private static URL getRegistryURL(URL url) { - return URLBuilder.from(url) - .setPath(RegistryService.class.getName()) - .removeParameter(EXPORT_KEY).removeParameter(REFER_KEY) - .addParameter(INTERFACE_KEY, RegistryService.class.getName()) - .addParameter(CLUSTER_STICKY_KEY, "true") - .addParameter(LAZY_CONNECT_KEY, "true") - .addParameter(RECONNECT_KEY, "false") - .addParameterIfAbsent(TIMEOUT_KEY, "10000") - .addParameterIfAbsent(CALLBACK_INSTANCES_LIMIT_KEY, "10000") - .addParameterIfAbsent(CONNECT_TIMEOUT_KEY, "10000") - .addParameter(METHODS_KEY, StringUtils.join(new HashSet<>(Arrays.asList(Wrapper.getWrapper(RegistryService.class).getDeclaredMethodNames())), ",")) - //.addParameter(Constants.STUB_KEY, RegistryServiceStub.class.getName()) - //.addParameter(Constants.STUB_EVENT_KEY, Boolean.TRUE.toString()) //for event dispatch - //.addParameter(Constants.ON_DISCONNECT_KEY, "disconnect") - .addParameter("subscribe.1.callback", "true") - .addParameter("unsubscribe.1.callback", "false") - .build(); - } - - public void setProtocol(Protocol protocol) { - this.protocol = protocol; - } - - public void setProxyFactory(ProxyFactory proxyFactory) { - this.proxyFactory = proxyFactory; - } - - public void setCluster(Cluster cluster) { - this.cluster = cluster; - } - - @Override - public Registry createRegistry(URL url) { - url = getRegistryURL(url); - List urls = new ArrayList<>(); - urls.add(url.removeParameter(BACKUP_KEY)); - String backup = url.getParameter(BACKUP_KEY); - if (backup != null && backup.length() > 0) { - String[] addresses = COMMA_SPLIT_PATTERN.split(backup); - for (String address : addresses) { - urls.add(url.setAddress(address)); - } - } - RegistryDirectory directory = new RegistryDirectory<>(RegistryService.class, url.addParameter(INTERFACE_KEY, RegistryService.class.getName()).addParameterAndEncoded(REFER_KEY, url.toParameterString())); - Invoker registryInvoker = cluster.join(directory); - RegistryService registryService = proxyFactory.getProxy(registryInvoker); - DubboRegistry registry = new DubboRegistry(registryInvoker, registryService); - directory.setRegistry(registry); - directory.setProtocol(protocol); - directory.setRouterChain(RouterChain.buildChain(url)); - directory.notify(urls); - directory.subscribe(new URL(CONSUMER_PROTOCOL, NetUtils.getLocalHost(), 0, RegistryService.class.getName(), url.getParameters())); - return registry; - } -} diff --git a/dubbo-registry/dubbo-registry-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory b/dubbo-registry/dubbo-registry-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory deleted file mode 100644 index a2c6f12ea0..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory +++ /dev/null @@ -1 +0,0 @@ -dubbo=org.apache.dubbo.registry.dubbo.DubboRegistryFactory \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/AbstractRegistryService.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/AbstractRegistryService.java deleted file mode 100644 index 8b7a32a36b..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/AbstractRegistryService.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.registry.dubbo; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.registry.NotifyListener; -import org.apache.dubbo.registry.RegistryService; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CopyOnWriteArrayList; - -/** - * AbstractRegistryService - * - */ -public abstract class AbstractRegistryService implements RegistryService { - - // Log output - protected final Logger logger = LoggerFactory.getLogger(getClass()); - - // Registered services - // Map> - private final ConcurrentMap> registered = new ConcurrentHashMap>(); - - // Subscribed services - // Map - private final ConcurrentMap> subscribed = new ConcurrentHashMap>(); - - // Notified services - // Map> - private final ConcurrentMap> notified = new ConcurrentHashMap>(); - - // Listeners list for subscribed services - // Map> - private final ConcurrentMap> notifyListeners = new ConcurrentHashMap>(); - - @Override - public void register(URL url) { - if (logger.isInfoEnabled()) { - logger.info("Register service: " + url.getServiceKey() + ",url:" + url); - } - register(url.getServiceKey(), url); - } - - @Override - public void unregister(URL url) { - if (logger.isInfoEnabled()) { - logger.info("Unregister service: " + url.getServiceKey() + ",url:" + url); - } - unregister(url.getServiceKey(), url); - } - - @Override - public void subscribe(URL url, NotifyListener listener) { - if (logger.isInfoEnabled()) { - logger.info("Subscribe service: " + url.getServiceKey() + ",url:" + url); - } - subscribe(url.getServiceKey(), url, listener); - } - - @Override - public void unsubscribe(URL url, NotifyListener listener) { - if (logger.isInfoEnabled()) { - logger.info("Unsubscribe service: " + url.getServiceKey() + ",url:" + url); - } - unsubscribe(url.getServiceKey(), url, listener); - } - - @Override - public List lookup(URL url) { - return getRegistered(url.getServiceKey()); - } - - public void register(String service, URL url) { - if (service == null) { - throw new IllegalArgumentException("service == null"); - } - if (url == null) { - throw new IllegalArgumentException("url == null"); - } - List urls = registered.computeIfAbsent(service, k -> new CopyOnWriteArrayList<>()); - if (!urls.contains(url)) { - urls.add(url); - } - } - - public void unregister(String service, URL url) { - if (service == null) { - throw new IllegalArgumentException("service == null"); - } - if (url == null) { - throw new IllegalArgumentException("url == null"); - } - List urls = registered.get(service); - if (urls != null) { - URL deleteURL = null; - for (URL u : urls) { - if (u.toIdentityString().equals(url.toIdentityString())) { - deleteURL = u; - break; - } - } - if (deleteURL != null) { - urls.remove(deleteURL); - } - } - } - - public void subscribe(String service, URL url, NotifyListener listener) { - if (service == null) { - throw new IllegalArgumentException("service == null"); - } - if (url == null) { - throw new IllegalArgumentException("parameters == null"); - } - if (listener == null) { - throw new IllegalArgumentException("listener == null"); - } - subscribed.put(service, url.getParameters()); - addListener(service, listener); - } - - public void unsubscribe(String service, URL url, NotifyListener listener) { - if (service == null) { - throw new IllegalArgumentException("service == null"); - } - if (url == null) { - throw new IllegalArgumentException("parameters == null"); - } - if (listener == null) { - throw new IllegalArgumentException("listener == null"); - } - subscribed.remove(service); - removeListener(service, listener); - } - - //The listener of the consumer and the provider can be stored together, all based on the service name - private void addListener(final String service, final NotifyListener listener) { - if (listener == null) { - return; - } - List listeners = notifyListeners.computeIfAbsent(service, k -> new CopyOnWriteArrayList<>()); - if (!listeners.contains(listener)) { - listeners.add(listener); - } - } - - private void removeListener(final String service, final NotifyListener listener) { - if (listener == null) { - return; - } - List listeners = notifyListeners.get(service); - if (listeners != null) { - listeners.remove(listener); - } - } - - private void doNotify(String service, List urls) { - notified.put(service, urls); - List listeners = notifyListeners.get(service); - if (listeners != null) { - for (NotifyListener listener : listeners) { - try { - notify(service, urls, listener); - } catch (Throwable t) { - logger.error("Failed to notify registry event, service: " + service + ", urls: " + urls + ", cause: " + t.getMessage(), t); - } - } - } - } - - protected void notify(String service, List urls, NotifyListener listener) { - listener.notify(urls); - } - - protected final void forbid(String service) { - doNotify(service, new ArrayList(0)); - } - - protected final void notify(String service, List urls) { - if (service == null || service.length() == 0 - || urls == null || urls.size() == 0) { - return; - } - doNotify(service, urls); - } - - public Map> getRegistered() { - return Collections.unmodifiableMap(registered); - } - - public List getRegistered(String service) { - return Collections.unmodifiableList(registered.get(service)); - } - - public Map> getSubscribed() { - return Collections.unmodifiableMap(subscribed); - } - - public Map getSubscribed(String service) { - return subscribed.get(service); - } - - public Map> getNotified() { - return Collections.unmodifiableMap(notified); - } - - public List getNotified(String service) { - return Collections.unmodifiableList(notified.get(service)); - } - - public Map> getListeners() { - return Collections.unmodifiableMap(notifyListeners); - } - -} diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DemoService.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DemoService.java deleted file mode 100644 index f47febb970..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DemoService.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.registry.dubbo; - -/** - * TestService - */ - -public interface DemoService { - void sayHello(String name); - - int plus(int a, int b); -} \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DemoServiceImpl.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DemoServiceImpl.java deleted file mode 100644 index 5b928726cd..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DemoServiceImpl.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.registry.dubbo; - -/** - * - */ -public class DemoServiceImpl implements DemoService { - @Override - public void sayHello(String name) { - - } - - @Override - public int plus(int a, int b) { - return 0; - } -} diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DubboRegistryTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DubboRegistryTest.java deleted file mode 100644 index b757d4accf..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DubboRegistryTest.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.registry.dubbo; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.registry.NotifyListener; -import org.apache.dubbo.registry.RegistryService; -import org.apache.dubbo.registry.support.FailbackRegistry; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.mock; - -public class DubboRegistryTest { - - private static final Logger logger = LoggerFactory.getLogger(DubboRegistryTest.class); - - private DubboRegistry dubboRegistry; - - private URL registryURL; - - private URL serviceURL; - - private NotifyListener notifyListener; - - private Invoker invoker; - - private RegistryService registryService; - - @BeforeEach - public void setUp() { - registryURL = new URL(REGISTRY_PROTOCOL, NetUtils.getLocalHost(), NetUtils.getAvailablePort()) - .addParameter(Constants.CHECK_KEY, false) - .setServiceInterface(RegistryService.class.getName()); - serviceURL = new URL(DubboProtocol.NAME, NetUtils.getLocalHost(), NetUtils.getAvailablePort()) - .addParameter(Constants.CHECK_KEY, false) - .setServiceInterface(RegistryService.class.getName()); - - registryService = new MockDubboRegistry(registryURL); - - invoker = mock(Invoker.class); - given(invoker.getUrl()).willReturn(serviceURL); - given(invoker.getInterface()).willReturn(RegistryService.class); - given(invoker.invoke(new RpcInvocation())).willReturn(null); - - dubboRegistry = new DubboRegistry(invoker, registryService); - notifyListener = mock(NotifyListener.class); - } - - @Test - public void testRegister() { - dubboRegistry.register(serviceURL); - assertEquals(1, getRegisteredSize()); - } - - @Test - public void testUnRegister() { - assertEquals(0, getRegisteredSize()); - dubboRegistry.register(serviceURL); - assertEquals(1, getRegisteredSize()); - dubboRegistry.unregister(serviceURL); - assertEquals(0, getRegisteredSize()); - } - - @Test - public void testSubscribe() { - dubboRegistry.register(serviceURL); - assertEquals(1, getRegisteredSize()); - dubboRegistry.subscribe(serviceURL, notifyListener); - assertEquals(1, getSubscribedSize()); - assertEquals(1, getNotifiedListeners()); - } - - @Test - public void testUnsubscribe() { - dubboRegistry.subscribe(serviceURL, notifyListener); - assertEquals(1, getSubscribedSize()); - assertEquals(1, getNotifiedListeners()); - dubboRegistry.unsubscribe(serviceURL, notifyListener); - assertEquals(0, getNotifiedListeners()); - } - - private class MockDubboRegistry extends FailbackRegistry { - - private volatile boolean isAvailable = false; - - public MockDubboRegistry(URL url) { - super(url); - } - - @Override - public void doRegister(URL url) { - logger.info("Begin to register: " + url); - isAvailable = true; - } - - @Override - public void doUnregister(URL url) { - logger.info("Begin to ungister: " + url); - isAvailable = false; - } - - @Override - public void doSubscribe(URL url, NotifyListener listener) { - logger.info("Begin to subscribe: " + url); - } - - @Override - public void doUnsubscribe(URL url, NotifyListener listener) { - logger.info("Begin to unSubscribe: " + url); - } - - @Override - public boolean isAvailable() { - return isAvailable; - } - } - - private int getNotifiedListeners() { - return dubboRegistry.getSubscribed().get(serviceURL).size(); - } - - private int getRegisteredSize() { - return dubboRegistry.getRegistered().size(); - } - - private int getSubscribedSize() { - return dubboRegistry.getSubscribed().size(); - } -} diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/MockChannel.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/MockChannel.java deleted file mode 100644 index e563da616c..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/MockChannel.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.registry.dubbo; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.exchange.ExchangeChannel; -import org.apache.dubbo.remoting.exchange.ExchangeHandler; - -import java.net.InetSocketAddress; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutorService; - -public class MockChannel implements ExchangeChannel { - - public static boolean closed = false; - public static boolean closing = true; - final InetSocketAddress localAddress; - final InetSocketAddress remoteAddress; - - public MockChannel(String localHostname, int localPort, String remoteHostName, int remotePort) { - localAddress = new InetSocketAddress(localHostname, localPort); - remoteAddress = new InetSocketAddress(remoteHostName, remotePort); - closed = false; - } - - @Override - public InetSocketAddress getLocalAddress() { - return localAddress; - } - - @Override - public InetSocketAddress getRemoteAddress() { - return remoteAddress; - } - - @Override - public boolean isConnected() { - return true; - } - - @Override - public void close() { - closed = true; - } - - @Override - public void send(Object message) throws RemotingException { - } - - @Override - public void close(int timeout) { - } - - @Override - public void startClose() { - closing = true; - } - - @Override - public URL getUrl() { - return null; - } - - public CompletableFuture send(Object request, int timeout) throws RemotingException { - return null; - } - - @Override - public ChannelHandler getChannelHandler() { - return null; - } - - public CompletableFuture request(Object request) throws RemotingException { - return null; - } - - public CompletableFuture request(Object request, int timeout) throws RemotingException { - return null; - } - - @Override - public CompletableFuture request(Object request, ExecutorService executor) throws RemotingException { - return null; - } - - @Override - public CompletableFuture request(Object request, int timeout, ExecutorService executor) throws RemotingException { - return null; - } - - public ExchangeHandler getExchangeHandler() { - return null; - } - - @Override - public Object getAttribute(String key) { - return null; - } - - @Override - public void setAttribute(String key, Object value) { - - } - - @Override - public boolean hasAttribute(String key) { - return false; - } - - @Override - public boolean isClosed() { - return false; - } - - @Override - public void removeAttribute(String key) { - - } - - @Override - public void send(Object message, boolean sent) throws RemotingException { - - } - -} diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/MockedClient.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/MockedClient.java deleted file mode 100644 index ad06cd2096..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/MockedClient.java +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.registry.dubbo; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.Channel; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.Codec; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.exchange.ExchangeClient; -import org.apache.dubbo.remoting.exchange.ExchangeHandler; -import org.apache.dubbo.remoting.exchange.support.Replier; - -import java.net.InetSocketAddress; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.TimeoutException; - -/** - * MockedClient - * - */ -public class MockedClient implements ExchangeClient { - - //private String host; - - //private int port; - - private boolean connected; - - private Object received; - - private Object sent; - - private Object invoked; - - private Replier> handler; - - private InetSocketAddress address; - - private boolean closed = false; - - //private ChannelListener listener; - - public MockedClient(String host, int port, boolean connected) { - this(host, port, connected, null); - } - - public MockedClient(String host, int port, boolean connected, Object received) { - this.address = new InetSocketAddress(host, port); - this.connected = connected; - this.received = received; - } - - public void open() { - } - - @Override - public void close() { - this.closed = true; - } - - @Override - public void send(Object msg) throws RemotingException { - this.sent = msg; - } - - public CompletableFuture request(Object msg) throws RemotingException { - return request(msg, null); - } - - public CompletableFuture request(Object msg, int timeout) throws RemotingException { - return this.request(msg, timeout, null); - } - - @Override - public CompletableFuture request(Object msg, ExecutorService executor) throws RemotingException { - return this.request(msg, 0, executor); - } - - @Override - public CompletableFuture request(Object msg, int timeout, ExecutorService executor) throws RemotingException { - this.invoked = msg; - return new CompletableFuture() { - public Object get() throws InterruptedException, ExecutionException { - return received; - } - - public Object get(int timeoutInMillis) throws InterruptedException, ExecutionException, TimeoutException { - return received; - } - - public boolean isDone() { - return true; - } - }; - } - - public void registerHandler(Replier> handler) { - this.handler = handler; - } - - public void unregisterHandler(Replier> handler) { - //this.handler = null; - } - - public void addChannelListener(ChannelHandler listener) { - //this.listener = listener; - } - - public void removeChannelListener(ChannelHandler listener) { - //this.listener = null; - } - - @Override - public boolean isConnected() { - return connected; - } - - /** - * @param connected the connected to set - */ - public void setConnected(boolean connected) { - this.connected = connected; - } - - public Object getSent() { - return sent; - } - - public Replier> getHandler() { - return handler; - } - - public Object getInvoked() { - return invoked; - } - - @Override - public InetSocketAddress getRemoteAddress() { - return address; - } - - public String getName() { - return "mocked"; - } - - @Override - public InetSocketAddress getLocalAddress() { - return null; - } - - public int getTimeout() { - return 0; - } - - public void setTimeout(int timeout) { - } - - @Override - public void close(int timeout) { - close(); - } - - @Override - public void startClose() { - - } - - public boolean isOpen() { - return closed; - } - - public Codec getCodec() { - return null; - } - - public void setCodec(Codec codec) { - } - - public String getHost() { - return null; - } - - public void setHost(String host) { - } - - public int getPort() { - return 0; - } - - public void setPort(int port) { - } - - public int getThreadCount() { - return 0; - } - - public void setThreadCount(int threadCount) { - } - - @Override - public URL getUrl() { - return null; - } - - public Replier> getReceiver() { - return null; - } - - @Override - public ChannelHandler getChannelHandler() { - return null; - } - - public void reset(Map parameters) { - } - - public Channel getChannel() { - return this; - } - - public ExchangeHandler getExchangeHandler() { - return null; - } - - @Override - public void reconnect() throws RemotingException { - } - - @Override - public Object getAttribute(String key) { - return null; - } - - @Override - public void setAttribute(String key, Object value) { - - } - - @Override - public boolean hasAttribute(String key) { - return false; - } - - @Override - public boolean isClosed() { - return closed; - } - - @Override - public void removeAttribute(String key) { - - } - - /** - * @return the received - */ - public Object getReceived() { - return received; - } - - /** - * @param received the received to set - */ - public void setReceived(Object received) { - this.received = received; - } - - @Override - public void send(Object message, boolean sent) throws RemotingException { - } - - @Override - public void reset(URL url) { - } - - @Deprecated - public void reset(org.apache.dubbo.common.Parameters parameters) { - } - -} diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java deleted file mode 100644 index 9cc954e95a..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java +++ /dev/null @@ -1,1143 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.registry.dubbo; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.utils.LogUtil; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.registry.NotifyListener; -import org.apache.dubbo.registry.Registry; -import org.apache.dubbo.registry.RegistryFactory; -import org.apache.dubbo.registry.integration.RegistryDirectory; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Protocol; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.cluster.RouterChain; -import org.apache.dubbo.rpc.cluster.loadbalance.LeastActiveLoadBalance; -import org.apache.dubbo.rpc.cluster.loadbalance.RoundRobinLoadBalance; -import org.apache.dubbo.rpc.cluster.router.script.ScriptRouterFactory; -import org.apache.dubbo.rpc.cluster.support.wrapper.MockClusterInvoker; -import org.apache.dubbo.rpc.model.ApplicationModel; -import org.apache.dubbo.rpc.service.GenericService; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - -import javax.script.ScriptEngineManager; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CountDownLatch; - -import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE; -import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; -import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; -import static org.apache.dubbo.common.constants.CommonConstants.DISABLED_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.LOADBALANCE_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.ROUTE_PROTOCOL; -import static org.apache.dubbo.rpc.Constants.MOCK_KEY; -import static org.apache.dubbo.rpc.cluster.Constants.INVOCATION_NEED_MOCK; -import static org.apache.dubbo.rpc.cluster.Constants.MOCK_PROTOCOL; -import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; -import static org.apache.dubbo.rpc.cluster.Constants.ROUTER_KEY; -import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY; -import static org.apache.dubbo.rpc.cluster.Constants.TYPE_KEY; -import static org.junit.jupiter.api.Assertions.fail; - -@SuppressWarnings({"rawtypes", "unchecked"}) -public class RegistryDirectoryTest { - - private static boolean isScriptUnsupported = new ScriptEngineManager().getEngineByName("javascript") == null; - RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension(); - Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - String service = DemoService.class.getName(); - RpcInvocation invocation = new RpcInvocation(); - URL noMeaningUrl = URL.valueOf("notsupport:/" + service + "?refer=" + URL.encode("interface=" + service)); - URL SERVICEURL = URL.valueOf("dubbo://127.0.0.1:9091/" + service + "?lazy=true&side=consumer&application=mockName"); - URL SERVICEURL2 = URL.valueOf("dubbo://127.0.0.1:9092/" + service + "?lazy=true&side=consumer&application=mockName"); - URL SERVICEURL3 = URL.valueOf("dubbo://127.0.0.1:9093/" + service + "?lazy=true&side=consumer&application=mockName"); - URL SERVICEURL_DUBBO_NOPATH = URL.valueOf("dubbo://127.0.0.1:9092" + "?lazy=true&side=consumer&application=mockName"); - - private Registry registry = Mockito.mock(Registry.class); - - @BeforeEach - public void setUp() { - ApplicationModel.setApplication("RegistryDirectoryTest"); - } - - private RegistryDirectory getRegistryDirectory(URL url) { - RegistryDirectory registryDirectory = new RegistryDirectory(URL.class, url); - registryDirectory.setProtocol(protocol); - registryDirectory.setRegistry(registry); - registryDirectory.setRouterChain(RouterChain.buildChain(url)); - registryDirectory.subscribe(url); - // asert empty - List invokers = registryDirectory.list(invocation); - Assertions.assertEquals(0, invokers.size()); - Assertions.assertFalse(registryDirectory.isAvailable()); - return registryDirectory; - } - - private RegistryDirectory getRegistryDirectory() { - return getRegistryDirectory(noMeaningUrl); - } - - @Test - public void test_Constructor_WithErrorParam() { - try { - new RegistryDirectory(null, null); - fail(); - } catch (IllegalArgumentException e) { - - } - try { - // null url - new RegistryDirectory(null, noMeaningUrl); - fail(); - } catch (IllegalArgumentException e) { - - } - try { - // no servicekey - new RegistryDirectory(RegistryDirectoryTest.class, URL.valueOf("dubbo://10.20.30.40:9090")); - fail(); - } catch (IllegalArgumentException e) { - - } - } - - @Test - public void test_Constructor_CheckStatus() throws Exception { - URL url = URL.valueOf("notsupported://10.20.30.40/" + service + "?a=b").addParameterAndEncoded(REFER_KEY, - "foo=bar"); - RegistryDirectory reg = getRegistryDirectory(url); - Field field = reg.getClass().getDeclaredField("queryMap"); - field.setAccessible(true); - Map queryMap = (Map) field.get(reg); - Assertions.assertEquals("bar", queryMap.get("foo")); - Assertions.assertEquals(url.clearParameters().addParameter("foo", "bar"), reg.getConsumerUrl()); - } - - @Test - public void testNotified_Normal() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - test_Notified2invokers(registryDirectory); - test_Notified1invokers(registryDirectory); - test_Notified3invokers(registryDirectory); - testforbid(registryDirectory); - } - - /** - * Test push only router - */ - @Test - public void testNotified_Normal_withRouters() { - LogUtil.start(); - RegistryDirectory registryDirectory = getRegistryDirectory(); - test_Notified1invokers(registryDirectory); - test_Notified_only_routers(registryDirectory); - Assertions.assertTrue(registryDirectory.isAvailable()); - Assertions.assertTrue(LogUtil.checkNoError(), "notify no invoker urls ,should not error"); - LogUtil.stop(); - test_Notified2invokers(registryDirectory); - - } - - @Test - public void testNotified_WithError() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - List serviceUrls = new ArrayList(); - // ignore error log - URL badurl = URL.valueOf("notsupported://127.0.0.1/" + service); - serviceUrls.add(badurl); - serviceUrls.add(SERVICEURL); - - registryDirectory.notify(serviceUrls); - Assertions.assertTrue(registryDirectory.isAvailable()); - List invokers = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers.size()); - } - - @Test - public void testNotified_WithDuplicateUrls() { - List serviceUrls = new ArrayList(); - // ignore error log - serviceUrls.add(SERVICEURL); - serviceUrls.add(SERVICEURL); - - RegistryDirectory registryDirectory = getRegistryDirectory(); - registryDirectory.notify(serviceUrls); - List invokers = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers.size()); - } - - // forbid - private void testforbid(RegistryDirectory registryDirectory) { - invocation = new RpcInvocation(); - List serviceUrls = new ArrayList(); - serviceUrls.add(new URL(EMPTY_PROTOCOL, ANYHOST_VALUE, 0, service, CATEGORY_KEY, PROVIDERS_CATEGORY)); - registryDirectory.notify(serviceUrls); - Assertions.assertFalse(registryDirectory.isAvailable(), - "invokers size=0 ,then the registry directory is not available"); - try { - registryDirectory.list(invocation); - fail("forbid must throw RpcException"); - } catch (RpcException e) { - Assertions.assertEquals(RpcException.FORBIDDEN_EXCEPTION, e.getCode()); - } - } - - //The test call is independent of the path of the registry url - @Test - public void test_NotifiedDubbo1() { - URL errorPathUrl = URL.valueOf("notsupport:/" + "xxx" + "?refer=" + URL.encode("interface=" + service)); - RegistryDirectory registryDirectory = getRegistryDirectory(errorPathUrl); - List serviceUrls = new ArrayList(); - URL Dubbo1URL = URL.valueOf("dubbo://127.0.0.1:9098?lazy=true"); - serviceUrls.add(Dubbo1URL.addParameter("methods", "getXXX")); - registryDirectory.notify(serviceUrls); - Assertions.assertTrue(registryDirectory.isAvailable()); - - invocation = new RpcInvocation(); - - List> invokers = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers.size()); - - invocation.setMethodName("getXXX"); - invokers = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers.size()); - Assertions.assertEquals(DemoService.class.getName(), invokers.get(0).getUrl().getPath()); - } - - // notify one invoker - private void test_Notified_only_routers(RegistryDirectory registryDirectory) { - List serviceUrls = new ArrayList(); - serviceUrls.add(URL.valueOf("empty://127.0.0.1/?category=routers")); - registryDirectory.notify(serviceUrls); - } - - // notify one invoker - private void test_Notified1invokers(RegistryDirectory registryDirectory) { - - List serviceUrls = new ArrayList(); - serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1").addParameter(APPLICATION_KEY, "mockApplicationName"));// .addParameter("refer.autodestroy", "true") - registryDirectory.notify(serviceUrls); - Assertions.assertTrue(registryDirectory.isAvailable()); - - invocation = new RpcInvocation(); - - List invokers = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers.size()); - - invocation.setMethodName("getXXX"); - invokers = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers.size()); - - invocation.setMethodName("getXXX1"); - invokers = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers.size()); - - invocation.setMethodName("getXXX2"); - invokers = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers.size()); - } - - // 2 invokers=================================== - private void test_Notified2invokers(RegistryDirectory registryDirectory) { - List serviceUrls = new ArrayList(); - serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1")); - serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1,getXXX2")); - serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1,getXXX2")); - - registryDirectory.notify(serviceUrls); - Assertions.assertTrue(registryDirectory.isAvailable()); - - invocation = new RpcInvocation(); - - List invokers = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers.size()); - - invocation.setMethodName("getXXX"); - invokers = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers.size()); - - invocation.setMethodName("getXXX1"); - invokers = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers.size()); - } - - // 3 invoker notifications=================================== - private void test_Notified3invokers(RegistryDirectory registryDirectory) { - List serviceUrls = new ArrayList(); - serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1")); - serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1,getXXX2")); - serviceUrls.add(SERVICEURL3.addParameter("methods", "getXXX1,getXXX2,getXXX3")); - - registryDirectory.notify(serviceUrls); - Assertions.assertTrue(registryDirectory.isAvailable()); - - invocation = new RpcInvocation(); - - List invokers = registryDirectory.list(invocation); - Assertions.assertEquals(3, invokers.size()); - - invocation.setMethodName("getXXX"); - invokers = registryDirectory.list(invocation); - Assertions.assertEquals(3, invokers.size()); - - invocation.setMethodName("getXXX1"); - invokers = registryDirectory.list(invocation); - Assertions.assertEquals(3, invokers.size()); - - invocation.setMethodName("getXXX2"); - invokers = registryDirectory.list(invocation); - Assertions.assertEquals(3, invokers.size()); - - invocation.setMethodName("getXXX3"); - invokers = registryDirectory.list(invocation); - Assertions.assertEquals(3, invokers.size()); - } - - @Test - public void testParametersMerge() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - URL regurl = noMeaningUrl.addParameter("test", "reg").addParameterAndEncoded(REFER_KEY, - "key=query&" + LOADBALANCE_KEY + "=" + LeastActiveLoadBalance.NAME); - RegistryDirectory registryDirectory2 = new RegistryDirectory( - RegistryDirectoryTest.class, - regurl); - registryDirectory2.setProtocol(protocol); - - List serviceUrls = new ArrayList(); - // The parameters of the inspection registry need to be cleared - { - serviceUrls.clear(); - serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1")); - registryDirectory.notify(serviceUrls); - - invocation = new RpcInvocation(); - List invokers = registryDirectory.list(invocation); - - Invoker invoker = (Invoker) invokers.get(0); - URL url = invoker.getUrl(); - Assertions.assertNull(url.getParameter("key")); - } - // The parameters of the provider for the inspection service need merge - { - serviceUrls.clear(); - serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX2").addParameter("key", "provider")); - - registryDirectory.notify(serviceUrls); - invocation = new RpcInvocation(); - List invokers = registryDirectory.list(invocation); - - Invoker invoker = (Invoker) invokers.get(0); - URL url = invoker.getUrl(); - Assertions.assertEquals("provider", url.getParameter("key")); - } - // The parameters of the test service query need to be with the providermerge. - { - serviceUrls.clear(); - serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX3").addParameter("key", "provider")); - registryDirectory2.setRegistry(registry); - registryDirectory2.setRouterChain(RouterChain.buildChain(noMeaningUrl)); - registryDirectory2.subscribe(noMeaningUrl); - registryDirectory2.notify(serviceUrls); - invocation = new RpcInvocation(); - List invokers = registryDirectory2.list(invocation); - - Invoker invoker = (Invoker) invokers.get(0); - URL url = invoker.getUrl(); - Assertions.assertEquals("query", url.getParameter("key")); - } - - { - serviceUrls.clear(); - serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1")); - registryDirectory.notify(serviceUrls); - - invocation = new RpcInvocation(); - List invokers = registryDirectory.list(invocation); - - Invoker invoker = (Invoker) invokers.get(0); - URL url = invoker.getUrl(); - Assertions.assertFalse(url.getParameter(Constants.CHECK_KEY, false)); - } - { - serviceUrls.clear(); - serviceUrls.add(SERVICEURL.addParameter(LOADBALANCE_KEY, RoundRobinLoadBalance.NAME)); - registryDirectory2.notify(serviceUrls); - - invocation = new RpcInvocation(); - invocation.setMethodName("get"); - List invokers = registryDirectory2.list(invocation); - - Invoker invoker = (Invoker) invokers.get(0); - URL url = invoker.getUrl(); - Assertions.assertEquals(LeastActiveLoadBalance.NAME, url.getMethodParameter("get", LOADBALANCE_KEY)); - } - //test geturl - { - Assertions.assertNull(registryDirectory2.getUrl().getParameter("mock")); - serviceUrls.clear(); - serviceUrls.add(SERVICEURL.addParameter(MOCK_KEY, "true")); - registryDirectory2.notify(serviceUrls); - - Assertions.assertEquals("true", registryDirectory2.getConsumerUrl().getParameter("mock")); - } - } - - /** - * When destroying, RegistryDirectory should: 1. be disconnected from Registry 2. destroy all invokers - */ - @Test - public void testDestroy() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - - List serviceUrls = new ArrayList(); - serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1")); - serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1,getXXX2")); - serviceUrls.add(SERVICEURL3.addParameter("methods", "getXXX1,getXXX2,getXXX3")); - - registryDirectory.notify(serviceUrls); - List invokers = registryDirectory.list(invocation); - Assertions.assertTrue(registryDirectory.isAvailable()); - Assertions.assertTrue(invokers.get(0).isAvailable()); - - registryDirectory.destroy(); - Assertions.assertFalse(registryDirectory.isAvailable()); - Assertions.assertFalse(invokers.get(0).isAvailable()); - registryDirectory.destroy(); - - List> cachedInvokers = registryDirectory.getInvokers(); - Map> urlInvokerMap = registryDirectory.getUrlInvokerMap(); - - Assertions.assertNull(cachedInvokers); - Assertions.assertEquals(0, urlInvokerMap.size()); - // List urls = mockRegistry.getSubscribedUrls(); - - RpcInvocation inv = new RpcInvocation(); - try { - registryDirectory.list(inv); - fail(); - } catch (RpcException e) { - Assertions.assertTrue(e.getMessage().contains("already destroyed")); - } - } - - @Test - public void testDestroy_WithDestroyRegistry() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - CountDownLatch latch = new CountDownLatch(1); - registryDirectory.setRegistry(new MockRegistry(latch)); - registryDirectory.subscribe(URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/DemoService?category=providers")); - registryDirectory.destroy(); - Assertions.assertEquals(0, latch.getCount()); - } - - @Test - public void testDestroy_WithDestroyRegistry_WithError() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - registryDirectory.setRegistry(new MockRegistry(true)); - registryDirectory.destroy(); - } - - @Test - public void testDubbo1UrlWithGenericInvocation() { - - RegistryDirectory registryDirectory = getRegistryDirectory(); - - List serviceUrls = new ArrayList(); - URL serviceURL = SERVICEURL_DUBBO_NOPATH.addParameter("methods", "getXXX1,getXXX2,getXXX3"); - serviceUrls.add(serviceURL); - - registryDirectory.notify(serviceUrls); - - // Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException; - invocation = new RpcInvocation($INVOKE, GenericService.class.getName(), new Class[]{String.class, String[].class, Object[].class}, - new Object[]{"getXXX1", "", new Object[]{}}); - - List invokers = registryDirectory.list(invocation); - - Assertions.assertEquals(1, invokers.size()); -// Assertions.assertEquals( -// serviceURL.setPath(service).addParameters("check", "false", "interface", DemoService.class.getName(), REMOTE_APPLICATION_KEY, serviceURL.getParameter(APPLICATION_KEY)) -// , invokers.get(0).getUrl() -// ); - - } - - /** - * When the first arg of a method is String or Enum, Registry server can do parameter-value-based routing. - */ - @Disabled("Parameter routing is not available at present.") - @Test - public void testParmeterRoute() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - List serviceUrls = new ArrayList(); - serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1.napoli")); - serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1.MORGAN,getXXX2")); - serviceUrls.add(SERVICEURL3.addParameter("methods", "getXXX1.morgan,getXXX2,getXXX3")); - - registryDirectory.notify(serviceUrls); - - invocation = new RpcInvocation($INVOKE, GenericService.class.getName(), - new Class[]{String.class, String[].class, Object[].class}, - new Object[]{"getXXX1", new String[]{"Enum"}, new Object[]{Param.MORGAN}}); - - List invokers = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers.size()); - } - - /** - * Empty notify cause forbidden, non-empty notify cancels forbidden state - */ - @Test - public void testEmptyNotifyCauseForbidden() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - List invokers = null; - - List serviceUrls = new ArrayList(); - registryDirectory.notify(serviceUrls); - - RpcInvocation inv = new RpcInvocation(); - try { - invokers = registryDirectory.list(inv); - } catch (RpcException e) { - Assertions.assertEquals(RpcException.FORBIDDEN_EXCEPTION, e.getCode()); - Assertions.assertFalse(registryDirectory.isAvailable()); - } - - serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1")); - serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1,getXXX2")); - serviceUrls.add(SERVICEURL3.addParameter("methods", "getXXX1,getXXX2,getXXX3")); - - registryDirectory.notify(serviceUrls); - inv.setMethodName("getXXX2"); - invokers = registryDirectory.list(inv); - Assertions.assertTrue(registryDirectory.isAvailable()); - Assertions.assertEquals(3, invokers.size()); - } - - /** - * 1. notify twice, the second time notified router rules should completely replace the former one. 2. notify with - * no router url, do nothing to current routers 3. notify with only one router url, with router=clean, clear all - * current routers - */ - @Test - public void testNotifyRouterUrls() { - if (isScriptUnsupported) return; - RegistryDirectory registryDirectory = getRegistryDirectory(); - URL routerurl = URL.valueOf(ROUTE_PROTOCOL + "://127.0.0.1:9096/"); - URL routerurl2 = URL.valueOf(ROUTE_PROTOCOL + "://127.0.0.1:9097/"); - - List serviceUrls = new ArrayList(); - // without ROUTER_KEY, the first router should not be created. - serviceUrls.add(routerurl.addParameter(CATEGORY_KEY, ROUTERS_CATEGORY).addParameter(TYPE_KEY, "javascript").addParameter(ROUTER_KEY, "notsupported").addParameter(RULE_KEY, "function test1(){}")); - serviceUrls.add(routerurl2.addParameter(CATEGORY_KEY, ROUTERS_CATEGORY).addParameter(TYPE_KEY, "javascript").addParameter(ROUTER_KEY, - ScriptRouterFactory.NAME).addParameter(RULE_KEY, - "function test1(){}")); - - // FIXME - /*registryDirectory.notify(serviceUrls); - RouterChain routerChain = registryDirectory.getRouterChain(); - //default invocation selector - Assertions.assertEquals(1 + 1, routers.size()); - Assertions.assertTrue(ScriptRouter.class == routers.get(1).getClass() || ScriptRouter.class == routers.get(0).getClass()); - - registryDirectory.notify(new ArrayList()); - routers = registryDirectory.getRouters(); - Assertions.assertEquals(1 + 1, routers.size()); - Assertions.assertTrue(ScriptRouter.class == routers.get(1).getClass() || ScriptRouter.class == routers.get(0).getClass()); - - serviceUrls.clear(); - serviceUrls.add(routerurl.addParameter(Constants.ROUTER_KEY, Constants.ROUTER_TYPE_CLEAR)); - registryDirectory.notify(serviceUrls); - routers = registryDirectory.getRouters(); - Assertions.assertEquals(0 + 1, routers.size());*/ - } - - /** - * Test whether the override rule have a high priority - * Scene: first push override , then push invoker - */ - @Test - public void testNotifyoverrideUrls_beforeInvoker() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - List overrideUrls = new ArrayList(); - overrideUrls.add(URL.valueOf("override://0.0.0.0?timeout=1&connections=5")); - registryDirectory.notify(overrideUrls); - //The registry is initially pushed to override only, and the dirctory state should be false because there is no invoker. - Assertions.assertFalse(registryDirectory.isAvailable()); - - //After pushing two provider, the directory state is restored to true - List serviceUrls = new ArrayList(); - serviceUrls.add(SERVICEURL.addParameter("timeout", "1000")); - serviceUrls.add(SERVICEURL2.addParameter("timeout", "1000").addParameter("connections", "10")); - - registryDirectory.notify(serviceUrls); - Assertions.assertTrue(registryDirectory.isAvailable()); - - //Start validation of parameter values - - invocation = new RpcInvocation(); - - List> invokers = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers.size()); - - Assertions.assertEquals("1", invokers.get(0).getUrl().getParameter("timeout"), "override rute must be first priority"); - Assertions.assertEquals("5", invokers.get(0).getUrl().getParameter("connections"), "override rute must be first priority"); - } - - /** - * Test whether the override rule have a high priority - * Scene: first push override , then push invoker - */ - @Test - public void testNotifyoverrideUrls_afterInvoker() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - - //After pushing two provider, the directory state is restored to true - List serviceUrls = new ArrayList(); - serviceUrls.add(SERVICEURL.addParameter("timeout", "1000")); - serviceUrls.add(SERVICEURL2.addParameter("timeout", "1000").addParameter("connections", "10")); - - registryDirectory.notify(serviceUrls); - Assertions.assertTrue(registryDirectory.isAvailable()); - - List overrideUrls = new ArrayList(); - overrideUrls.add(URL.valueOf("override://0.0.0.0?timeout=1&connections=5")); - registryDirectory.notify(overrideUrls); - - //Start validation of parameter values - - invocation = new RpcInvocation(); - - List> invokers = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers.size()); - - Assertions.assertEquals("1", invokers.get(0).getUrl().getParameter("timeout"), "override rute must be first priority"); - Assertions.assertEquals("5", invokers.get(0).getUrl().getParameter("connections"), "override rute must be first priority"); - } - - /** - * Test whether the override rule have a high priority - * Scene: push override rules with invoker - */ - @Test - public void testNotifyoverrideUrls_withInvoker() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - - List durls = new ArrayList(); - durls.add(SERVICEURL.addParameter("timeout", "1000")); - durls.add(SERVICEURL2.addParameter("timeout", "1000").addParameter("connections", "10")); - durls.add(URL.valueOf("override://0.0.0.0?timeout=1&connections=5")); - - registryDirectory.notify(durls); - Assertions.assertTrue(registryDirectory.isAvailable()); - - //Start validation of parameter values - - invocation = new RpcInvocation(); - - List> invokers = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers.size()); - - Assertions.assertEquals("1", invokers.get(0).getUrl().getParameter("timeout"), "override rute must be first priority"); - Assertions.assertEquals("5", invokers.get(0).getUrl().getParameter("connections"), "override rute must be first priority"); - } - - /** - * Test whether the override rule have a high priority - * Scene: the rules of the push are the same as the parameters of the provider - * Expectation: no need to be re-referenced - */ - @Test - public void testNotifyoverrideUrls_Nouse() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - invocation = new RpcInvocation(); - - List durls = new ArrayList(); - durls.add(SERVICEURL.addParameter("timeout", "1"));//One is the same, one is different - durls.add(SERVICEURL2.addParameter("timeout", "1").addParameter("connections", "5")); - registryDirectory.notify(durls); - List> invokers = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers.size()); - Map> map = new HashMap<>(); - map.put(invokers.get(0).getUrl().getAddress(), invokers.get(0)); - map.put(invokers.get(1).getUrl().getAddress(), invokers.get(1)); - - durls = new ArrayList(); - durls.add(URL.valueOf("override://0.0.0.0?timeout=1&connections=5")); - registryDirectory.notify(durls); - Assertions.assertTrue(registryDirectory.isAvailable()); - - invokers = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers.size()); - - Map> map2 = new HashMap<>(); - map2.put(invokers.get(0).getUrl().getAddress(), invokers.get(0)); - map2.put(invokers.get(1).getUrl().getAddress(), invokers.get(1)); - - //The parameters are different and must be rereferenced. - Assertions.assertNotSame(map.get(SERVICEURL.getAddress()), map2.get(SERVICEURL.getAddress()), - "object should not same"); - - //The parameters can not be rereferenced - Assertions.assertSame(map.get(SERVICEURL2.getAddress()), map2.get(SERVICEURL2.getAddress()), - "object should not same"); - } - - /** - * Test override rules for a certain provider - */ - @Test - public void testNofityOverrideUrls_Provider() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - invocation = new RpcInvocation(); - - List durls = new ArrayList(); - durls.add(SERVICEURL.setHost("10.20.30.140").addParameter("timeout", "1").addParameter(SIDE_KEY, CONSUMER_SIDE));//One is the same, one is different - durls.add(SERVICEURL2.setHost("10.20.30.141").addParameter("timeout", "2").addParameter(SIDE_KEY, CONSUMER_SIDE)); - registryDirectory.notify(durls); - - durls = new ArrayList(); - durls.add(URL.valueOf("override://0.0.0.0?timeout=3")); - durls.add(URL.valueOf("override://10.20.30.141:9092?timeout=4")); - registryDirectory.notify(durls); - - List> invokers = registryDirectory.list(invocation); - URL aUrl = invokers.get(0).getUrl(); - URL bUrl = invokers.get(1).getUrl(); - Assertions.assertEquals(aUrl.getHost().equals("10.20.30.140") ? "3" : "4", aUrl.getParameter("timeout")); - Assertions.assertEquals(bUrl.getHost().equals("10.20.30.141") ? "4" : "3", bUrl.getParameter("timeout")); - } - - /** - * Test cleanup override rules, and sent remove rules and other override rules - * Whether the test can be restored to the providerUrl when it is pushed - */ - @Test - public void testNofityOverrideUrls_Clean1() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - invocation = new RpcInvocation(); - - List durls = new ArrayList(); - durls.add(SERVICEURL.setHost("10.20.30.140").addParameter("timeout", "1")); - registryDirectory.notify(durls); - - durls = new ArrayList(); - durls.add(URL.valueOf("override://0.0.0.0?timeout=1000")); - registryDirectory.notify(durls); - - durls = new ArrayList(); - durls.add(URL.valueOf("override://0.0.0.0?timeout=3")); - durls.add(URL.valueOf("override://0.0.0.0")); - registryDirectory.notify(durls); - - List> invokers = registryDirectory.list(invocation); - Invoker> aInvoker = invokers.get(0); - //Need to be restored to the original providerUrl - Assertions.assertEquals("3", aInvoker.getUrl().getParameter("timeout")); - } - - /** - * The test clears the override rule and only sends the override cleanup rules - * Whether the test can be restored to the providerUrl when it is pushed - */ - @Test - public void testNofityOverrideUrls_CleanOnly() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - invocation = new RpcInvocation(); - - List durls = new ArrayList(); - durls.add(SERVICEURL.setHost("10.20.30.140").addParameter("timeout", "1")); - registryDirectory.notify(durls); - Assertions.assertNull(registryDirectory.getConsumerUrl().getParameter("mock")); - - //override - durls = new ArrayList(); - durls.add(URL.valueOf("override://0.0.0.0?timeout=1000&mock=fail")); - registryDirectory.notify(durls); - List> invokers = registryDirectory.list(invocation); - Invoker> aInvoker = invokers.get(0); - Assertions.assertEquals("1000", aInvoker.getUrl().getParameter("timeout")); - Assertions.assertEquals("fail", registryDirectory.getConsumerUrl().getParameter("mock")); - - //override clean - durls = new ArrayList(); - durls.add(URL.valueOf("override://0.0.0.0/dubbo.test.api.HelloService")); - registryDirectory.notify(durls); - invokers = registryDirectory.list(invocation); - aInvoker = invokers.get(0); - //Need to be restored to the original providerUrl - Assertions.assertEquals("1", aInvoker.getUrl().getParameter("timeout")); - - Assertions.assertNull(registryDirectory.getConsumerUrl().getParameter("mock")); - } - - /** - * Test the simultaneous push to clear the override and the override for a certain provider - * See if override can take effect - */ - @Test - public void testNofityOverrideUrls_CleanNOverride() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - invocation = new RpcInvocation(); - - List durls = new ArrayList(); - durls.add(SERVICEURL.setHost("10.20.30.140").addParameter("timeout", "1")); - registryDirectory.notify(durls); - - durls = new ArrayList(); - durls.add(URL.valueOf("override://0.0.0.0?timeout=3")); - durls.add(URL.valueOf("override://0.0.0.0")); - durls.add(URL.valueOf("override://10.20.30.140:9091?timeout=4")); - registryDirectory.notify(durls); - - List> invokers = registryDirectory.list(invocation); - Invoker> aInvoker = invokers.get(0); - Assertions.assertEquals("4", aInvoker.getUrl().getParameter("timeout")); - } - - /** - * Test override disables all service providers through enable=false - * Expectation: all service providers can not be disabled through override. - */ - @Test - public void testNofityOverrideUrls_disabled_allProvider() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - invocation = new RpcInvocation(); - - List durls = new ArrayList(); - durls.add(SERVICEURL.setHost("10.20.30.140")); - durls.add(SERVICEURL.setHost("10.20.30.141")); - registryDirectory.notify(durls); - - durls = new ArrayList(); - durls.add(URL.valueOf("override://0.0.0.0?" + ENABLED_KEY + "=false")); - registryDirectory.notify(durls); - - List> invokers = registryDirectory.list(invocation); - //All service providers can not be disabled through override. - Assertions.assertEquals(2, invokers.size()); - } - - /** - * Test override disables a specified service provider through enable=false - * It is expected that a specified service provider can be disable. - */ - @Test - public void testNofityOverrideUrls_disabled_specifiedProvider() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - invocation = new RpcInvocation(); - - List durls = new ArrayList(); - durls.add(SERVICEURL.setHost("10.20.30.140")); - durls.add(SERVICEURL.setHost("10.20.30.141")); - registryDirectory.notify(durls); - - durls = new ArrayList(); - durls.add(URL.valueOf("override://10.20.30.140:9091?" + DISABLED_KEY + "=true")); - registryDirectory.notify(durls); - - List> invokers = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers.size()); - Assertions.assertEquals("10.20.30.141", invokers.get(0).getUrl().getHost()); - - durls = new ArrayList(); - durls.add(URL.valueOf("empty://0.0.0.0?" + DISABLED_KEY + "=true&" + CATEGORY_KEY + "=" + CONFIGURATORS_CATEGORY)); - registryDirectory.notify(durls); - List> invokers2 = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers2.size()); - } - - /** - * Test override disables a specified service provider through enable=false - * It is expected that a specified service provider can be disable. - */ - @Test - public void testNofity_To_Decrease_provider() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - invocation = new RpcInvocation(); - - List durls = new ArrayList(); - durls.add(SERVICEURL.setHost("10.20.30.140")); - durls.add(SERVICEURL.setHost("10.20.30.141")); - registryDirectory.notify(durls); - - List> invokers = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers.size()); - - durls = new ArrayList(); - durls.add(SERVICEURL.setHost("10.20.30.140")); - registryDirectory.notify(durls); - List> invokers2 = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers2.size()); - Assertions.assertEquals("10.20.30.140", invokers2.get(0).getUrl().getHost()); - - durls = new ArrayList(); - durls.add(URL.valueOf("empty://0.0.0.0?" + DISABLED_KEY + "=true&" + CATEGORY_KEY + "=" + CONFIGURATORS_CATEGORY)); - registryDirectory.notify(durls); - List> invokers3 = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers3.size()); - } - - /** - * Test override disables a specified service provider through enable=false - * It is expected that a specified service provider can be disable. - */ - @Test - public void testNofity_disabled_specifiedProvider() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - invocation = new RpcInvocation(); - - // Initially disable - List durls = new ArrayList(); - durls.add(SERVICEURL.setHost("10.20.30.140").addParameter(ENABLED_KEY, "false")); - durls.add(SERVICEURL.setHost("10.20.30.141")); - registryDirectory.notify(durls); - - List> invokers = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers.size()); - Assertions.assertEquals("10.20.30.141", invokers.get(0).getUrl().getHost()); - - //Enabled by override rule - durls = new ArrayList(); - durls.add(URL.valueOf("override://10.20.30.140:9091?" + DISABLED_KEY + "=false")); - registryDirectory.notify(durls); - List> invokers2 = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers2.size()); - } - - @Test - public void testNotifyRouterUrls_Clean() { - if (isScriptUnsupported) return; - RegistryDirectory registryDirectory = getRegistryDirectory(); - URL routerurl = URL.valueOf(ROUTE_PROTOCOL + "://127.0.0.1:9096/").addParameter(ROUTER_KEY, - "javascript").addParameter(RULE_KEY, - "function test1(){}").addParameter(ROUTER_KEY, - "script"); // FIX - // BAD - - List serviceUrls = new ArrayList(); - // without ROUTER_KEY, the first router should not be created. - serviceUrls.add(routerurl); - registryDirectory.notify(serviceUrls); - // FIXME - /* List routers = registryDirectory.getRouters(); - Assertions.assertEquals(1 + 1, routers.size()); - - serviceUrls.clear(); - serviceUrls.add(routerurl.addParameter(Constants.ROUTER_KEY, Constants.ROUTER_TYPE_CLEAR)); - registryDirectory.notify(serviceUrls); - routers = registryDirectory.getRouters(); - Assertions.assertEquals(0 + 1, routers.size());*/ - } - - /** - * Test mock provider distribution - */ - @Test - public void testNotify_MockProviderOnly() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - - List serviceUrls = new ArrayList(); - serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1")); - serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1,getXXX2")); - serviceUrls.add(SERVICEURL.setProtocol(MOCK_PROTOCOL)); - - registryDirectory.notify(serviceUrls); - Assertions.assertTrue(registryDirectory.isAvailable()); - invocation = new RpcInvocation(); - - List invokers = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers.size()); - - RpcInvocation mockinvocation = new RpcInvocation(); - mockinvocation.setAttachment(INVOCATION_NEED_MOCK, "true"); - invokers = registryDirectory.list(mockinvocation); - Assertions.assertEquals(1, invokers.size()); - } - - // mock protocol - - //Test the matching of protocol and select only the matched protocol for refer - @Test - public void test_Notified_acceptProtocol0() { - URL errorPathUrl = URL.valueOf("notsupport:/xxx?refer=" + URL.encode("interface=" + service)); - RegistryDirectory registryDirectory = getRegistryDirectory(errorPathUrl); - List serviceUrls = new ArrayList(); - URL dubbo1URL = URL.valueOf("dubbo://127.0.0.1:9098?lazy=true&methods=getXXX"); - URL dubbo2URL = URL.valueOf("injvm://127.0.0.1:9099?lazy=true&methods=getXXX"); - serviceUrls.add(dubbo1URL); - serviceUrls.add(dubbo2URL); - registryDirectory.notify(serviceUrls); - - invocation = new RpcInvocation(); - - List> invokers = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers.size()); - } - - //Test the matching of protocol and select only the matched protocol for refer - @Test - public void test_Notified_acceptProtocol1() { - URL errorPathUrl = URL.valueOf("notsupport:/xxx"); - errorPathUrl = errorPathUrl.addParameterAndEncoded(REFER_KEY, "interface=" + service + "&protocol=dubbo"); - RegistryDirectory registryDirectory = getRegistryDirectory(errorPathUrl); - List serviceUrls = new ArrayList(); - URL dubbo1URL = URL.valueOf("dubbo://127.0.0.1:9098?lazy=true&methods=getXXX"); - URL dubbo2URL = URL.valueOf("injvm://127.0.0.1:9098?lazy=true&methods=getXXX"); - serviceUrls.add(dubbo1URL); - serviceUrls.add(dubbo2URL); - registryDirectory.notify(serviceUrls); - - invocation = new RpcInvocation(); - - List> invokers = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers.size()); - } - - //Test the matching of protocol and select only the matched protocol for refer - @Test - public void test_Notified_acceptProtocol2() { - URL errorPathUrl = URL.valueOf("notsupport:/xxx"); - errorPathUrl = errorPathUrl.addParameterAndEncoded(REFER_KEY, "interface=" + service + "&protocol=dubbo,injvm"); - RegistryDirectory registryDirectory = getRegistryDirectory(errorPathUrl); - List serviceUrls = new ArrayList(); - URL dubbo1URL = URL.valueOf("dubbo://127.0.0.1:9098?lazy=true&methods=getXXX"); - URL dubbo2URL = URL.valueOf("injvm://127.0.0.1:9099?lazy=true&methods=getXXX"); - serviceUrls.add(dubbo1URL); - serviceUrls.add(dubbo2URL); - registryDirectory.notify(serviceUrls); - - invocation = new RpcInvocation(); - - List> invokers = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers.size()); - } - - @Test - public void test_Notified_withGroupFilter() { - URL directoryUrl = noMeaningUrl.addParameterAndEncoded(REFER_KEY, "interface" + service + "&group=group1,group2"); - RegistryDirectory directory = this.getRegistryDirectory(directoryUrl); - URL provider1 = URL.valueOf("dubbo://10.134.108.1:20880/" + service + "?methods=getXXX&group=group1&mock=false&application=mockApplication"); - URL provider2 = URL.valueOf("dubbo://10.134.108.1:20880/" + service + "?methods=getXXX&group=group2&mock=false&application=mockApplication"); - - List providers = new ArrayList<>(); - providers.add(provider1); - providers.add(provider2); - directory.notify(providers); - - invocation = new RpcInvocation(); - invocation.setMethodName("getXXX"); - List> invokers = directory.list(invocation); - - Assertions.assertEquals(2, invokers.size()); - Assertions.assertTrue(invokers.get(0) instanceof MockClusterInvoker); - Assertions.assertTrue(invokers.get(1) instanceof MockClusterInvoker); - - directoryUrl = noMeaningUrl.addParameterAndEncoded(REFER_KEY, "interface" + service + "&group=group1"); - directory = this.getRegistryDirectory(directoryUrl); - directory.notify(providers); - - invokers = directory.list(invocation); - - Assertions.assertEquals(2, invokers.size()); - Assertions.assertFalse(invokers.get(0) instanceof MockClusterInvoker); - Assertions.assertFalse(invokers.get(1) instanceof MockClusterInvoker); - } - - enum Param { - MORGAN, - } - - private interface DemoService { - } - - private static class MockRegistry implements Registry { - - CountDownLatch latch; - boolean destroyWithError; - - public MockRegistry(CountDownLatch latch) { - this.latch = latch; - } - - public MockRegistry(boolean destroyWithError) { - this.destroyWithError = destroyWithError; - } - - @Override - public void register(URL url) { - - } - - @Override - public void unregister(URL url) { - - } - - @Override - public void subscribe(URL url, NotifyListener listener) { - - } - - @Override - public void unsubscribe(URL url, NotifyListener listener) { - if (latch != null) latch.countDown(); - } - - @Override - public List lookup(URL url) { - return null; - } - - public URL getUrl() { - return null; - } - - @Override - public boolean isAvailable() { - return true; - } - - @Override - public void destroy() { - if (destroyWithError) { - throw new RpcException("test exception ignore."); - } - } - } -} diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java deleted file mode 100644 index 8d08b3dfdb..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.dubbo.registry.dubbo; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.config.ConfigurationUtils; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.registry.NotifyListener; -import org.apache.dubbo.registry.RegistryFactory; -import org.apache.dubbo.registry.RegistryService; -import org.apache.dubbo.registry.integration.RegistryProtocol; -import org.apache.dubbo.registry.support.AbstractRegistry; -import org.apache.dubbo.remoting.exchange.ExchangeClient; -import org.apache.dubbo.rpc.Exporter; -import org.apache.dubbo.rpc.Invocation; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Protocol; -import org.apache.dubbo.rpc.Result; -import org.apache.dubbo.rpc.model.ApplicationModel; -import org.apache.dubbo.rpc.model.ServiceDescriptor; -import org.apache.dubbo.rpc.protocol.AbstractInvoker; -import org.apache.dubbo.rpc.protocol.dubbo.DubboInvoker; -import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; - -import org.apache.commons.lang3.ArrayUtils; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.List; - -import static org.apache.dubbo.registry.integration.RegistryProtocol.DEFAULT_REGISTER_PROVIDER_KEYS; -import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * RegistryProtocolTest - */ -public class RegistryProtocolTest { - - static { - SimpleRegistryExporter.exportIfAbsent(9090); - } - - final String service = DemoService.class.getName() + ":1.0.0"; - final String serviceUrl = "dubbo://127.0.0.1:9453/" + service + "?notify=true&methods=test1,test2&side=con&side=consumer"; - final URL registryUrl = URL.valueOf("registry://127.0.0.1:9090/"); - final private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - - public static RegistryProtocol getRegistryProtocol() { - return RegistryProtocol.getRegistryProtocol(); - } - - @BeforeEach - public void setUp() { - ApplicationModel.setApplication("RegistryProtocolTest"); - ApplicationModel.getServiceRepository().registerService(RegistryService.class); - } - - @Test - public void testDefaultPort() { - RegistryProtocol registryProtocol = getRegistryProtocol(); - assertEquals(9090, registryProtocol.getDefaultPort()); - } - - @Test - public void testExportUrlNull() { - Assertions.assertThrows(IllegalArgumentException.class, () -> { - RegistryProtocol registryProtocol = getRegistryProtocol(); -// registryProtocol.setCluster(new FailfastCluster()); - - Protocol dubboProtocol = DubboProtocol.getDubboProtocol(); - registryProtocol.setProtocol(dubboProtocol); - Invoker invoker = new DubboInvoker(DemoService.class, - registryUrl, new ExchangeClient[]{new MockedClient("10.20.20.20", 2222, true)}); - registryProtocol.export(invoker); - }); - } - - @Test - public void testExport() { - RegistryProtocol registryProtocol = getRegistryProtocol(); -// registryProtocol.setCluster(new FailfastCluster()); - registryProtocol.setRegistryFactory(ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension()); - - Protocol dubboProtocol = DubboProtocol.getDubboProtocol(); - registryProtocol.setProtocol(dubboProtocol); - URL newRegistryUrl = registryUrl.addParameter(EXPORT_KEY, serviceUrl); - DubboInvoker invoker = new DubboInvoker(DemoService.class, - newRegistryUrl, new ExchangeClient[]{new MockedClient("10.20.20.20", 2222, true)}); - Exporter exporter = registryProtocol.export(invoker); - Exporter exporter2 = registryProtocol.export(invoker); - //The same invoker, exporter that multiple exported are different - Assertions.assertNotSame(exporter, exporter2); - exporter.unexport(); - exporter2.unexport(); - - } - -// @Test -// public void testNotifyOverride() throws Exception { -// URL newRegistryUrl = registryUrl.addParameter(EXPORT_KEY, serviceUrl); -// Invoker invoker = new MockInvoker(RegistryProtocolTest.class, newRegistryUrl); -// -// ServiceDescriptor descriptor = ApplicationModel.getServiceRepository().registerService(DemoService.class); -// ApplicationModel.getServiceRepository().registerProvider(service, new DemoServiceImpl(), descriptor, null, null); -// -// Exporter> exporter = protocol.export(invoker); -// RegistryProtocol rprotocol = getRegistryProtocol(); -// NotifyListener listener = getListener(rprotocol); -// List urls = new ArrayList(); -// urls.add(URL.valueOf("override://0.0.0.0/?timeout=1000")); -// urls.add(URL.valueOf("override://0.0.0.0/" + service + "?timeout=100")); -// urls.add(URL.valueOf("override://0.0.0.0/" + service + "?x=y")); -// listener.notify(urls); -// -// assertTrue(exporter.getInvoker().isAvailable()); -// assertEquals("100", exporter.getInvoker().getUrl().getParameter("timeout")); -// assertEquals("y", exporter.getInvoker().getUrl().getParameter("x")); -// -// exporter.unexport(); -//// int timeout = ConfigUtils.getServerShutdownTimeout(); -//// Thread.sleep(timeout + 1000); -//// assertEquals(false, exporter.getInvoker().isAvailable()); -// destroyRegistryProtocol(); -// -// } - - - /** - * The name of the service does not match and can't override invoker - * Service name matching, service version number mismatch - */ - @Test - public void testNotifyOverride_notmatch() throws Exception { - URL newRegistryUrl = registryUrl.addParameter(EXPORT_KEY, serviceUrl); - Invoker
- * e.g. 1)<dubbo:service cache="lru" /> - * 2)<dubbo:service /> <dubbo:method name="method2" cache="threadlocal" /> <dubbo:service/> - * 3)<dubbo:provider cache="expiring" /> - * 4)<dubbo:consumer cache="jcache" /> - * - *If cache type is defined in method level then method level type will get precedence. According to above provided - *example, if service has two method, method1 and method2, method2 will have cache type as threadlocal where others will - *be backed by lru - *
+ * e.g. 1)<dubbo:service cache="lru" /> + * 2)<dubbo:service /> <dubbo:method name="method2" cache="threadlocal" /> <dubbo:service/> + * 3)<dubbo:provider cache="expiring" /> + * 4)<dubbo:consumer cache="jcache" /> + * + *If cache type is defined in method level then method level type will get precedence. According to above provided + *example, if service has two method, method1 and method2, method2 will have cache type as threadlocal where others will + *be backed by lru + *
- * e.g. 1) <dubbo:service cache="lru" cache.size="5000"/> - * 2) <dubbo:consumer cache="lru" /> - *
- * LruCache uses url's cache.size value for its max store size, if nothing is provided then - * default value will be 1000 - *
+ * e.g. 1) <dubbo:service cache="lru" cache.size="5000"/> + * 2) <dubbo:consumer cache="lru" /> + *
+ * LruCache uses url's cache.size value for its max store size, if nothing is provided then + * default value will be 1000 + *
- * e.g. <dubbo:service cache="threadlocal" /> - *
- * As this ThreadLocalCache stores key-value in memory without any expiry or delete support per thread wise, if number threads and number of key-value are high then jvm should be - * configured with appropriate memory. - *
+ * e.g. <dubbo:service cache="threadlocal" /> + *
+ * As this ThreadLocalCache stores key-value in memory without any expiry or delete support per thread wise, if number threads and number of key-value are high then jvm should be + * configured with appropriate memory. + *
- * e.g. <dubbo:method name="save" validation="jvalidation" /> - * In the above configuration a validation has been configured of type jvalidation. On invocation of method save - * dubbo will invoke {@link org.apache.dubbo.validation.support.jvalidation.JValidator} - *
- * e.g. <dubbo:method name="save" validation="special" /> - * where "special" is representing a validator for special character. - *
+ * e.g. <dubbo:method name="save" validation="jvalidation" /> + * In the above configuration a validation has been configured of type jvalidation. On invocation of method save + * dubbo will invoke {@link org.apache.dubbo.validation.support.jvalidation.JValidator} + *
+ * e.g. <dubbo:method name="save" validation="special" /> + * where "special" is representing a validator for special character. + *
- * e.g. <dubbo:method name="save" validation="jvalidation" /> - *
+ * e.g. <dubbo:method name="save" validation="jvalidation" /> + *
TestService