From 9a427801b3c03798de1036f2e3f1646a6c7b7cca Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Mon, 20 May 2019 15:47:15 +0800 Subject: [PATCH 01/46] Polish apache/incubator-dubbo/#4096 : To add new module for Dubbo Event --- dubbo-all/pom.xml | 17 ++ .../dubbo/common/utils/ReflectUtils.java | 66 ++++++++ dubbo-event/pom.xml | 45 +++++ .../dubbo/event/AbstractEventDispatcher.java | 155 ++++++++++++++++++ .../dubbo/event/DirectEventDispatcher.java | 30 ++++ .../java/org/apache/dubbo/event/Event.java | 49 ++++++ .../apache/dubbo/event/EventDispatcher.java | 66 ++++++++ .../org/apache/dubbo/event/EventListener.java | 124 ++++++++++++++ .../org/apache/dubbo/event/GenericEvent.java | 34 ++++ .../org/apache/dubbo/event/Listenable.java | 131 +++++++++++++++ .../dubbo/event/ParallelEventDispatcher.java | 32 ++++ .../org.apache.dubbo.event.EventDispatcher | 2 + .../dubbo/event/AbstractEventListener.java | 40 +++++ .../event/DirectEventDispatcherTest.java | 153 +++++++++++++++++ .../org/apache/dubbo/event/EchoEvent.java | 29 ++++ .../apache/dubbo/event/EchoEventListener.java | 32 ++++ .../dubbo/event/EchoEventListener2.java | 61 +++++++ .../dubbo/event/EventDispatcherTest.java | 45 +++++ .../apache/dubbo/event/EventListenerTest.java | 44 +++++ .../apache/dubbo/event/GenericEventTest.java | 41 +++++ .../event/ParallelEventDispatcherTest.java | 59 +++++++ .../org.apache.dubbo.event.EventListener | 1 + pom.xml | 1 + 23 files changed, 1257 insertions(+) create mode 100644 dubbo-event/pom.xml create mode 100644 dubbo-event/src/main/java/org/apache/dubbo/event/AbstractEventDispatcher.java create mode 100644 dubbo-event/src/main/java/org/apache/dubbo/event/DirectEventDispatcher.java create mode 100644 dubbo-event/src/main/java/org/apache/dubbo/event/Event.java create mode 100644 dubbo-event/src/main/java/org/apache/dubbo/event/EventDispatcher.java create mode 100644 dubbo-event/src/main/java/org/apache/dubbo/event/EventListener.java create mode 100644 dubbo-event/src/main/java/org/apache/dubbo/event/GenericEvent.java create mode 100644 dubbo-event/src/main/java/org/apache/dubbo/event/Listenable.java create mode 100644 dubbo-event/src/main/java/org/apache/dubbo/event/ParallelEventDispatcher.java create mode 100644 dubbo-event/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.event.EventDispatcher create mode 100644 dubbo-event/src/test/java/org/apache/dubbo/event/AbstractEventListener.java create mode 100644 dubbo-event/src/test/java/org/apache/dubbo/event/DirectEventDispatcherTest.java create mode 100644 dubbo-event/src/test/java/org/apache/dubbo/event/EchoEvent.java create mode 100644 dubbo-event/src/test/java/org/apache/dubbo/event/EchoEventListener.java create mode 100644 dubbo-event/src/test/java/org/apache/dubbo/event/EchoEventListener2.java create mode 100644 dubbo-event/src/test/java/org/apache/dubbo/event/EventDispatcherTest.java create mode 100644 dubbo-event/src/test/java/org/apache/dubbo/event/EventListenerTest.java create mode 100644 dubbo-event/src/test/java/org/apache/dubbo/event/GenericEventTest.java create mode 100644 dubbo-event/src/test/java/org/apache/dubbo/event/ParallelEventDispatcherTest.java create mode 100644 dubbo-event/src/test/resources/META-INF/services/org.apache.dubbo.event.EventListener diff --git a/dubbo-all/pom.xml b/dubbo-all/pom.xml index be5a2e3fd77..0ff4568aa12 100644 --- a/dubbo-all/pom.xml +++ b/dubbo-all/pom.xml @@ -500,6 +500,15 @@ true + + + org.apache.dubbo + dubbo-event + ${project.version} + compile + true + + org.springframework @@ -631,6 +640,9 @@ org.apache.dubbo:dubbo-metadata-report-nacos org.apache.dubbo:dubbo-serialization-native-hession org.apache.dubbo:dubbo-rpc-native-thrift + + + org.apache.dubbo:dubbo-event @@ -756,6 +768,11 @@ META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory + + + META-INF/dubbo/internal/org.apache.dubbo.event.EventDispatcher + + diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java index ccec6875ca8..4d1c95e70b8 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java @@ -28,19 +28,28 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; import java.net.URL; import java.security.CodeSource; import java.security.ProtectionDomain; import java.util.ArrayList; +import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashSet; +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.ConcurrentMap; import java.util.regex.Matcher; import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import static java.util.Arrays.asList; +import static java.util.Collections.unmodifiableSet; /** * ReflectUtils @@ -1096,4 +1105,61 @@ public static Map getBeanPropertyReadMethods(Class cl) { return properties; } + + /** + * Find the {@link Set} of {@link ParameterizedType} + * + * @param sourceClass the source {@link Class class} + * @return non-null read-only {@link Set} + * @since 2.7.2 + */ + public static Set findParameterizedTypes(Class sourceClass) { + // Add Generic Interfaces + List genericTypes = new LinkedList<>(asList(sourceClass.getGenericInterfaces())); + // Add Generic Super Class + genericTypes.add(sourceClass.getGenericSuperclass()); + + Set parameterizedTypes = genericTypes.stream() + .filter(type -> type instanceof ParameterizedType)// filter ParameterizedType + .map(type -> ParameterizedType.class.cast(type)) // cast to ParameterizedType + .collect(Collectors.toSet()); + + if (parameterizedTypes.isEmpty()) { // If not found, try to search super types recursively + genericTypes.stream() + .filter(type -> type instanceof Class) + .map(type -> Class.class.cast(type)) + .forEach(superClass -> { + parameterizedTypes.addAll(findParameterizedTypes(superClass)); + }); + } + + return unmodifiableSet(parameterizedTypes); // build as a Set + + } + + /** + * Find the hierarchical types form the source {@link Class class} by specified {@link Class type}. + * + * @param sourceClass the source {@link Class class} + * @param matchType the type to match + * @param the type to match + * @return non-null read-only {@link Set} + * @since 2.7.2 + */ + public static Set> findHierarchicalTypes(Class sourceClass, Class matchType) { + if (sourceClass == null) { + return Collections.emptySet(); + } + + Set> hierarchicalTypes = new LinkedHashSet<>(); + + if (matchType.isAssignableFrom(sourceClass)) { + hierarchicalTypes.add((Class) sourceClass); + } + + // Find all super classes + hierarchicalTypes.addAll(findHierarchicalTypes(sourceClass.getSuperclass(), matchType)); + + return unmodifiableSet(hierarchicalTypes); + } } \ No newline at end of file diff --git a/dubbo-event/pom.xml b/dubbo-event/pom.xml new file mode 100644 index 00000000000..7f30db48794 --- /dev/null +++ b/dubbo-event/pom.xml @@ -0,0 +1,45 @@ + + + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + + 4.0.0 + + dubbo-event + jar + + dubbo-event + The event module of Dubbo project + + + + org.apache.dubbo + dubbo-common + ${revision} + true + + + + + + \ No newline at end of file diff --git a/dubbo-event/src/main/java/org/apache/dubbo/event/AbstractEventDispatcher.java b/dubbo-event/src/main/java/org/apache/dubbo/event/AbstractEventDispatcher.java new file mode 100644 index 00000000000..8989f29a0aa --- /dev/null +++ b/dubbo-event/src/main/java/org/apache/dubbo/event/AbstractEventDispatcher.java @@ -0,0 +1,155 @@ +/* + * 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.event; + +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.ServiceLoader; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.Executor; +import java.util.function.Consumer; + +import static java.util.Collections.sort; +import static java.util.Collections.unmodifiableList; +import static java.util.ServiceLoader.load; +import static org.apache.dubbo.event.EventListener.findEventType; + +/** + * The abstract {@link EventDispatcher} providers the common implementation. + * + * @see EventDispatcher + * @see Listenable + * @see ServiceLoader + * @see EventListener + * @see Event + * @since 2.7.2 + */ +public abstract class AbstractEventDispatcher implements EventDispatcher { + + private final Object mutex = new Object(); + + private final ConcurrentMap, List> listenersCache = new ConcurrentHashMap<>(); + + private final Executor executor; + + /** + * Constructor with an instance of {@link Executor} + * + * @param executor {@link Executor} + * @throws NullPointerException executor is null + */ + protected AbstractEventDispatcher(Executor executor) { + if (executor == null) { + throw new NullPointerException("executor must not be null"); + } + this.executor = executor; + this.loadEventListenerInstances(); + } + + @Override + public void addEventListener(EventListener listener) throws NullPointerException, IllegalArgumentException { + Listenable.assertListener(listener); + doInListener(listener, listeners -> { + addIfAbsent(listeners, listener); + }); + } + + @Override + public void removeEventListener(EventListener listener) throws NullPointerException, IllegalArgumentException { + Listenable.assertListener(listener); + doInListener(listener, listeners -> listeners.remove(listener)); + } + + @Override + public List> getAllEventListeners() { + List> listeners = new LinkedList<>(); + + listenersCache + .entrySet() + .stream() + .map(Map.Entry::getValue) + .flatMap(Collection::stream) + .forEach(listener -> { + addIfAbsent(listeners, listener); + }); + + sort((List) listeners); + + return unmodifiableList(listeners); + } + + private void addIfAbsent(Collection collection, E element) { + if (!collection.contains(element)) { + collection.add(element); + } + } + + @Override + public void dispatch(Event event) { + + Executor executor = getExecutor(); + + // execute in sequential or parallel execution model + executor.execute(() -> { + listenersCache.entrySet() + .stream() + .filter(entry -> entry.getKey().isAssignableFrom(event.getClass())) + .map(Map.Entry::getValue) + .flatMap(Collection::stream) + .forEach(listener -> { + listener.onEvent(event); + }); + }); + } + + /** + * @return the non-null {@link Executor} + */ + @Override + public final Executor getExecutor() { + return executor; + } + + protected void doInListener(EventListener listener, Consumer> consumer) { + Class eventType = findEventType(listener); + if (eventType != null) { + synchronized (mutex) { + List listeners = listenersCache.computeIfAbsent(eventType, e -> new LinkedList<>()); + // consume + consumer.accept(listeners); + // sort + sort(listeners); + } + } + } + + /** + * Default, load the instances of {@link EventListener event listeners} by {@link ServiceLoader} + *

+ * It could be override by the sub-class + * + * @see EventListener + * @see ServiceLoader#load(Class) + */ + protected void loadEventListenerInstances() { + ServiceLoader serviceLoader = load(EventListener.class, getClass().getClassLoader()); + serviceLoader.forEach(this::addEventListener); + } +} diff --git a/dubbo-event/src/main/java/org/apache/dubbo/event/DirectEventDispatcher.java b/dubbo-event/src/main/java/org/apache/dubbo/event/DirectEventDispatcher.java new file mode 100644 index 00000000000..91282b34c6e --- /dev/null +++ b/dubbo-event/src/main/java/org/apache/dubbo/event/DirectEventDispatcher.java @@ -0,0 +1,30 @@ +/* + * 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.event; + +/** + * Direct {@link EventDispatcher} implementation uses current thread execution model + * + * @see EventDispatcher + * @since 2.7.2 + */ +public final class DirectEventDispatcher extends AbstractEventDispatcher { + + public DirectEventDispatcher() { + super(DIRECT_EXECUTOR); + } +} diff --git a/dubbo-event/src/main/java/org/apache/dubbo/event/Event.java b/dubbo-event/src/main/java/org/apache/dubbo/event/Event.java new file mode 100644 index 00000000000..13f2aec16e1 --- /dev/null +++ b/dubbo-event/src/main/java/org/apache/dubbo/event/Event.java @@ -0,0 +1,49 @@ +/* + * 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.event; + +import java.util.EventObject; + +/** + * An event object of Dubbo is based on the Java standard {@link EventObject event} + * + * @since 2.7.2 + */ +public abstract class Event extends EventObject { + + private static final long serialVersionUID = -1704315605423947137L; + + /** + * The timestamp of event occurs + */ + private final long timestamp; + + /** + * Constructs a prototypical Event. + * + * @param source The object on which the Event initially occurred. + * @throws IllegalArgumentException if source is null. + */ + public Event(Object source) { + super(source); + this.timestamp = System.currentTimeMillis(); + } + + public long getTimestamp() { + return timestamp; + } +} diff --git a/dubbo-event/src/main/java/org/apache/dubbo/event/EventDispatcher.java b/dubbo-event/src/main/java/org/apache/dubbo/event/EventDispatcher.java new file mode 100644 index 00000000000..ab3a2e4998b --- /dev/null +++ b/dubbo-event/src/main/java/org/apache/dubbo/event/EventDispatcher.java @@ -0,0 +1,66 @@ +/* + * 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.event; + +import org.apache.dubbo.common.extension.ExtensionLoader; +import org.apache.dubbo.common.extension.SPI; + +import java.util.concurrent.Executor; + +/** + * {@link Event Dubbo Event} Dispatcher + * + * @see Event + * @see EventListener + * @see DirectEventDispatcher + * @since 2.7.2 + */ +@SPI("direct") +public interface EventDispatcher extends Listenable> { + + /** + * Direct {@link Executor} uses sequential execution model + */ + Executor DIRECT_EXECUTOR = Runnable::run; + + /** + * Dispatch a Dubbo event to the registered {@link EventListener Dubbo event listeners} + * + * @param event a {@link Event Dubbo event} + */ + void dispatch(Event event); + + /** + * The {@link Executor} to dispatch a {@link Event Dubbo event} + * + * @return default implementation directly invoke {@link Runnable#run()} method, rather than multiple-threaded + * {@link Executor}. If the return value is null, the behavior is same as default. + * @see #DIRECT_EXECUTOR + */ + default Executor getExecutor() { + return DIRECT_EXECUTOR; + } + + /** + * The default extension of {@link EventDispatcher} is loaded by {@link ExtensionLoader} + * + * @return the default extension of {@link EventDispatcher} + */ + static EventDispatcher getDefaultExtension() { + return ExtensionLoader.getExtensionLoader(EventDispatcher.class).getDefaultExtension(); + } +} diff --git a/dubbo-event/src/main/java/org/apache/dubbo/event/EventListener.java b/dubbo-event/src/main/java/org/apache/dubbo/event/EventListener.java new file mode 100644 index 00000000000..92c35b9c882 --- /dev/null +++ b/dubbo-event/src/main/java/org/apache/dubbo/event/EventListener.java @@ -0,0 +1,124 @@ +/* + * 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.event; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.Objects; + +import static java.lang.Integer.compare; +import static org.apache.dubbo.common.utils.ReflectUtils.findParameterizedTypes; + +/** + * The {@link Event Dubbo Event} Listener that is based on Java standard {@link java.util.EventListener} interface supports + * the generic {@link Event}. + *

+ * The {@link #onEvent(Event) handle method} will be notified when the matched-type {@link Event Dubbo Event} is + * published, whose priority could be changed by {@link #getPriority()} method. + * + * @param the concrete class of {@link Event Dubbo Event} + * @see Event + * @see java.util.EventListener + * @since 2.7.2 + */ +@FunctionalInterface +public interface EventListener extends java.util.EventListener, Comparable> { + + /** + * Handle a {@link Event Dubbo Event} when it's be published + * + * @param event a {@link Event Dubbo Event} + */ + void onEvent(E event); + + /** + * The priority of {@link EventListener current listener}. + * + * @return the value is more greater, the priority is more lower. + * {@link Integer#MIN_VALUE} indicates the highest priority. The default value is {@link Integer#MAX_VALUE}. + * The comparison rule , refer to {@link #compareTo(EventListener)}. + * @see #compareTo(EventListener) + * @see Integer#MAX_VALUE + * @see Integer#MIN_VALUE + */ + default int getPriority() { + return Integer.MAX_VALUE; + } + + @Override + default int compareTo(EventListener another) { + return compare(this.getPriority(), another.getPriority()); + } + + /** + * Find the {@link Class type} {@link Event Dubbo event} from the specified {@link EventListener Dubbo event listener} + * + * @param listener the {@link Class class} of {@link EventListener Dubbo event listener} + * @return null if not found + */ + static Class findEventType(EventListener listener) { + return findEventType(listener.getClass()); + } + + /** + * Find the {@link Class type} {@link Event Dubbo event} from the specified {@link EventListener Dubbo event listener} + * + * @param listenerClass the {@link Class class} of {@link EventListener Dubbo event listener} + * @return null if not found + */ + static Class findEventType(Class listenerClass) { + Class eventType = null; + + if (listenerClass != null && EventListener.class.isAssignableFrom(listenerClass)) { + eventType = findParameterizedTypes(listenerClass) + .stream() + .map(EventListener::findEventType) + .filter(Objects::nonNull) + .findAny() + .orElse((Class) findEventType(listenerClass.getSuperclass())); + } + + return eventType; + } + + /** + * Find the type {@link Event Dubbo event} from the specified {@link ParameterizedType} presents + * a class of {@link EventListener Dubbo event listener} + * + * @param parameterizedType the {@link ParameterizedType} presents a class of {@link EventListener Dubbo event listener} + * @return null if not found + */ + static Class findEventType(ParameterizedType parameterizedType) { + Class eventType = null; + + Type rawType = parameterizedType.getRawType(); + if ((rawType instanceof Class) && EventListener.class.isAssignableFrom((Class) rawType)) { + Type[] typeArguments = parameterizedType.getActualTypeArguments(); + for (Type typeArgument : typeArguments) { + if (typeArgument instanceof Class) { + Class argumentClass = (Class) typeArgument; + if (Event.class.isAssignableFrom(argumentClass)) { + eventType = argumentClass; + break; + } + } + } + } + + return eventType; + } +} \ No newline at end of file diff --git a/dubbo-event/src/main/java/org/apache/dubbo/event/GenericEvent.java b/dubbo-event/src/main/java/org/apache/dubbo/event/GenericEvent.java new file mode 100644 index 00000000000..591bcebb086 --- /dev/null +++ b/dubbo-event/src/main/java/org/apache/dubbo/event/GenericEvent.java @@ -0,0 +1,34 @@ +/* + * 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.event; + +/** + * Generic {@link Event Dubbo event} + * + * @param the type of event source + * @since 2.7.2 + */ +public class GenericEvent extends Event { + + public GenericEvent(S source) { + super(source); + } + + public S getSource() { + return (S) super.getSource(); + } +} diff --git a/dubbo-event/src/main/java/org/apache/dubbo/event/Listenable.java b/dubbo-event/src/main/java/org/apache/dubbo/event/Listenable.java new file mode 100644 index 00000000000..9b854ac2203 --- /dev/null +++ b/dubbo-event/src/main/java/org/apache/dubbo/event/Listenable.java @@ -0,0 +1,131 @@ +/* + * 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.event; + +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static java.util.stream.StreamSupport.stream; + +/** + * Dubbo Event Listenable + * + * @see EventDispatcher + * @since 2.7.2 + */ +public interface Listenable> { + + /** + * Add a {@link EventListener Dubbo event listener} + * + * @param listener a {@link EventListener Dubbo event listener} + * If current {@link EventListener} is existed, return false + * @throws NullPointerException if listener argument is null + * @throws IllegalArgumentException if listener argument is not concrete instance + */ + void addEventListener(E listener) throws NullPointerException, IllegalArgumentException; + + /** + * Add one or more {@link EventListener Dubbo event listeners} + * + * @param listener a {@link EventListener Dubbo event listener} + * @param others an optional {@link EventListener Dubbo event listeners} + * @throws NullPointerException if one of arguments is null + * @throws IllegalArgumentException if one of arguments argument is not concrete instance + */ + default void addEventListeners(E listener, E... others) throws NullPointerException, + IllegalArgumentException { + List listeners = new ArrayList<>(1 + others.length); + listeners.add(listener); + listeners.addAll(Arrays.asList(others)); + addEventListeners(listeners); + } + + /** + * Add multiple {@link EventListener Dubbo event listeners} + * + * @param listeners the {@link EventListener Dubbo event listeners} + * @throws NullPointerException if listeners argument is null + * @throws IllegalArgumentException if any element of listeners is not concrete instance + */ + default void addEventListeners(Iterable listeners) throws NullPointerException, IllegalArgumentException { + stream(listeners.spliterator(), false).forEach(this::addEventListener); + } + + /** + * Remove a a {@link EventListener Dubbo event listener} + * + * @param listener a {@link EventListener Dubbo event listener} + * @return If remove successfully, return true. + * If current {@link EventListener} is existed, return false + * @throws NullPointerException if listener argument is null + */ + void removeEventListener(E listener) throws NullPointerException, IllegalArgumentException; + + /** + * Remove a {@link EventListener Dubbo event listener} + * + * @param listeners the {@link EventListener Dubbo event listeners} + * @return If remove successfully, return true. + * If current {@link EventListener} is existed, return false + * @throws NullPointerException if listener argument is null + * @throws IllegalArgumentException if any element of listeners is not concrete instance + */ + default void removeEventListeners(Iterable listeners) throws NullPointerException, IllegalArgumentException { + stream(listeners.spliterator(), false).forEach(this::removeEventListener); + } + + /** + * Remove all {@link EventListener Dubbo event listeners} + * + * @return a amount of removed listeners + */ + default void removeAllEventListeners() { + removeEventListeners(getAllEventListeners()); + } + + /** + * Get all registered {@link EventListener Dubbo event listeners} + * + * @return non-null read-only ordered {@link EventListener Dubbo event listeners} + * @see EventListener#getPriority() + */ + List getAllEventListeners(); + + + /** + * Assets the listener is valid or not + * + * @param listener the instance of {@link EventListener} + * @throws NullPointerException + */ + static void assertListener(EventListener listener) throws NullPointerException { + if (listener == null) { + throw new NullPointerException("The listener must not be null."); + } + + Class listenerClass = listener.getClass(); + + int modifiers = listenerClass.getModifiers(); + + if (Modifier.isAbstract(modifiers) || Modifier.isInterface(modifiers)) { + throw new IllegalArgumentException("The listener must be concrete class"); + } + } +} diff --git a/dubbo-event/src/main/java/org/apache/dubbo/event/ParallelEventDispatcher.java b/dubbo-event/src/main/java/org/apache/dubbo/event/ParallelEventDispatcher.java new file mode 100644 index 00000000000..f7b0f329763 --- /dev/null +++ b/dubbo-event/src/main/java/org/apache/dubbo/event/ParallelEventDispatcher.java @@ -0,0 +1,32 @@ +/* + * 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.event; + +import java.util.concurrent.ForkJoinPool; + +/** + * Parallel {@link EventDispatcher} implementation uses {@link ForkJoinPool#commonPool() JDK common thread pool} + * + * @see ForkJoinPool#commonPool() + * @since 2.7.2 + */ +public class ParallelEventDispatcher extends AbstractEventDispatcher { + + public ParallelEventDispatcher() { + super(ForkJoinPool.commonPool()); + } +} diff --git a/dubbo-event/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.event.EventDispatcher b/dubbo-event/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.event.EventDispatcher new file mode 100644 index 00000000000..ecd54edb280 --- /dev/null +++ b/dubbo-event/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.event.EventDispatcher @@ -0,0 +1,2 @@ +direct=org.apache.dubbo.event.DirectEventDispatcher +parallel=org.apache.dubbo.event.ParallelEventDispatcher diff --git a/dubbo-event/src/test/java/org/apache/dubbo/event/AbstractEventListener.java b/dubbo-event/src/test/java/org/apache/dubbo/event/AbstractEventListener.java new file mode 100644 index 00000000000..692b3b6d12b --- /dev/null +++ b/dubbo-event/src/test/java/org/apache/dubbo/event/AbstractEventListener.java @@ -0,0 +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.event; + +import java.util.concurrent.atomic.AtomicInteger; + +public abstract class AbstractEventListener implements EventListener { + + private final AtomicInteger eventOccurs = new AtomicInteger(0); + + @Override + public final void onEvent(E event) { + eventOccurs.getAndIncrement(); + handleEvent(event); + } + + protected abstract void handleEvent(E event); + + public int getEventOccurs() { + return eventOccurs.get(); + } + + protected void println(String message) { + System.out.printf("[%s] %s\n", Thread.currentThread().getName(), message); + } +} \ No newline at end of file diff --git a/dubbo-event/src/test/java/org/apache/dubbo/event/DirectEventDispatcherTest.java b/dubbo-event/src/test/java/org/apache/dubbo/event/DirectEventDispatcherTest.java new file mode 100644 index 00000000000..c3cc7323df2 --- /dev/null +++ b/dubbo-event/src/test/java/org/apache/dubbo/event/DirectEventDispatcherTest.java @@ -0,0 +1,153 @@ +/* + * 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.event; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static java.util.Arrays.asList; +import static java.util.Collections.emptyList; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@link DirectEventDispatcher} Test + * + * @since 2.7.2 + */ +public class DirectEventDispatcherTest { + + private DirectEventDispatcher dispatcher; + + private EchoEventListener echoEventListener; + + private EchoEventListener2 echoEventListener2; + + @BeforeEach + public void init() { + dispatcher = new DirectEventDispatcher(); + echoEventListener = new EchoEventListener(); + echoEventListener2 = new EchoEventListener2(); + } + + @AfterEach + public void destroy() { + dispatcher.removeAllEventListeners(); + } + + @Test + public void testGetExecutor() { + assertNotNull(dispatcher.getExecutor()); + } + + @Test + public void testGetAllListeners() { + assertTrue(dispatcher.getAllEventListeners().isEmpty()); + } + + @Test + public void testSingleListener() { + // add two listeners + dispatcher.addEventListener(echoEventListener); + dispatcher.addEventListener(echoEventListener2); + assertEquals(asList(echoEventListener2, echoEventListener), dispatcher.getAllEventListeners()); + + // add a duplicated listener + dispatcher.addEventListener(echoEventListener); + assertEquals(asList(echoEventListener2, echoEventListener), dispatcher.getAllEventListeners()); + + // remove + dispatcher.removeEventListener(echoEventListener); + assertEquals(asList(echoEventListener2), dispatcher.getAllEventListeners()); + + dispatcher.removeEventListener(echoEventListener2); + assertEquals(emptyList(), dispatcher.getAllEventListeners()); + } + + @Test + public void testMultipleListeners() { + + // add two listeners + dispatcher.addEventListeners(echoEventListener, echoEventListener2); + assertEquals(asList(echoEventListener2, echoEventListener), dispatcher.getAllEventListeners()); + + // remove all listeners + dispatcher.removeAllEventListeners(); + assertEquals(emptyList(), dispatcher.getAllEventListeners()); + + // add the duplicated listeners + dispatcher.addEventListeners(echoEventListener, echoEventListener, echoEventListener2); + assertEquals(asList(echoEventListener2, echoEventListener), dispatcher.getAllEventListeners()); + + // remove all listeners + dispatcher.removeAllEventListeners(); + assertEquals(emptyList(), dispatcher.getAllEventListeners()); + + dispatcher.addEventListeners(asList(echoEventListener, echoEventListener, echoEventListener2)); + assertEquals(asList(echoEventListener2, echoEventListener), dispatcher.getAllEventListeners()); + + dispatcher.removeEventListeners(asList(echoEventListener, echoEventListener, echoEventListener2)); + assertEquals(emptyList(), dispatcher.getAllEventListeners()); + } + + @Test + public void testDispatchEvent() { + + dispatcher.addEventListener(echoEventListener); + + // dispatch a Event + dispatcher.dispatch(new Event("Test") { + }); + + // no-op occurs + assertEquals(0, echoEventListener.getEventOccurs()); + + // dispatch a EchoEvent + dispatcher.dispatch(new EchoEvent("Hello,World")); + + // event has been handled + assertEquals(1, echoEventListener.getEventOccurs()); + + dispatcher.addEventListener(echoEventListener2); + + // reset the listeners + init(); + dispatcher.addEventListeners(echoEventListener, echoEventListener2); + + // dispatch a Event + dispatcher.dispatch(new Event("Test") { + }); + + // echoEventListener will be not triggered + 0 + // echoEventListener2 will be triggered + 1 + assertEquals(0, echoEventListener.getEventOccurs()); + assertEquals(1, echoEventListener2.getEventOccurs()); + + // dispatch a EchoEvent + // echoEventListener and echoEventListener2 are triggered both (+1) + dispatcher.dispatch(new EchoEvent("Hello,World")); + assertEquals(1, echoEventListener.getEventOccurs()); + assertEquals(2, echoEventListener2.getEventOccurs()); + + // both +1 + dispatcher.dispatch(new EchoEvent("2019")); + assertEquals(2, echoEventListener.getEventOccurs()); + assertEquals(3, echoEventListener2.getEventOccurs()); + } +} diff --git a/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEvent.java b/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEvent.java new file mode 100644 index 00000000000..785d411f256 --- /dev/null +++ b/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEvent.java @@ -0,0 +1,29 @@ +/* + * 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.event; + +/** + * Echo {@link Event} + * + * @since 2.7.2 + */ +class EchoEvent extends Event { + + public EchoEvent(Object source) { + super(source); + } +} diff --git a/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEventListener.java b/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEventListener.java new file mode 100644 index 00000000000..f88b9df3318 --- /dev/null +++ b/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEventListener.java @@ -0,0 +1,32 @@ +/* + * 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.event; + +import java.io.Serializable; + +/** + * {@link EchoEvent} {@link EventListener} + * + * @since 2.7.2 + */ +public class EchoEventListener extends AbstractEventListener implements Serializable { + + @Override + public void handleEvent(EchoEvent event) { + println("EchoEventListener : " + event); + } +} \ No newline at end of file diff --git a/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEventListener2.java b/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEventListener2.java new file mode 100644 index 00000000000..f30327c4852 --- /dev/null +++ b/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEventListener2.java @@ -0,0 +1,61 @@ +/* + * 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.event; + +import java.io.Serializable; +import java.util.Objects; +import java.util.Vector; + +/** + * {@link EchoEvent} {@link EventListener} 2 + * + * @since 2.7.2 + */ +public class EchoEventListener2 extends Vector> implements Serializable, Comparable>, + EventListener { + + private AbstractEventListener delegate = new AbstractEventListener() { + @Override + protected void handleEvent(Event event) { + println("EchoEventListener2 : " + event); + } + }; + + @Override + public void onEvent(Event event) { + delegate.onEvent(event); + } + + @Override + public int getPriority() { + return 0; + } + + public int getEventOccurs() { + return delegate.getEventOccurs(); + } + + @Override + public boolean equals(Object o) { + return this.getClass().equals(o.getClass()); + } + + @Override + public int hashCode() { + return Objects.hash(this.getClass()); + } +} diff --git a/dubbo-event/src/test/java/org/apache/dubbo/event/EventDispatcherTest.java b/dubbo-event/src/test/java/org/apache/dubbo/event/EventDispatcherTest.java new file mode 100644 index 00000000000..b8d57f93992 --- /dev/null +++ b/dubbo-event/src/test/java/org/apache/dubbo/event/EventDispatcherTest.java @@ -0,0 +1,45 @@ +/* + * 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.event; + +import org.junit.jupiter.api.Test; + +import static org.apache.dubbo.event.EventDispatcher.DIRECT_EXECUTOR; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@link EventDispatcher} Test + * + * @see DirectEventDispatcher + * @since 2.7.2 + */ +public class EventDispatcherTest { + + private EventDispatcher defaultInstance = EventDispatcher.getDefaultExtension(); + + @Test + public void testDefaultInstance() { + assertEquals(DirectEventDispatcher.class, defaultInstance.getClass()); + } + + @Test + public void testDefaultMethods() { + assertEquals(DIRECT_EXECUTOR, defaultInstance.getExecutor()); + assertTrue(defaultInstance.getAllEventListeners().isEmpty()); + } +} diff --git a/dubbo-event/src/test/java/org/apache/dubbo/event/EventListenerTest.java b/dubbo-event/src/test/java/org/apache/dubbo/event/EventListenerTest.java new file mode 100644 index 00000000000..eb3d27b02ea --- /dev/null +++ b/dubbo-event/src/test/java/org/apache/dubbo/event/EventListenerTest.java @@ -0,0 +1,44 @@ +/* + * 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.event; + +import org.junit.jupiter.api.Test; + +import static org.apache.dubbo.event.EventListener.findEventType; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * {@link EventListener} Test + * + * @since 2.7.2 + */ +public class EventListenerTest { + + @Test + public void testFindEventHierarchicalTypes() { + assertEquals(EchoEvent.class, findEventType(new EchoEventListener())); + assertEquals(Event.class, findEventType(new EchoEventListener2())); + + assertEquals(EchoEvent.class, findEventType(EchoEventListener.class)); + assertEquals(Event.class, findEventType(EchoEventListener2.class)); + } + + @Test + public void testOnEvent() { + } + +} \ No newline at end of file diff --git a/dubbo-event/src/test/java/org/apache/dubbo/event/GenericEventTest.java b/dubbo-event/src/test/java/org/apache/dubbo/event/GenericEventTest.java new file mode 100644 index 00000000000..92970343f1c --- /dev/null +++ b/dubbo-event/src/test/java/org/apache/dubbo/event/GenericEventTest.java @@ -0,0 +1,41 @@ +/* + * 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.event; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@link GenericEvent} Test + * + * @since 2.7.2 + */ +public class GenericEventTest { + + @Test + public void test() { + + long timestamp = System.currentTimeMillis(); + GenericEvent event = new GenericEvent("Hello,World"); + + assertEquals("Hello,World", event.getSource()); + assertTrue(event.getTimestamp() >= timestamp); + } + +} diff --git a/dubbo-event/src/test/java/org/apache/dubbo/event/ParallelEventDispatcherTest.java b/dubbo-event/src/test/java/org/apache/dubbo/event/ParallelEventDispatcherTest.java new file mode 100644 index 00000000000..755d482d2a8 --- /dev/null +++ b/dubbo-event/src/test/java/org/apache/dubbo/event/ParallelEventDispatcherTest.java @@ -0,0 +1,59 @@ +/* + * 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.event; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * {@link ParallelEventDispatcher} Test + * + * @since 2.7.2 + */ +public class ParallelEventDispatcherTest { + + private EventDispatcher eventDispatcher; + + private AbstractEventListener listener; + + @BeforeEach + public void init() { + eventDispatcher = new ParallelEventDispatcher(); + listener = new EchoEventListener(); + eventDispatcher.addEventListener(listener); + } + + @Test + public void testDispatchEvent() throws InterruptedException { + eventDispatcher.dispatch(new EchoEvent("Hello,World")); + ForkJoinPool.commonPool().awaitTermination(1, TimeUnit.SECONDS); + // event has been handled + assertEquals(1, listener.getEventOccurs()); + } + + @AfterAll + public static void destroy() { + ForkJoinPool.commonPool().shutdown(); + } + +} diff --git a/dubbo-event/src/test/resources/META-INF/services/org.apache.dubbo.event.EventListener b/dubbo-event/src/test/resources/META-INF/services/org.apache.dubbo.event.EventListener new file mode 100644 index 00000000000..3cb4b7fdd34 --- /dev/null +++ b/dubbo-event/src/test/resources/META-INF/services/org.apache.dubbo.event.EventListener @@ -0,0 +1 @@ +#org.apache.dubbo.event.EchoEventListener2 \ No newline at end of file diff --git a/pom.xml b/pom.xml index a1f7b56820d..434ff0e1d3e 100644 --- a/pom.xml +++ b/pom.xml @@ -148,6 +148,7 @@ dubbo-metadata-report dubbo-configcenter dubbo-dependencies + dubbo-event From 77d802ec3cb65ff571df6445ba5fc647cd8b7ff2 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Mon, 20 May 2019 16:35:11 +0800 Subject: [PATCH 02/46] Polish apache/incubator-dubbo#3942 : Dubbo Cloud Native: To Add Service registration and discovery abstract --- .../dubbo/common/utils/DefaultPage.java | 71 +++++ .../org/apache/dubbo/common/utils/Page.java | 73 +++++ dubbo-registry/dubbo-registry-api/pom.xml | 6 + .../client/CompositeServiceDiscovery.java | 118 ++++++++ .../client/DefaultServiceInstance.java | 133 +++++++++ .../EventPublishingServiceRegistry.java | 128 +++++++++ .../registry/client/ServiceDiscovery.java | 195 ++++++++++++++ .../registry/client/ServiceInstance.java | 94 +++++++ .../registry/client/ServiceRegistry.java | 66 +++++ .../event/ServiceDiscoveryChangeEvent.java | 73 +++++ .../event/ServiceDiscoveryChangeListener.java | 35 +++ .../client/event/ServiceInstanceEvent.java | 47 ++++ .../ServiceInstancePreRegisteredEvent.java | 33 +++ .../event/ServiceInstanceRegisteredEvent.java | 33 +++ .../dubbo/registry/client/package-info.java | 23 ++ .../client/CompositeServiceDiscoveryTest.java | 221 +++++++++++++++ .../client/DefaultServiceInstanceTest.java | 60 +++++ .../EventPublishingServiceRegistryTest.java | 77 ++++++ .../client/InMemoryServiceDiscovery.java | 69 +++++ .../registry/client/ServiceDiscoveryTest.java | 253 ++++++++++++++++++ 20 files changed, 1808 insertions(+) create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/utils/DefaultPage.java create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/utils/Page.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/CompositeServiceDiscovery.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceInstance.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceRegistry.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscovery.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstance.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceRegistry.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryChangeEvent.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryChangeListener.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstanceEvent.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancePreRegisteredEvent.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstanceRegisteredEvent.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/package-info.java create mode 100644 dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/CompositeServiceDiscoveryTest.java create mode 100644 dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/DefaultServiceInstanceTest.java create mode 100644 dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/EventPublishingServiceRegistryTest.java create mode 100644 dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InMemoryServiceDiscovery.java create mode 100644 dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryTest.java diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DefaultPage.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DefaultPage.java new file mode 100644 index 00000000000..71dd2afe895 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DefaultPage.java @@ -0,0 +1,71 @@ +/* + * 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.common.utils; + +import java.io.Serializable; +import java.util.List; + +/** + * The default implementation of {@link Page} + * + * @since 2.7.2 + */ +public class DefaultPage implements Page, Serializable { + + private static final long serialVersionUID = 1099331838954070419L; + + private final int requestOffset; + + private final int requestSize; + + private int totalSize; + + private List data; + + public DefaultPage(int requestOffset, int requestSize) { + this.requestOffset = requestOffset; + this.requestSize = requestSize; + } + + @Override + public int getRequestOffset() { + return requestOffset; + } + + @Override + public int getRequestSize() { + return requestSize; + } + + @Override + public int getTotalSize() { + return totalSize; + } + + public void setTotalSize(int totalSize) { + this.totalSize = totalSize; + } + + @Override + public List getData() { + return data; + } + + public void setData(List data) { + this.data = data; + } +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Page.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Page.java new file mode 100644 index 00000000000..58a4249195d --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Page.java @@ -0,0 +1,73 @@ +/* + * 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.common.utils; + +import java.util.List; + +/** + * The model class of pagination + * + * @since 2.7.2 + */ +public interface Page { + + /** + * Gets the offset of request + * + * @return positive integer + */ + int getRequestOffset(); + + /** + * Gets the size of request for query + * + * @return positive integer + */ + int getRequestSize(); + + /** + * Returns the total amount of elements. + * + * @return the total amount of elements + */ + int getTotalSize(); + + /** + * The data of current page + * + * @return non-null {@link List} + */ + List getData(); + + /** + * The size of {@link #getData() data} + * + * @return positive integer + */ + default int getDataSize() { + return getData().size(); + } + + /** + * Returns whether the page has data at all. + * + * @return + */ + default boolean hasData() { + return getDataSize() > 0; + } +} diff --git a/dubbo-registry/dubbo-registry-api/pom.xml b/dubbo-registry/dubbo-registry-api/pom.xml index 5a707d0686b..d5689b334e8 100644 --- a/dubbo-registry/dubbo-registry-api/pom.xml +++ b/dubbo-registry/dubbo-registry-api/pom.xml @@ -55,6 +55,12 @@ + + org.apache.dubbo + dubbo-event + ${project.parent.version} + + org.apache.curator curator-framework diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/CompositeServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/CompositeServiceDiscovery.java new file mode 100644 index 00000000000..d01891ddb58 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/CompositeServiceDiscovery.java @@ -0,0 +1,118 @@ +/* + * 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.client; + +import org.apache.dubbo.common.utils.DefaultPage; +import org.apache.dubbo.common.utils.Page; +import org.apache.dubbo.registry.client.event.ServiceDiscoveryChangeListener; + +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import static java.lang.String.format; +import static java.lang.String.valueOf; +import static java.util.Arrays.asList; +import static java.util.Collections.unmodifiableSet; +import static org.apache.dubbo.common.utils.CollectionUtils.isNotEmpty; +import static org.apache.dubbo.common.utils.CollectionUtils.sort; + +/** + * The serviceDiscoveries of {@link ServiceDiscovery} + * + * @since 2.7.2 + */ +public class CompositeServiceDiscovery implements ServiceDiscovery { + + private List serviceDiscoveries = new LinkedList<>(); + + public CompositeServiceDiscovery(ServiceDiscovery... serviceDiscoveries) { + this(asList(serviceDiscoveries)); + } + + public CompositeServiceDiscovery(Collection serviceDiscoveries) { + addServiceDiscoveries(serviceDiscoveries); + } + + protected void addServiceDiscoveries(Collection serviceDiscoveries) { + this.serviceDiscoveries.addAll(serviceDiscoveries); + sort(this.serviceDiscoveries); + } + + @Override + public Set getServices() { + Set allServiceNames = new TreeSet<>(); + for (ServiceDiscovery serviceDiscovery : serviceDiscoveries) { + Set serviceNames = serviceDiscovery.getServices(); + if (isNotEmpty(serviceNames)) { + allServiceNames.addAll(serviceNames); + } + } + return unmodifiableSet(allServiceNames); + } + + @Override + public List getInstances(String serviceName) throws NullPointerException { + List serviceInstances = new LinkedList<>(); + for (ServiceDiscovery serviceDiscovery : serviceDiscoveries) { + List instances = serviceDiscovery.getInstances(serviceName); + if (isNotEmpty(instances)) { + serviceInstances.addAll(instances); + } + } + return serviceInstances; + } + + @Override + public Page getInstances(String serviceName, int offset, int requestSize, boolean healthyOnly) + throws NullPointerException, IllegalArgumentException { + DefaultPage page = new DefaultPage<>(offset, requestSize); + + int totalElements = 0; + List serviceInstances = new LinkedList<>(); + + for (ServiceDiscovery serviceDiscovery : serviceDiscoveries) { + Page p = serviceDiscovery.getInstances(serviceName, offset, requestSize, healthyOnly); + totalElements += p.getTotalSize(); + if (p.hasData()) { + serviceInstances.addAll(p.getData()); + } + } + + page.setTotalSize(totalElements); + page.setData(serviceInstances); + return page; + } + + @Override + public String toString() { + return format("%s [composite : %s]", this.getClass().getSimpleName(), valueOf(serviceDiscoveries)); + } + + @Override + public int getPriority() { + return Integer.MIN_VALUE; + } + + @Override + public void addServiceDiscoveryChangeListener(String serviceName, + ServiceDiscoveryChangeListener listener) throws NullPointerException, IllegalArgumentException { + serviceDiscoveries.forEach(serviceDiscovery -> serviceDiscovery.addServiceDiscoveryChangeListener(serviceName, listener)); + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceInstance.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceInstance.java new file mode 100644 index 00000000000..dda1faa680c --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceInstance.java @@ -0,0 +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.registry.client; + +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +/** + * The default implementation of {@link ServiceInstance}. + * + * @since 2.7.2 + */ +public class DefaultServiceInstance implements ServiceInstance { + + private final String id; + + private final String serviceName; + + private final String host; + + private final int port; + + private boolean enabled; + + private boolean healthy; + + private Map metadata = new HashMap<>(); + + public DefaultServiceInstance(String id, String serviceName, String host, int port) { + this.id = id; + this.serviceName = serviceName; + this.host = host; + this.port = port; + this.enabled = true; + this.healthy = true; + } + + public DefaultServiceInstance(String serviceName, String host, int port) { + this(null, serviceName, host, port); + } + + @Override + public String getId() { + return id; + } + + @Override + public String getServiceName() { + return serviceName; + } + + @Override + public String getHost() { + return host; + } + + @Override + public int getPort() { + return port; + } + + @Override + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + @Override + public boolean isHealthy() { + return healthy; + } + + public void setHealthy(boolean healthy) { + this.healthy = healthy; + } + + @Override + public Map getMetadata() { + return metadata; + } + + public void setMetadata(Map metadata) { + this.metadata = metadata; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof DefaultServiceInstance)) return false; + DefaultServiceInstance that = (DefaultServiceInstance) o; + return getPort() == that.getPort() && + Objects.equals(getId(), that.getId()) && + Objects.equals(getServiceName(), that.getServiceName()) && + Objects.equals(getHost(), that.getHost()) && + Objects.equals(getMetadata(), that.getMetadata()); + } + + @Override + public int hashCode() { + return Objects.hash(getId(), getServiceName(), getHost(), getPort(), getMetadata()); + } + + @Override + public String toString() { + return "DefaultServiceInstance{" + + "id='" + id + '\'' + + ", serviceName='" + serviceName + '\'' + + ", host='" + host + '\'' + + ", port=" + port + + ", enabled=" + enabled + + ", healthy=" + healthy + + ", metadata=" + metadata + + '}'; + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceRegistry.java new file mode 100644 index 00000000000..f0459281dad --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceRegistry.java @@ -0,0 +1,128 @@ +/* + * 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.client; + +import org.apache.dubbo.event.Event; +import org.apache.dubbo.event.EventDispatcher; +import org.apache.dubbo.registry.client.event.ServiceInstancePreRegisteredEvent; +import org.apache.dubbo.registry.client.event.ServiceInstanceRegisteredEvent; + +import java.util.Optional; + +import static java.util.Optional.empty; +import static java.util.Optional.of; + +/** + * The abstract {@link ServiceRegistry} implementation publishes the {@link Event Dubbo event} on methods executing. + * + * @since 2.7.2 + */ +public abstract class EventPublishingServiceRegistry implements ServiceRegistry { + + private final EventDispatcher eventDispatcher = EventDispatcher.getDefaultExtension(); + + @Override + public final void register(ServiceInstance serviceInstance) throws RuntimeException { + executeWithEvents( + of(new ServiceInstancePreRegisteredEvent(this, serviceInstance)), + () -> doRegister(serviceInstance), + of(new ServiceInstanceRegisteredEvent(this, serviceInstance)) + ); + } + + @Override + public final void update(ServiceInstance serviceInstance) throws RuntimeException { + // TODO publish event + executeWithEvents( + empty(), + () -> doUpdate(serviceInstance), + empty() + ); + } + + @Override + public final void unregister(ServiceInstance serviceInstance) throws RuntimeException { + // TODO publish event + executeWithEvents( + empty(), + () -> doUnregister(serviceInstance), + empty() + ); + } + + @Override + public final void start() { + // TODO publish event + executeWithEvents( + empty(), + this::doStart, + empty() + ); + } + + @Override + public final void stop() { + // TODO publish event + executeWithEvents( + empty(), + this::doStop, + empty() + ); + } + + protected final void executeWithEvents(Optional beforeEvent, + Runnable action, + Optional afterEvent) { + beforeEvent.ifPresent(eventDispatcher::dispatch); + action.run(); + afterEvent.ifPresent(eventDispatcher::dispatch); + } + + /** + * Registers an instance of {@link ServiceInstance}. + * + * @param serviceInstance an instance of {@link ServiceInstance} to be registered + * @throws RuntimeException if failed + */ + protected abstract void doRegister(ServiceInstance serviceInstance) throws RuntimeException; + + /** + * Updates the registered {@link ServiceInstance}. + * + * @param serviceInstance the registered {@link ServiceInstance} + * @throws RuntimeException if failed + */ + protected abstract void doUpdate(ServiceInstance serviceInstance) throws RuntimeException; + + /** + * Unregisters an instance of {@link ServiceInstance}. + * + * @param serviceInstance an instance of {@link ServiceInstance} to be deregistered + * @throws RuntimeException if failed + */ + protected abstract void doUnregister(ServiceInstance serviceInstance) throws RuntimeException; + + /** + * Starts the ServiceRegistry. This is a lifecycle method. + */ + protected abstract void doStart(); + + /** + * Stops the ServiceRegistry. This is a lifecycle method. + */ + protected abstract void doStop(); +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscovery.java new file mode 100644 index 00000000000..6a1888a4039 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscovery.java @@ -0,0 +1,195 @@ +/* + * 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.client; + +import org.apache.dubbo.common.utils.DefaultPage; +import org.apache.dubbo.common.utils.Page; +import org.apache.dubbo.registry.client.event.ServiceDiscoveryChangeListener; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static java.lang.Integer.compare; +import static java.util.Collections.emptyList; +import static java.util.Collections.unmodifiableMap; + +/** + * The common operations of Service Discovery + * + * @since 2.7.2 + */ +public interface ServiceDiscovery extends Comparable { + + /** + * A human-readable description of the implementation + * + * @return The description. + */ + String toString(); + + /** + * Gets all service names + * + * @return non-null read-only {@link Set} + */ + Set getServices(); + + /** + * Gets all {@link ServiceInstance service instances} by the specified service name. + * + * @param serviceName the service name + * @return non-null {@link List} + * @throws NullPointerException if serviceName is null is null + */ + List getInstances(String serviceName) throws NullPointerException; + + /** + * Gets the total size of {@link #getInstances(String)} instances} + * + * @param serviceName the service name + * @return + * @throws NullPointerException if serviceName is null is null + */ + default int getTotalSizeInstances(String serviceName) throws NullPointerException { + return getInstances(serviceName).size(); + } + + /** + * Gets the {@link Page pagination} of {@link ServiceInstance service instances} by the specified service name. + * It's equal to {@link #getInstances(String, int, int, boolean)} with healthyOnly == true + * + * @param serviceName the service name + * @param offset the offset of request , the number "0" indicates first page + * @param requestSize the number of request, the {@link Integer#MAX_VALUE max value} indicates the range is unlimited + * @return non-null {@link Page} object + * @throws NullPointerException if serviceName is null is null + * @throws IllegalArgumentException if offset or requestSize is negative number + */ + default Page getInstances(String serviceName, int offset, int requestSize) throws NullPointerException, + IllegalArgumentException { + return getInstances(serviceName, offset, requestSize, false); + } + + /** + * Get the {@link Page pagination} of {@link ServiceInstance service instances} by the specified service name. + * If healthyOnly == true, filter healthy instances only. + * + * @param serviceName the service name + * @param offset the offset of request , the number "0" indicates first page + * @param requestSize the number of request, the {@link Integer#MAX_VALUE max value} indicates the range is unlimited + * @param healthyOnly if true , filter healthy instances only + * @return non-null {@link Page} object + * @throws NullPointerException if serviceName is null is null + * @throws IllegalArgumentException if offset or requestSize is negative number + */ + default Page getInstances(String serviceName, int offset, int requestSize, boolean healthyOnly) throws + NullPointerException, IllegalArgumentException { + + List serviceInstances = getInstances(serviceName); + + DefaultPage page = new DefaultPage(offset, requestSize); + + int totalElements = getTotalSizeInstances(serviceName); + + boolean hasMore = totalElements > offset + requestSize; + + int fromIndex = offset < totalElements ? offset : -1; + + int endIndex = hasMore ? offset + requestSize : totalElements; + + List data = fromIndex < 0 ? emptyList() : + new ArrayList<>(serviceInstances.subList(fromIndex, endIndex)); + + Iterator iterator = data.iterator(); + + while (iterator.hasNext()) { + ServiceInstance serviceInstance = iterator.next(); + if (!serviceInstance.isEnabled()) { // remove disabled instance + iterator.remove(); + continue; + } + + if (healthyOnly) { + if (!serviceInstance.isHealthy()) { // remove unhealthy instance + iterator.remove(); + continue; + } + } + } + + page.setData(data); + page.setTotalSize(totalElements); + + return page; + } + + /** + * batch-get all {@link ServiceInstance service instances} by the specified service names + * + * @param serviceNames the multiple service names + * @param offset the offset of request , the number "0" indicates first page + * @param requestSize the number of request, the {@link Integer#MAX_VALUE max value} indicates the range is unlimited + * @return non-null read-only {@link Map} whose key is the service name and value is + * the {@link Page pagination} of {@link ServiceInstance service instances} + * @throws NullPointerException if serviceName is null is null + * @throws IllegalArgumentException if offset or requestSize is negative number + */ + default Map> getInstances(Iterable serviceNames, int offset, int requestSize) throws + NullPointerException, IllegalArgumentException { + Map> instances = new LinkedHashMap<>(); + for (String serviceName : serviceNames) { + instances.put(serviceName, getInstances(serviceName, offset, requestSize)); + } + return unmodifiableMap(instances); + } + + /** + * The priority of current {@link ServiceDiscovery} + * + * @return The {@link Integer#MIN_VALUE minimum integer} indicates the highest priority, in contrast, + * the lowest priority is {@link Integer#MAX_VALUE the maximum integer} + */ + default int getPriority() { + return Integer.MAX_VALUE; + } + + /** + * Compares its priority + * + * @param that {@link ServiceDiscovery} + * @return + */ + @Override + default int compareTo(ServiceDiscovery that) { + return compare(this.getPriority(), that.getPriority()); + } + + /** + * Add an instance of {@link ServiceDiscoveryChangeListener} for specified service + * + * @param serviceName the service name + * @param listener an instance of {@link ServiceDiscoveryChangeListener} + * @throws NullPointerException + * @throws IllegalArgumentException + */ + void addServiceDiscoveryChangeListener(String serviceName, ServiceDiscoveryChangeListener listener) + throws NullPointerException, IllegalArgumentException; +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstance.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstance.java new file mode 100644 index 00000000000..9006681cfe2 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstance.java @@ -0,0 +1,94 @@ +/* + * 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.client; + +import java.util.Map; + +/** + * The model class of an instance of a service, which is used for service registration and discovery. + *

+ * + * @since 2.7.2 + */ +public interface ServiceInstance { + + /** + * The id of the registered service instance. + * + * @return nullable + */ + String getId(); + + /** + * The name of service that current instance belongs to. + * + * @return non-null + */ + String getServiceName(); + + /** + * The hostname of the registered service instance. + * + * @return non-null + */ + String getHost(); + + /** + * The port of the registered service instance. + * + * @return the positive integer + */ + int getPort(); + + /** + * The enable status of the registered service instance. + * + * @return if true, indicates current instance is enabled, or disable, the client should remove this one. + * The default value is true + */ + default boolean isEnabled() { + return true; + } + + /** + * The registered service instance is health or not. + * + * @return if true, indicates current instance is enabled, or disable, the client may ignore this one. + * The default value is true + */ + default boolean isHealthy() { + return true; + } + + /** + * The key / value pair metadata associated with the service instance. + * + * @return non-null, mutable and unsorted {@link Map} + */ + Map getMetadata(); + + /** + * @return the hash code of current instance. + */ + int hashCode(); + + /** + * @param another another {@link ServiceInstance} + * @return if equals , return true, or false + */ + boolean equals(Object another); +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceRegistry.java new file mode 100644 index 00000000000..07b1bfceba6 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceRegistry.java @@ -0,0 +1,66 @@ +/* + * 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.client; + +/** + * The common interface to register and unregister for a service registry + * + * @since 2.7.2 + */ +public interface ServiceRegistry { + + /** + * A human-readable description of the implementation + * + * @return The description. + */ + String toString(); + + /** + * Registers an instance of {@link ServiceInstance}. + * + * @param serviceInstance an instance of {@link ServiceInstance} to be registered + * @throws RuntimeException if failed + */ + void register(ServiceInstance serviceInstance) throws RuntimeException; + + /** + * Updates the registered {@link ServiceInstance}. + * + * @param serviceInstance the registered {@link ServiceInstance} + * @throws RuntimeException if failed + */ + void update(ServiceInstance serviceInstance) throws RuntimeException; + + /** + * Unregisters an instance of {@link ServiceInstance}. + * + * @param serviceInstance an instance of {@link ServiceInstance} to be deregistered + * @throws RuntimeException if failed + */ + void unregister(ServiceInstance serviceInstance) throws RuntimeException; + + /** + * Starts the ServiceRegistry. This is a lifecycle method. + */ + void start(); + + /** + * Stops the ServiceRegistry. This is a lifecycle method. + */ + void stop(); +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryChangeEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryChangeEvent.java new file mode 100644 index 00000000000..1bbf768081c --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryChangeEvent.java @@ -0,0 +1,73 @@ +/* + * 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.client.event; + +import org.apache.dubbo.event.Event; +import org.apache.dubbo.registry.client.ServiceInstance; + +import java.util.Collection; +import java.util.EventObject; + +import static java.util.Collections.unmodifiableCollection; + +/** + * The Service Discovery Change {@link EventObject Event} + * + * @see ServiceDiscoveryChangeListener + * @since 2.7.2 + */ +public class ServiceDiscoveryChangeEvent extends Event { + + private final String serviceName; + + private final Collection serviceInstances; + + private final long timestamp; + + /** + * @param serviceName The name of service that was changed + * @param serviceInstances all {@link ServiceInstance service instances} + * @throws IllegalArgumentException if source is null. + */ + public ServiceDiscoveryChangeEvent(String serviceName, Collection serviceInstances) { + super(serviceName); + this.serviceName = serviceName; + this.serviceInstances = unmodifiableCollection(serviceInstances); + this.timestamp = System.currentTimeMillis(); + } + + /** + * @return The name of service that was changed + */ + public String getServiceName() { + return serviceName; + } + + /** + * @return all {@link ServiceInstance service instances} + */ + public Collection getServiceInstances() { + return serviceInstances; + } + + /** + * Return the system time in milliseconds when the event happened. + */ + public long getTimestamp() { + return this.timestamp; + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryChangeListener.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryChangeListener.java new file mode 100644 index 00000000000..654f069ff02 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryChangeListener.java @@ -0,0 +1,35 @@ +/* + * 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.client.event; + +import org.apache.dubbo.event.EventListener; + +/** + * The Service Discovery Change {@link EventListener Event Listener} + * + * @see ServiceDiscoveryChangeEvent + * @since 2.7.2 + */ +public interface ServiceDiscoveryChangeListener extends EventListener { + + /** + * On {@link ServiceDiscoveryChangeEvent the service change event} + * + * @param event {@link ServiceDiscoveryChangeEvent} + */ + void onEvent(ServiceDiscoveryChangeEvent event); +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstanceEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstanceEvent.java new file mode 100644 index 00000000000..eec9d06ac79 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstanceEvent.java @@ -0,0 +1,47 @@ +/* + * 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.client.event; + +import org.apache.dubbo.event.Event; +import org.apache.dubbo.registry.client.ServiceInstance; + +/** + * The {@link Event Dubbo event} for {@link ServiceInstance an service instance} + * + * @since 2.7.2 + */ +public abstract class ServiceInstanceEvent extends Event { + + private final ServiceInstance serviceInstance; + + /** + * @param serviceInstance {@link ServiceInstance an service instance} + */ + public ServiceInstanceEvent(Object source, ServiceInstance serviceInstance) { + super(source); + this.serviceInstance = serviceInstance; + } + + /** + * Get current {@link ServiceInstance service instance} + * + * @return current {@link ServiceInstance service instance} + */ + public ServiceInstance getServiceInstance() { + return serviceInstance; + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancePreRegisteredEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancePreRegisteredEvent.java new file mode 100644 index 00000000000..ef1151ad8fa --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancePreRegisteredEvent.java @@ -0,0 +1,33 @@ +/* + * 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.client.event; + +import org.apache.dubbo.registry.client.ServiceInstance; +import org.apache.dubbo.registry.client.ServiceRegistry; + + +/** + * The before-{@link ServiceRegistry#register(ServiceInstance) register} event for {@link ServiceInstance} + * + * @since 2.7.2 + */ +public class ServiceInstancePreRegisteredEvent extends ServiceInstanceEvent { + + public ServiceInstancePreRegisteredEvent(Object source, ServiceInstance serviceInstance) { + super(source, serviceInstance); + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstanceRegisteredEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstanceRegisteredEvent.java new file mode 100644 index 00000000000..f359d41376a --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstanceRegisteredEvent.java @@ -0,0 +1,33 @@ +/* + * 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.client.event; + +import org.apache.dubbo.registry.client.ServiceInstance; +import org.apache.dubbo.registry.client.ServiceRegistry; + + +/** + * The after-{@link ServiceRegistry#register(ServiceInstance) register} event for {@link ServiceInstance} + * + * @since 2.7.2 + */ +public class ServiceInstanceRegisteredEvent extends ServiceInstanceEvent { + + public ServiceInstanceRegisteredEvent(Object source, ServiceInstance serviceInstance) { + super(source, serviceInstance); + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/package-info.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/package-info.java new file mode 100644 index 00000000000..3283c3c0c72 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/package-info.java @@ -0,0 +1,23 @@ +/* + * 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. + */ +/** + * * The inspiration of service registration and discovery comes from + * Spring Cloud Commons. + * + * @since 2.7.2 + */ +package org.apache.dubbo.registry.client; \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/CompositeServiceDiscoveryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/CompositeServiceDiscoveryTest.java new file mode 100644 index 00000000000..1ed3f203b77 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/CompositeServiceDiscoveryTest.java @@ -0,0 +1,221 @@ +/* + * 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.client; + +import org.apache.dubbo.common.utils.Page; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; + +import static java.lang.Integer.MIN_VALUE; +import static java.util.Arrays.asList; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@link CompositeServiceDiscovery} Test + * + * @since 2.7.2 + */ +public class CompositeServiceDiscoveryTest { + + private InMemoryServiceDiscovery instance = new InMemoryServiceDiscovery(); + + private CompositeServiceDiscovery serviceDiscovery; + + @BeforeEach + public void init() { + serviceDiscovery = new CompositeServiceDiscovery(instance); + } + + @Test + public void testToString() { + assertEquals("CompositeServiceDiscovery [composite : [InMemoryServiceDiscovery]]", serviceDiscovery.toString()); + } + + @Test + public void testGetPriority() { + assertEquals(MIN_VALUE, serviceDiscovery.getPriority()); + } + + @Test + public void testGetServices() { + instance.addServiceInstance(new DefaultServiceInstance("A", "127.0.0.1", 8080)); + instance.addServiceInstance(new DefaultServiceInstance("B", "127.0.0.1", 8080)); + instance.addServiceInstance(new DefaultServiceInstance("C", "127.0.0.1", 8080)); + assertEquals(new HashSet<>(asList("A", "B", "C")), instance.getServices()); + } + + @Test + public void testGetInstances() { + + List instances = asList( + new DefaultServiceInstance("A", "127.0.0.1", 8080), + new DefaultServiceInstance("A", "127.0.0.1", 8081), + new DefaultServiceInstance("A", "127.0.0.1", 8082) + ); + + instances.forEach(instance::addServiceInstance); + + // Duplicated + instance.addServiceInstance(new DefaultServiceInstance("A", "127.0.0.1", 8080)); + // Duplicated + instance.addServiceInstance(new DefaultServiceInstance("A", "127.0.0.1", 8081)); + + // offset starts 0 + int offset = 0; + // requestSize > total elements + int requestSize = 5; + + Page page = serviceDiscovery.getInstances("A", offset, requestSize); + assertEquals(0, page.getRequestOffset()); + assertEquals(5, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(3, page.getData().size()); + assertTrue(page.hasData()); + + for (ServiceInstance instance : page.getData()) { + assertTrue(instances.contains(instance)); + } + + // requestSize < total elements + requestSize = 2; + + page = serviceDiscovery.getInstances("A", offset, requestSize); + assertEquals(0, page.getRequestOffset()); + assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(2, page.getData().size()); + assertTrue(page.hasData()); + + for (ServiceInstance instance : page.getData()) { + assertTrue(instances.contains(instance)); + } + + offset = 1; + page = serviceDiscovery.getInstances("A", offset, requestSize); + assertEquals(1, page.getRequestOffset()); + assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(2, page.getData().size()); + assertTrue(page.hasData()); + + for (ServiceInstance instance : page.getData()) { + assertTrue(instances.contains(instance)); + } + + offset = 2; + page = serviceDiscovery.getInstances("A", offset, requestSize); + assertEquals(2, page.getRequestOffset()); + assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(1, page.getData().size()); + assertTrue(page.hasData()); + + offset = 3; + page = serviceDiscovery.getInstances("A", offset, requestSize); + assertEquals(3, page.getRequestOffset()); + assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(0, page.getData().size()); + assertFalse(page.hasData()); + + offset = 5; + page = serviceDiscovery.getInstances("A", offset, requestSize); + assertEquals(5, page.getRequestOffset()); + assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(0, page.getData().size()); + assertFalse(page.hasData()); + } + + @Test + public void testGetInstancesWithHealthy() { + + List instances = new LinkedList<>(asList( + new DefaultServiceInstance("A", "127.0.0.1", 8080), + new DefaultServiceInstance("A", "127.0.0.1", 8081) + )); + + + DefaultServiceInstance serviceInstance = new DefaultServiceInstance("A", "127.0.0.1", 8082); + serviceInstance.setHealthy(false); + instances.add(serviceInstance); + + instances.forEach(instance::addServiceInstance); + + // offset starts 0 + int offset = 0; + // requestSize > total elements + int requestSize = 5; + + Page page = serviceDiscovery.getInstances("A", offset, requestSize, true); + assertEquals(0, page.getRequestOffset()); + assertEquals(5, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(2, page.getData().size()); + assertTrue(page.hasData()); + + for (ServiceInstance instance : page.getData()) { + assertTrue(instances.contains(instance)); + } + + // requestSize < total elements + requestSize = 2; + + offset = 1; + page = serviceDiscovery.getInstances("A", offset, requestSize, true); + assertEquals(1, page.getRequestOffset()); + assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(1, page.getData().size()); + assertTrue(page.hasData()); + + for (ServiceInstance instance : page.getData()) { + assertTrue(instances.contains(instance)); + } + + offset = 2; + page = serviceDiscovery.getInstances("A", offset, requestSize, true); + assertEquals(2, page.getRequestOffset()); + assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(0, page.getData().size()); + assertFalse(page.hasData()); + + offset = 3; + page = serviceDiscovery.getInstances("A", offset, requestSize, true); + assertEquals(3, page.getRequestOffset()); + assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(0, page.getData().size()); + assertFalse(page.hasData()); + + offset = 5; + page = serviceDiscovery.getInstances("A", offset, requestSize, true); + assertEquals(5, page.getRequestOffset()); + assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(0, page.getData().size()); + assertFalse(page.hasData()); + } +} \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/DefaultServiceInstanceTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/DefaultServiceInstanceTest.java new file mode 100644 index 00000000000..fb31571aed2 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/DefaultServiceInstanceTest.java @@ -0,0 +1,60 @@ +/* + * 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.client; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@link DefaultServiceInstance} Test + * + * @since 2.7.2 + */ +public class DefaultServiceInstanceTest { + + public static DefaultServiceInstance INSTANCE = + new DefaultServiceInstance("A", "127.0.0.1", 8080); + + @BeforeEach + public void init() { + INSTANCE = new DefaultServiceInstance("A", "127.0.0.1", 8080); + } + + @Test + public void testDefaultValues() { + assertTrue(INSTANCE.isEnabled()); + assertTrue(INSTANCE.isHealthy()); + assertTrue(INSTANCE.getMetadata().isEmpty()); + } + + @Test + public void testSetAndGetValues() { + INSTANCE.setEnabled(false); + INSTANCE.setHealthy(false); + + assertEquals("A", INSTANCE.getServiceName()); + assertEquals("127.0.0.1", INSTANCE.getHost()); + assertEquals(8080, INSTANCE.getPort()); + assertFalse(INSTANCE.isEnabled()); + assertFalse(INSTANCE.isHealthy()); + assertTrue(INSTANCE.getMetadata().isEmpty()); + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/EventPublishingServiceRegistryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/EventPublishingServiceRegistryTest.java new file mode 100644 index 00000000000..4a3f61f0b53 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/EventPublishingServiceRegistryTest.java @@ -0,0 +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.registry.client; + +import org.junit.jupiter.api.Test; + +import static org.apache.dubbo.registry.client.DefaultServiceInstanceTest.INSTANCE; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * {@link EventPublishingServiceRegistry} Test + * + * @since 2.7.2 + */ +public class EventPublishingServiceRegistryTest { + + private static ServiceRegistry serviceRegistry = new DefaultServiceRegistry(); + + private ServiceInstance serviceInstance = INSTANCE; + + @Test + public void testRegister() { + serviceRegistry.register(serviceInstance); + } + + @Test + public void testUpdate() { + serviceRegistry.update(serviceInstance); + } + + @Test + public void testUnregister() { + serviceRegistry.unregister(serviceInstance); + } +} + +class DefaultServiceRegistry extends EventPublishingServiceRegistry { + + @Override + protected void doRegister(ServiceInstance serviceInstance) throws RuntimeException { + assertEquals(INSTANCE, serviceInstance); + } + + @Override + protected void doUpdate(ServiceInstance serviceInstance) throws RuntimeException { + assertEquals(INSTANCE, serviceInstance); + } + + @Override + protected void doUnregister(ServiceInstance serviceInstance) throws RuntimeException { + assertEquals(INSTANCE, serviceInstance); + } + + @Override + protected void doStart() { + + } + + @Override + protected void doStop() { + + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InMemoryServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InMemoryServiceDiscovery.java new file mode 100644 index 00000000000..4311d8259fd --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InMemoryServiceDiscovery.java @@ -0,0 +1,69 @@ +/* + * 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.client; + +import org.apache.dubbo.event.EventDispatcher; +import org.apache.dubbo.registry.client.event.ServiceDiscoveryChangeListener; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.apache.dubbo.event.EventDispatcher.getDefaultExtension; + +/** + * In-Memory {@link ServiceDiscovery} implementation + * + * @since 2.7.2 + */ +public class InMemoryServiceDiscovery implements ServiceDiscovery { + + private final EventDispatcher dispatcher = getDefaultExtension(); + + private Map> repository = new HashMap<>(); + + @Override + public Set getServices() { + return repository.keySet(); + } + + @Override + public List getInstances(String serviceName) throws NullPointerException { + return repository.computeIfAbsent(serviceName, s -> new LinkedList<>()); + } + + public InMemoryServiceDiscovery addServiceInstance(ServiceInstance serviceInstance) { + String serviceName = serviceInstance.getServiceName(); + List serviceInstances = repository.computeIfAbsent(serviceName, s -> new LinkedList<>()); + if (!serviceInstances.contains(serviceInstance)) { + serviceInstances.add(serviceInstance); + } + return this; + } + + public String toString() { + return "InMemoryServiceDiscovery"; + } + + @Override + public void addServiceDiscoveryChangeListener(String serviceName, ServiceDiscoveryChangeListener listener) throws NullPointerException, IllegalArgumentException { + dispatcher.addEventListener(listener); + } + +} diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryTest.java new file mode 100644 index 00000000000..30bdd9c9bb3 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryTest.java @@ -0,0 +1,253 @@ +/* + * 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.client; + +import org.apache.dubbo.common.utils.Page; +import org.apache.dubbo.event.EventDispatcher; +import org.apache.dubbo.event.EventListener; +import org.apache.dubbo.registry.client.event.ServiceInstanceEvent; +import org.apache.dubbo.registry.client.event.ServiceInstancePreRegisteredEvent; +import org.apache.dubbo.registry.client.event.ServiceInstanceRegisteredEvent; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; + +import static java.lang.Integer.MAX_VALUE; +import static java.util.Arrays.asList; +import static org.apache.dubbo.registry.client.DefaultServiceInstanceTest.INSTANCE; +import static org.apache.dubbo.registry.client.ServiceDiscoveryTest.handleEvent; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@link ServiceDiscovery} Test case + * + * @since 2.7.2 + */ +public class ServiceDiscoveryTest { + + private static InMemoryServiceDiscovery instance; + + private EventDispatcher dispatcher = EventDispatcher.getDefaultExtension(); + + @BeforeEach + public void init() { + instance = new InMemoryServiceDiscovery(); + dispatcher.addEventListener(new BeforeEventListener()); + dispatcher.addEventListener(new AfterEventListener()); + dispatcher.removeAllEventListeners(); + } + + @Test + public void testToString() { + assertEquals("InMemoryServiceDiscovery", instance.toString()); + } + + @Test + public void testGetPriority() { + assertEquals(MAX_VALUE, instance.getPriority()); + } + + @Test + public void testGetServices() { + instance.addServiceInstance(new DefaultServiceInstance("A", "127.0.0.1", 8080)); + instance.addServiceInstance(new DefaultServiceInstance("B", "127.0.0.1", 8080)); + instance.addServiceInstance(new DefaultServiceInstance("C", "127.0.0.1", 8080)); + assertEquals(new HashSet<>(asList("A", "B", "C")), instance.getServices()); + } + + @Test + public void testGetInstances() { + + List instances = asList( + new DefaultServiceInstance("A", "127.0.0.1", 8080), + new DefaultServiceInstance("A", "127.0.0.1", 8081), + new DefaultServiceInstance("A", "127.0.0.1", 8082) + ); + + instances.forEach(instance::addServiceInstance); + + // Duplicated + instance.addServiceInstance(new DefaultServiceInstance("A", "127.0.0.1", 8080)); + // Duplicated + instance.addServiceInstance(new DefaultServiceInstance("A", "127.0.0.1", 8081)); + + // offset starts 0 + int offset = 0; + // requestSize > total elements + int requestSize = 5; + + Page page = instance.getInstances("A", offset, requestSize); + assertEquals(0, page.getRequestOffset()); + assertEquals(5, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(3, page.getData().size()); + assertTrue(page.hasData()); + + for (ServiceInstance instance : page.getData()) { + assertTrue(instances.contains(instance)); + } + + // requestSize < total elements + requestSize = 2; + + page = instance.getInstances("A", offset, requestSize); + assertEquals(0, page.getRequestOffset()); + assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(2, page.getData().size()); + assertTrue(page.hasData()); + + for (ServiceInstance instance : page.getData()) { + assertTrue(instances.contains(instance)); + } + + offset = 1; + page = instance.getInstances("A", offset, requestSize); + assertEquals(1, page.getRequestOffset()); + assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(2, page.getData().size()); + assertTrue(page.hasData()); + + for (ServiceInstance instance : page.getData()) { + assertTrue(instances.contains(instance)); + } + + offset = 2; + page = instance.getInstances("A", offset, requestSize); + assertEquals(2, page.getRequestOffset()); + assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(1, page.getData().size()); + assertTrue(page.hasData()); + + offset = 3; + page = instance.getInstances("A", offset, requestSize); + assertEquals(3, page.getRequestOffset()); + assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(0, page.getData().size()); + assertFalse(page.hasData()); + + offset = 5; + page = instance.getInstances("A", offset, requestSize); + assertEquals(5, page.getRequestOffset()); + assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(0, page.getData().size()); + assertFalse(page.hasData()); + } + + @Test + public void testGetInstancesWithHealthy() { + + List instances = new LinkedList<>(asList( + new DefaultServiceInstance("A", "127.0.0.1", 8080), + new DefaultServiceInstance("A", "127.0.0.1", 8081) + )); + + + DefaultServiceInstance serviceInstance = new DefaultServiceInstance("A", "127.0.0.1", 8082); + serviceInstance.setHealthy(false); + instances.add(serviceInstance); + + instances.forEach(instance::addServiceInstance); + + // offset starts 0 + int offset = 0; + // requestSize > total elements + int requestSize = 5; + + Page page = instance.getInstances("A", offset, requestSize, true); + assertEquals(0, page.getRequestOffset()); + assertEquals(5, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(2, page.getData().size()); + assertTrue(page.hasData()); + + for (ServiceInstance instance : page.getData()) { + assertTrue(instances.contains(instance)); + } + + // requestSize < total elements + requestSize = 2; + + offset = 1; + page = instance.getInstances("A", offset, requestSize, true); + assertEquals(1, page.getRequestOffset()); + assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(1, page.getData().size()); + assertTrue(page.hasData()); + + for (ServiceInstance instance : page.getData()) { + assertTrue(instances.contains(instance)); + } + + offset = 2; + page = instance.getInstances("A", offset, requestSize, true); + assertEquals(2, page.getRequestOffset()); + assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(0, page.getData().size()); + assertFalse(page.hasData()); + + offset = 3; + page = instance.getInstances("A", offset, requestSize, true); + assertEquals(3, page.getRequestOffset()); + assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(0, page.getData().size()); + assertFalse(page.hasData()); + + offset = 5; + page = instance.getInstances("A", offset, requestSize, true); + assertEquals(5, page.getRequestOffset()); + assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(0, page.getData().size()); + assertFalse(page.hasData()); + } + + + static void handleEvent(ServiceInstanceEvent event) { + assertEquals(INSTANCE, event.getServiceInstance()); + assertEquals(instance, event.getSource()); + } +} + +class BeforeEventListener implements EventListener { + + @Override + public void onEvent(ServiceInstancePreRegisteredEvent event) { + handleEvent(event); + } +} + +class AfterEventListener implements EventListener { + + @Override + public void onEvent(ServiceInstanceRegisteredEvent event) { + handleEvent(event); + } +} From 5c73899641d1e7fb1d427f95083d7357935d27e9 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Tue, 21 May 2019 00:24:38 +0800 Subject: [PATCH 03/46] Polish apache/incubator-dubbo#3946 : Dubbo Cloud Native : To Add Dubbo metadata service --- dubbo-all/pom.xml | 17 ++ dubbo-metadata/pom.xml | 59 +++++++ .../InMemoryLocalMetadataService.java | 157 ++++++++++++++++++ .../dubbo/metadata/LocalMetadataService.java | 88 ++++++++++ .../dubbo/metadata/MetadataService.java | 135 +++++++++++++++ .../ConfigurableMetadataServiceExporter.java | 117 +++++++++++++ .../export/MetadataServiceExporter.java | 63 +++++++ ...apache.dubbo.metadata.LocalMetadataService | 1 + ...bo.metadata.export.MetadataServiceExporter | 1 + .../InMemoryLocalMetadataServiceTest.java | 140 ++++++++++++++++ .../metadata/LocalMetadataServiceTest.java | 34 ++++ ...nfigurableMetadataServiceExporterTest.java | 89 ++++++++++ .../dubbo/metadata/export/MockRegistry.java | 87 ++++++++++ .../metadata/export/MockRegistryFactory.java | 45 +++++ .../org.apache.dubbo.registry.RegistryFactory | 1 + pom.xml | 1 + 16 files changed, 1035 insertions(+) create mode 100644 dubbo-metadata/pom.xml create mode 100644 dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java create mode 100644 dubbo-metadata/src/main/java/org/apache/dubbo/metadata/LocalMetadataService.java create mode 100644 dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataService.java create mode 100644 dubbo-metadata/src/main/java/org/apache/dubbo/metadata/export/ConfigurableMetadataServiceExporter.java create mode 100644 dubbo-metadata/src/main/java/org/apache/dubbo/metadata/export/MetadataServiceExporter.java create mode 100644 dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.LocalMetadataService create mode 100644 dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.export.MetadataServiceExporter create mode 100644 dubbo-metadata/src/test/java/org/apache/dubbo/metadata/InMemoryLocalMetadataServiceTest.java create mode 100644 dubbo-metadata/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java create mode 100644 dubbo-metadata/src/test/java/org/apache/dubbo/metadata/export/ConfigurableMetadataServiceExporterTest.java create mode 100644 dubbo-metadata/src/test/java/org/apache/dubbo/metadata/export/MockRegistry.java create mode 100644 dubbo-metadata/src/test/java/org/apache/dubbo/metadata/export/MockRegistryFactory.java create mode 100644 dubbo-metadata/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory diff --git a/dubbo-all/pom.xml b/dubbo-all/pom.xml index 0ff4568aa12..6ae3fbf0909 100644 --- a/dubbo-all/pom.xml +++ b/dubbo-all/pom.xml @@ -509,6 +509,14 @@ true + + org.apache.dubbo + dubbo-metadata + ${project.version} + compile + true + + org.springframework @@ -643,6 +651,7 @@ org.apache.dubbo:dubbo-event + org.apache.dubbo:dubbo-metadata @@ -773,6 +782,14 @@ META-INF/dubbo/internal/org.apache.dubbo.event.EventDispatcher + + META-INF/dubbo/internal/org.apache.dubbo.metadata.export.MetadataServiceExporter + + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.LocalMetadataService + + diff --git a/dubbo-metadata/pom.xml b/dubbo-metadata/pom.xml new file mode 100644 index 00000000000..08ff7f234e0 --- /dev/null +++ b/dubbo-metadata/pom.xml @@ -0,0 +1,59 @@ + + + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + + 4.0.0 + + dubbo-metadata + jar + + dubbo-metadata + The metadata module of Dubbo project + + + + org.apache.dubbo + dubbo-config-api + ${revision} + true + + + + + org.apache.dubbo + dubbo-rpc-dubbo + ${revision} + test + + + + org.apache.dubbo + dubbo-remoting-netty4 + ${revision} + test + + + + + \ No newline at end of file diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java new file mode 100644 index 00000000000..1f90543eb6b --- /dev/null +++ b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java @@ -0,0 +1,157 @@ +/* + * 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; + +import org.apache.dubbo.common.URL; + +import java.util.Collection; +import java.util.LinkedHashSet; +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.ConcurrentMap; +import java.util.stream.Collectors; + +import static java.util.Collections.unmodifiableList; +import static org.apache.dubbo.common.URL.buildKey; +import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; + +/** + * The {@link LocalMetadataService} implementation stores the metadata of Dubbo services in memory locally when they + * exported. + * + * @see MetadataService + * @since 2.7.2 + */ +public class InMemoryLocalMetadataService implements LocalMetadataService { + + /** + * The class name of {@link MetadataService} + */ + static final String METADATA_SERVICE_CLASS_NAME = MetadataService.class.getName(); + + // =================================== Registration =================================== // + + /** + * All exported {@link URL urls} {@link Map} whose key is the return value of {@link URL#getServiceKey()} method + * and value is the {@link List} of the {@link URL URLs} + */ + private ConcurrentMap> exportedServiceURLs = new ConcurrentHashMap<>(); + + // ==================================================================================== // + + // =================================== Subscription =================================== // + + /** + * All subscribed service names + */ + private Set subscribedServices = new LinkedHashSet<>(); + + /** + * The subscribed {@link URL urls} {@link Map} of {@link MetadataService}, + * whose key is the return value of {@link URL#getServiceKey()} method and value is the {@link List} of + * the {@link URL URLs} + */ + private final ConcurrentMap> subscribedServiceURLs = new ConcurrentHashMap<>(); + + // ==================================================================================== // + + @Override + public List getSubscribedURLs() { + return getAllServiceURLs(subscribedServiceURLs); + } + + @Override + public List getExportedURLs(String serviceInterface, String group, String version, String protocol) { + if (ALL_SERVICE_INTERFACES.equals(serviceInterface)) { + return getAllServiceURLs(exportedServiceURLs); + } + String serviceKey = buildKey(serviceInterface, group, version); + return unmodifiableList(getServiceURLs(exportedServiceURLs, serviceKey, protocol)); + } + + protected List getServiceURLs(ConcurrentMap> exportedServiceURLs, String serviceKey, + String protocol) { + List serviceURLs = getServiceURLs(exportedServiceURLs, serviceKey); + return serviceURLs.stream().filter( + url -> protocol == null || protocol.equals(url.getParameter(PROTOCOL_KEY))) + .map(URL::toFullString) + .collect(Collectors.toList()); + } + + + private boolean isMetadataServiceURL(URL url) { + String serviceInterface = url.getServiceInterface(); + return METADATA_SERVICE_CLASS_NAME.equals(serviceInterface); + } + + @Override + public boolean exportURL(URL url) { + if (isMetadataServiceURL(url)) { // ignore MetadataService in the export phase + return true; + } + return addURL(exportedServiceURLs, url); + } + + @Override + public boolean unexportURL(URL url) { + if (isMetadataServiceURL(url)) { // ignore MetadataService in the export phase + return true; + } + return removeURL(exportedServiceURLs, url); + } + + @Override + public boolean subscribeURL(URL url) { + return addURL(subscribedServiceURLs, url); + } + + @Override + public boolean unsubscribeURL(URL url) { + return removeURL(subscribedServiceURLs, url); + } + + protected boolean addURL(Map> serviceURLs, URL url) { + String serviceKey = url.getServiceKey(); + List urls = getServiceURLs(serviceURLs, serviceKey); + if (!urls.contains(url)) { + return urls.add(url); + } + return false; + } + + protected boolean removeURL(Map> serviceURLs, URL url) { + String serviceKey = url.getServiceKey(); + List urls = getServiceURLs(serviceURLs, serviceKey); + return urls.remove(url); + } + + protected List getServiceURLs(Map> serviceURLs, String serviceKey) { + return serviceURLs.computeIfAbsent(serviceKey, s -> new LinkedList()); + } + + protected List getAllServiceURLs(Map> serviceURLs) { + return serviceURLs + .values() + .stream() + .flatMap(Collection::stream) + .map(URL::toFullString) + .collect(Collectors.toList()); + } +} diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/LocalMetadataService.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/LocalMetadataService.java new file mode 100644 index 00000000000..97636338959 --- /dev/null +++ b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/LocalMetadataService.java @@ -0,0 +1,88 @@ +/* + * 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; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.extension.ExtensionLoader; +import org.apache.dubbo.common.extension.SPI; +import org.apache.dubbo.rpc.model.ApplicationModel; + +import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; + +/** + * Local {@link MetadataService} that extends {@link MetadataService} and provides the modification, which is used for + * Dubbo's consumers and providers. + * + * @since 2.7.2 + */ +@SPI("default") +public interface LocalMetadataService extends MetadataService { + + /** + * Gets the current Dubbo Service name + * + * @return non-null + */ + @Override + default String serviceName() { + return ApplicationModel.getApplication(); + } + + /** + * Exports a {@link URL} + * + * @param url a {@link URL} + * @return If success , return true + */ + boolean exportURL(URL url); + + /** + * Unexports a {@link URL} + * + * @param url a {@link URL} + * @return If success , return true + */ + boolean unexportURL(URL url); + + /** + * Subscribes a {@link URL} + * + * @param url a {@link URL} + * @return If success , return true + */ + boolean subscribeURL(URL url); + + /** + * Unsubscribes a {@link URL} + * + * @param url a {@link URL} + * @return If success , return true + */ + boolean unsubscribeURL(URL url); + + + /** + * Get {@link ExtensionLoader#getDefaultExtension() the defautl extension} of {@link LocalMetadataService} + * + * @return non-null + * @see InMemoryLocalMetadataService + */ + public static LocalMetadataService getDefaultExtension() { + return getExtensionLoader(LocalMetadataService.class).getDefaultExtension(); + } + +} diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataService.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataService.java new file mode 100644 index 00000000000..a1cf75db8f1 --- /dev/null +++ b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataService.java @@ -0,0 +1,135 @@ +/* + * 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; + +import org.apache.dubbo.common.URL; + +import java.util.List; + +/** + * A framework interface of Dubbo Metadata Service defines the contract of Dubbo Services registartion and subscription + * between Dubbo service providers and its consumers. The implementationwill be exported as a normal Dubbo service that + * the clients would subscribe, whose version comes from the {@link #version()} method and group gets from + * {@link #serviceName()}, that means, The different Dubbo service(application) will export the different + * {@link MetadataService} that persists all the exported and subscribed metadata, they are present by + * {@link #getExportedURLs()} and {@link #getSubscribedURLs()} respectively. What's more, {@link MetadataService} + * also providers the fine-grain methods for the precise queries. + * + * @see InMemoryLocalMetadataService + * @since 2.7.2 + */ +public interface MetadataService { + + /** + * The value of all service names + */ + String ALL_SERVICE_NAMES = "*"; + + /** + * The value of All service instances + */ + String ALL_SERVICE_INTERFACES = "*"; + + /** + * The contract version of {@link MetadataService}, the future update must make sure compatible. + */ + String VERSION = "1.0.0"; + + /** + * Gets the current Dubbo Service name + * + * @return non-null + */ + String serviceName(); + + /** + * Gets the version of {@link MetadataService} that always equals {@link #VERSION} + * + * @return non-null + * @see #VERSION + */ + default String version() { + return VERSION; + } + + /** + * the list of String that presents all Dubbo subscribed {@link URL urls} + * + * @return non-null read-only {@link List} + */ + List getSubscribedURLs(); + + /** + * Get the list of String that presents all Dubbo exported {@link URL urls} + * + * @return non-null read-only {@link List} + */ + default List getExportedURLs() { + return getExportedURLs(ALL_SERVICE_INTERFACES); + } + + /** + * Get the list of String that presents the specified Dubbo exported {@link URL urls} by the serviceInterface + * + * @param serviceInterface The class name of Dubbo service interface + * @return non-null read-only {@link List} + * @see URL + */ + default List getExportedURLs(String serviceInterface) { + return getExportedURLs(serviceInterface, null); + } + + /** + * Get the list of String that presents the specified Dubbo exported {@link URL urls} by the + * serviceInterface and group + * + * @param serviceInterface The class name of Dubbo service interface + * @param group the Dubbo Service Group (optional) + * @return non-null read-only {@link List} + * @see URL + */ + default List getExportedURLs(String serviceInterface, String group) { + return getExportedURLs(serviceInterface, group, null); + } + + /** + * Get the list of String that presents the specified Dubbo exported {@link URL urls} by the + * serviceInterface, group and version + * + * @param serviceInterface The class name of Dubbo service interface + * @param group the Dubbo Service Group (optional) + * @param version the Dubbo Service Version (optional) + * @return non-null read-only {@link List} + * @see URL + */ + default List getExportedURLs(String serviceInterface, String group, String version) { + return getExportedURLs(serviceInterface, group, version, null); + } + + /** + * Get the list of String that presents the specified Dubbo exported {@link URL urls} by the + * serviceInterface, group, version and protocol + * + * @param serviceInterface The class name of Dubbo service interface + * @param group the Dubbo Service Group (optional) + * @param version the Dubbo Service Version (optional) + * @param protocol the Dubbo Service Protocol (optional) + * @return non-null read-only {@link List} + * @see URL + */ + List getExportedURLs(String serviceInterface, String group, String version, String protocol); +} diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/export/ConfigurableMetadataServiceExporter.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/export/ConfigurableMetadataServiceExporter.java new file mode 100644 index 00000000000..b15a025ecef --- /dev/null +++ b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/export/ConfigurableMetadataServiceExporter.java @@ -0,0 +1,117 @@ +/* + * 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.export; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.config.AbstractConfig; +import org.apache.dubbo.config.ApplicationConfig; +import org.apache.dubbo.config.ProtocolConfig; +import org.apache.dubbo.config.RegistryConfig; +import org.apache.dubbo.config.ServiceConfig; +import org.apache.dubbo.config.context.ConfigManager; +import org.apache.dubbo.metadata.LocalMetadataService; +import org.apache.dubbo.metadata.MetadataService; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * {@link MetadataServiceExporter} implementation based on {@link AbstractConfig Dubbo configurations}, the clients + * should make sure the {@link ApplicationConfig}, {@link RegistryConfig} and {@link ProtocolConfig} are ready before + * {@link #export()}. + *

+ * Typically, do not worry about their ready status, because they are initialized before + * any {@link ServiceConfig} exports, or The Dubbo export will be failed. + * + * @see MetadataServiceExporter + * @see ServiceConfig + * @see ConfigManager + * @since 2.7.2 + */ +public class ConfigurableMetadataServiceExporter implements MetadataServiceExporter { + + private final Logger logger = LoggerFactory.getLogger(getClass()); + + /** + * {@link ConfigManager} stores {@link AbstractConfig the Dubbo *Config instances} + */ + private final ConfigManager configManager = ConfigManager.getInstance(); + + private volatile ServiceConfig serviceConfig; + + @Override + public List export() { + + if (!isExported()) { + + LocalMetadataService metadataService = LocalMetadataService.getDefaultExtension(); + + ServiceConfig serviceConfig = new ServiceConfig<>(); + serviceConfig.setApplication(getApplicationConfig()); + serviceConfig.setRegistries(getRegistries()); + serviceConfig.setProtocols(getProtocols()); + serviceConfig.setInterface(MetadataService.class); + serviceConfig.setRef(metadataService); + serviceConfig.setGroup(getApplicationConfig().getName()); + serviceConfig.setVersion(metadataService.version()); + + // export + serviceConfig.export(); + + if (logger.isInfoEnabled()) { + logger.info("The MetadataService exports urls : " + serviceConfig.getExportedUrls()); + } + + this.serviceConfig = serviceConfig; + } else { + if (logger.isWarnEnabled()) { + logger.warn("The MetadataService has been exported : " + serviceConfig.getExportedUrls()); + } + } + return serviceConfig.getExportedUrls(); + } + + @Override + public void unexport() { + if (isExported()) { + serviceConfig.unexport(); + } + } + + private List list(Map map) { + return new ArrayList<>(map.values()); + } + + private List getProtocols() { + return list(configManager.getProtocols()); + } + + private List getRegistries() { + return list(configManager.getRegistries()); + } + + private ApplicationConfig getApplicationConfig() { + return configManager.getApplication().get(); + } + + private boolean isExported() { + return serviceConfig != null && serviceConfig.isExported(); + } +} diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/export/MetadataServiceExporter.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/export/MetadataServiceExporter.java new file mode 100644 index 00000000000..b99727a7267 --- /dev/null +++ b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/export/MetadataServiceExporter.java @@ -0,0 +1,63 @@ +/* + * 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.export; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.extension.ExtensionLoader; +import org.apache.dubbo.common.extension.SPI; +import org.apache.dubbo.metadata.MetadataService; + +import java.util.List; + +import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; + +/** + * The exporter of {@link MetadataService} + * + * @see MetadataService + * @see #export() + * @see #unexport() + * @since 2.7.2 + */ +@SPI("default") +public interface MetadataServiceExporter { + + /** + * Exports the {@link MetadataService} as a Dubbo service + * + * @return the exported {@link URL URLs} + */ + List export(); + + /** + * Unexports the {@link MetadataService} + */ + void unexport(); + + + /** + * Get {@link ExtensionLoader#getDefaultExtension() the defautl extension} of {@link MetadataServiceExporter} + * + * @return non-null + * @see MetadataServiceExporter + * @see ConfigurableMetadataServiceExporter + * @see ExtensionLoader + */ + static MetadataServiceExporter getDefaultExtension() { + return getExtensionLoader(MetadataServiceExporter.class).getDefaultExtension(); + } +} diff --git a/dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.LocalMetadataService b/dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.LocalMetadataService new file mode 100644 index 00000000000..2af06fde611 --- /dev/null +++ b/dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.LocalMetadataService @@ -0,0 +1 @@ +default=org.apache.dubbo.metadata.InMemoryLocalMetadataService \ No newline at end of file diff --git a/dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.export.MetadataServiceExporter b/dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.export.MetadataServiceExporter new file mode 100644 index 00000000000..fd3aaa3a0bf --- /dev/null +++ b/dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.export.MetadataServiceExporter @@ -0,0 +1 @@ +default=org.apache.dubbo.metadata.export.ConfigurableMetadataServiceExporter \ No newline at end of file diff --git a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/InMemoryLocalMetadataServiceTest.java b/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/InMemoryLocalMetadataServiceTest.java new file mode 100644 index 00000000000..835a0d56e3c --- /dev/null +++ b/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/InMemoryLocalMetadataServiceTest.java @@ -0,0 +1,140 @@ +/* + * 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; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.rpc.model.ApplicationModel; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static java.util.Arrays.asList; +import static org.apache.dubbo.common.URL.valueOf; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@link InMemoryLocalMetadataService} Test + * + * @since 2.7.2 + */ +public class InMemoryLocalMetadataServiceTest { + + private LocalMetadataService metadataService = new InMemoryLocalMetadataService(); + + private static final String TEST_SERVICE = "org.apache.dubbo.test.TestService"; + + private static final URL BASE_URL = valueOf("dubbo://127.0.0.1:20880/" + TEST_SERVICE); + private static final URL REST_BASE_URL = valueOf("rest://127.0.0.1:20880/" + TEST_SERVICE); + private static final URL BASE_URL_GROUP = BASE_URL.addParameter(GROUP_KEY, "test"); + private static final URL BASE_URL_GROUP_AND_VERSION = BASE_URL_GROUP.addParameter(VERSION_KEY, "1.0.0"); + private static final URL BASE_URL_GROUP_AND_VERSION_AND_PROTOCOL = BASE_URL_GROUP_AND_VERSION.addParameter(PROTOCOL_KEY, "rest"); + + @BeforeAll + public static void init() { + ApplicationModel.setApplication("test"); + } + + @Test + public void testServiceName() { + assertEquals("test", metadataService.serviceName()); + } + + @Test + public void testVersion() { + assertEquals("1.0.0", MetadataService.VERSION); + assertEquals("1.0.0", metadataService.version()); + } + + @Test + public void testGetExportedURLs() { + + assertTrue(metadataService.exportURL(BASE_URL)); + List exportedURLs = metadataService.getExportedURLs(TEST_SERVICE); + assertEquals(1, exportedURLs.size()); + assertEquals(asList(BASE_URL.toFullString()), exportedURLs); + assertTrue(metadataService.unexportURL(BASE_URL)); + + assertTrue(metadataService.exportURL(BASE_URL)); + assertFalse(metadataService.exportURL(BASE_URL)); + + assertTrue(metadataService.exportURL(BASE_URL_GROUP)); + assertTrue(metadataService.exportURL(BASE_URL_GROUP_AND_VERSION)); + + exportedURLs = metadataService.getExportedURLs(TEST_SERVICE); + assertEquals(asList(BASE_URL.toFullString()), exportedURLs); + assertEquals(asList( + BASE_URL.toFullString(), + BASE_URL_GROUP.toFullString(), + BASE_URL_GROUP_AND_VERSION.toFullString()), metadataService.getExportedURLs()); + + assertTrue(metadataService.exportURL(REST_BASE_URL)); + exportedURLs = metadataService.getExportedURLs(TEST_SERVICE); + assertEquals(asList(BASE_URL.toFullString(), REST_BASE_URL.toFullString()), exportedURLs); + + metadataService.exportURL(BASE_URL_GROUP_AND_VERSION_AND_PROTOCOL); + + exportedURLs = metadataService.getExportedURLs(TEST_SERVICE, "test", "1.0.0", "rest"); + + assertEquals(asList(BASE_URL_GROUP_AND_VERSION_AND_PROTOCOL.toFullString()), exportedURLs); + } + + @Test + public void testGetSubscribedURLs() { + assertTrue(metadataService.subscribeURL(BASE_URL)); + assertFalse(metadataService.subscribeURL(BASE_URL)); + + assertTrue(metadataService.subscribeURL(BASE_URL_GROUP)); + assertTrue(metadataService.subscribeURL(BASE_URL_GROUP_AND_VERSION)); + assertTrue(metadataService.subscribeURL(REST_BASE_URL)); + + List subscribedURLs = metadataService.getSubscribedURLs(); + assertEquals(4, subscribedURLs.size()); + assertEquals(asList( + BASE_URL.toFullString(), + REST_BASE_URL.toFullString(), + BASE_URL_GROUP.toFullString(), + BASE_URL_GROUP_AND_VERSION.toFullString()), subscribedURLs); + + assertTrue(metadataService.unsubscribeURL(REST_BASE_URL)); + subscribedURLs = metadataService.getSubscribedURLs(); + assertEquals(3, subscribedURLs.size()); + assertEquals(asList( + BASE_URL.toFullString(), + BASE_URL_GROUP.toFullString(), + BASE_URL_GROUP_AND_VERSION.toFullString()), subscribedURLs); + + assertTrue(metadataService.unsubscribeURL(BASE_URL_GROUP)); + subscribedURLs = metadataService.getSubscribedURLs(); + assertEquals(2, subscribedURLs.size()); + assertEquals(asList( + BASE_URL.toFullString(), + BASE_URL_GROUP_AND_VERSION.toFullString()), subscribedURLs); + + assertTrue(metadataService.unsubscribeURL(BASE_URL_GROUP_AND_VERSION)); + subscribedURLs = metadataService.getSubscribedURLs(); + assertEquals(1, subscribedURLs.size()); + assertEquals(asList( + BASE_URL.toFullString()), subscribedURLs); + } +} \ No newline at end of file diff --git a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java b/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java new file mode 100644 index 00000000000..937ddce985f --- /dev/null +++ b/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java @@ -0,0 +1,34 @@ +/* + * 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; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * {@link LocalMetadataService} Test + * + * @since 2.7.2 + */ +public class LocalMetadataServiceTest { + + @Test + public void testDefaultExtension() { + assertEquals(InMemoryLocalMetadataService.class, LocalMetadataService.getDefaultExtension().getClass()); + } +} diff --git a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/export/ConfigurableMetadataServiceExporterTest.java b/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/export/ConfigurableMetadataServiceExporterTest.java new file mode 100644 index 00000000000..24d56ed37e4 --- /dev/null +++ b/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/export/ConfigurableMetadataServiceExporterTest.java @@ -0,0 +1,89 @@ +/* + * 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.export; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.config.ApplicationConfig; +import org.apache.dubbo.config.ProtocolConfig; +import org.apache.dubbo.config.RegistryConfig; +import org.apache.dubbo.config.context.ConfigManager; +import org.apache.dubbo.metadata.MetadataService; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; +import static org.apache.dubbo.metadata.export.MetadataServiceExporter.getDefaultExtension; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * {@link ConfigurableMetadataServiceExporter} Test + * + * @since 2.7.2 + */ +public class ConfigurableMetadataServiceExporterTest { + + @BeforeAll + public static void init() { + ConfigManager configManager = ConfigManager.getInstance(); + ApplicationConfig applicationConfig = new ApplicationConfig(); + applicationConfig.setName("test"); + configManager.setApplication(applicationConfig); + + // Add ProtocolConfig + configManager.addProtocol(protocolConfig()); + // Add RegistryConfig + configManager.addRegistry(registryConfig()); + } + + private static ProtocolConfig protocolConfig() { + ProtocolConfig protocolConfig = new ProtocolConfig(); + protocolConfig.setName(DUBBO_PROTOCOL); + protocolConfig.setPort(20880); + return protocolConfig; + } + + private static RegistryConfig registryConfig() { + RegistryConfig registryConfig = new RegistryConfig(); + registryConfig.setAddress("mock://127.0.0.1"); + return registryConfig; + } + + @Test + public void testExportAndUnexport() { + MetadataServiceExporter exporter = getDefaultExtension(); + List urls = exporter.export(); + + assertEquals(1, urls.size()); + + URL url = urls.get(0); + + assertEquals("test", url.getParameter(APPLICATION_KEY)); + assertEquals(MetadataService.class.getName(), url.getServiceInterface()); + assertEquals("test", url.getParameter(GROUP_KEY)); + assertEquals(MetadataService.VERSION, url.getParameter(VERSION_KEY)); + assertEquals(DUBBO_PROTOCOL, url.getProtocol()); + + exporter.unexport(); + } + +} diff --git a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/export/MockRegistry.java b/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/export/MockRegistry.java new file mode 100644 index 00000000000..5d30385115d --- /dev/null +++ b/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/export/MockRegistry.java @@ -0,0 +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.metadata.export; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.registry.NotifyListener; +import org.apache.dubbo.registry.Registry; + +import java.util.ArrayList; +import java.util.List; + +public class MockRegistry implements Registry { + + private URL url; + + private List registered = new ArrayList(); + + private List subscribered = new ArrayList(); + + public MockRegistry(URL url) { + if (url == null) { + throw new NullPointerException(); + } + this.url = url; + } + + public List getRegistered() { + return registered; + } + + public List getSubscribered() { + return subscribered; + } + + public URL getUrl() { + return url; + } + + @Override + public boolean isAvailable() { + return true; + } + + @Override + public void destroy() { + + } + + @Override + public void register(URL url) { + registered.add(url); + } + + @Override + public void unregister(URL url) { + registered.remove(url); + } + + @Override + public void subscribe(URL url, NotifyListener listener) { + subscribered.add(url); + } + + @Override + public void unsubscribe(URL url, NotifyListener listener) { + subscribered.remove(url); + } + + @Override + public List lookup(URL url) { + return null; + } +} diff --git a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/export/MockRegistryFactory.java b/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/export/MockRegistryFactory.java new file mode 100644 index 00000000000..fbbae0cc7a5 --- /dev/null +++ b/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/export/MockRegistryFactory.java @@ -0,0 +1,45 @@ +/* + * 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.export; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.registry.Registry; +import org.apache.dubbo.registry.RegistryFactory; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +public class MockRegistryFactory implements RegistryFactory { + + private static final Map registries = new HashMap(); + + public static Collection getCachedRegistry() { + return registries.values(); + } + + public static void cleanCachedRegistry() { + registries.clear(); + } + + @Override + public Registry getRegistry(URL url) { + MockRegistry registry = new MockRegistry(url); + registries.put(url, registry); + return registry; + } +} diff --git a/dubbo-metadata/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory b/dubbo-metadata/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory new file mode 100644 index 00000000000..011c931b965 --- /dev/null +++ b/dubbo-metadata/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory @@ -0,0 +1 @@ +mock=org.apache.dubbo.metadata.export.MockRegistryFactory \ No newline at end of file diff --git a/pom.xml b/pom.xml index 434ff0e1d3e..0c9cb3d0c6a 100644 --- a/pom.xml +++ b/pom.xml @@ -149,6 +149,7 @@ dubbo-configcenter dubbo-dependencies dubbo-event + dubbo-metadata From b2dbff3043592f002c9038413034c85b31d33f0e Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Tue, 21 May 2019 01:19:56 +0800 Subject: [PATCH 04/46] Polish apache/incubator-dubbo#4093 : To add exported and unexported events for ServiceConfig --- .../apache/dubbo/config/ServiceConfig.java | 42 ++++++++++++----- .../event/ServiceConfigExportedEvent.java | 36 +++++++++++++++ .../event/ServiceConfigUnexportedEvent.java | 36 +++++++++++++++ .../dubbo/config/ServiceConfigTest.java | 45 ++++++++++++++++++- 4 files changed, 148 insertions(+), 11 deletions(-) create mode 100644 dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ServiceConfigExportedEvent.java create mode 100644 dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ServiceConfigUnexportedEvent.java diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index d485be70246..fe26082b17c 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -29,8 +29,12 @@ import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.annotation.Service; import org.apache.dubbo.config.context.ConfigManager; +import org.apache.dubbo.config.event.ServiceConfigExportedEvent; +import org.apache.dubbo.config.event.ServiceConfigUnexportedEvent; import org.apache.dubbo.config.invoker.DelegateProviderMetaDataInvoker; import org.apache.dubbo.config.support.Parameter; +import org.apache.dubbo.event.Event; +import org.apache.dubbo.event.EventDispatcher; import org.apache.dubbo.metadata.integration.MetadataReportService; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Exporter; @@ -67,31 +71,31 @@ import static org.apache.dubbo.common.constants.CommonConstants.DUBBO; import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_IP_TO_BIND; +import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.EXPORT_KEY; +import static org.apache.dubbo.common.utils.NetUtils.getAvailablePort; +import static org.apache.dubbo.common.utils.NetUtils.getLocalHost; +import static org.apache.dubbo.common.utils.NetUtils.isInvalidLocalHost; +import static org.apache.dubbo.common.utils.NetUtils.isInvalidPort; import static org.apache.dubbo.config.Constants.DUBBO_IP_TO_REGISTRY; import static org.apache.dubbo.config.Constants.DUBBO_PORT_TO_BIND; import static org.apache.dubbo.config.Constants.DUBBO_PORT_TO_REGISTRY; -import static org.apache.dubbo.common.constants.RegistryConstants.EXPORT_KEY; import static org.apache.dubbo.config.Constants.MULTICAST; import static org.apache.dubbo.config.Constants.PROTOCOLS_SUFFIX; -import static org.apache.dubbo.rpc.Constants.SCOPE_KEY; -import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL; import static org.apache.dubbo.config.Constants.SCOPE_NONE; -import static org.apache.dubbo.rpc.Constants.SCOPE_REMOTE; -import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL; import static org.apache.dubbo.rpc.Constants.PROXY_KEY; +import static org.apache.dubbo.rpc.Constants.SCOPE_KEY; +import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL; +import static org.apache.dubbo.rpc.Constants.SCOPE_REMOTE; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; -import static org.apache.dubbo.common.utils.NetUtils.getAvailablePort; -import static org.apache.dubbo.common.utils.NetUtils.getLocalHost; -import static org.apache.dubbo.common.utils.NetUtils.isInvalidLocalHost; -import static org.apache.dubbo.common.utils.NetUtils.isInvalidPort; /** * ServiceConfig @@ -144,6 +148,8 @@ public class ServiceConfig extends AbstractServiceConfig { */ private final List> exporters = new ArrayList>(); + private final EventDispatcher eventDispatcher = EventDispatcher.getDefaultExtension(); + /** * The interface name of the exported service */ @@ -413,6 +419,9 @@ protected synchronized void doExport() { path = interfaceName; } doExportUrls(); + + // dispatch a ServiceConfigExportedEvent since 2.7.2 + dispatch(new ServiceConfigExportedEvent(this)); } private void checkRef() { @@ -445,6 +454,9 @@ public synchronized void unexport() { exporters.clear(); } unexported = true; + + // dispatch a ServiceConfigUnExportedEvent since 2.7.2 + dispatch(new ServiceConfigUnexportedEvent(this)); } @SuppressWarnings({"unchecked", "rawtypes"}) @@ -1051,4 +1063,14 @@ public void setProviders(List providers) { public String getPrefix() { return DUBBO + ".service." + interfaceName; } + + /** + * Dispatch an {@link Event event} + * + * @param event an {@link Event event} + * @since 2.7.2 + */ + protected void dispatch(Event event) { + eventDispatcher.dispatch(event); + } } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ServiceConfigExportedEvent.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ServiceConfigExportedEvent.java new file mode 100644 index 00000000000..e6e9c09a108 --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ServiceConfigExportedEvent.java @@ -0,0 +1,36 @@ +/* + * 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.config.event; + +import org.apache.dubbo.config.ServiceConfig; +import org.apache.dubbo.event.Event; + +/** + * {@link ServiceConfig} event post-{@link ServiceConfig#export() export} + * + * @since 2.7.2 + */ +public class ServiceConfigExportedEvent extends Event { + + public ServiceConfigExportedEvent(ServiceConfig source) { + super(source); + } + + public ServiceConfig getServiceConfig() { + return (ServiceConfig) getSource(); + } +} diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ServiceConfigUnexportedEvent.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ServiceConfigUnexportedEvent.java new file mode 100644 index 00000000000..f4914fe8034 --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ServiceConfigUnexportedEvent.java @@ -0,0 +1,36 @@ +/* + * 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.config.event; + +import org.apache.dubbo.config.ServiceConfig; +import org.apache.dubbo.event.Event; + +/** + * {@link ServiceConfig} event post-{@link ServiceConfig#unexport() unexport} + * + * @since 2.7.2 + */ +public class ServiceConfigUnexportedEvent extends Event { + + public ServiceConfigUnexportedEvent(ServiceConfig source) { + super(source); + } + + public ServiceConfig getServiceConfig() { + return (ServiceConfig) getSource(); + } +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java index 7c4b5b49024..c4f3c639073 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java @@ -21,10 +21,14 @@ import org.apache.dubbo.config.api.DemoService; import org.apache.dubbo.config.api.Greeting; import org.apache.dubbo.config.context.ConfigManager; +import org.apache.dubbo.config.event.ServiceConfigExportedEvent; +import org.apache.dubbo.config.event.ServiceConfigUnexportedEvent; import org.apache.dubbo.config.mock.MockProtocol2; import org.apache.dubbo.config.mock.MockRegistryFactory2; import org.apache.dubbo.config.mock.TestProxyFactory; import org.apache.dubbo.config.provider.impl.DemoServiceImpl; +import org.apache.dubbo.event.EventDispatcher; +import org.apache.dubbo.event.EventListener; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; @@ -40,6 +44,7 @@ import java.util.Collections; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; @@ -47,9 +52,9 @@ import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; +import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.EXPORT_KEY; import static org.apache.dubbo.config.Constants.SHUTDOWN_TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.remoting.Constants.BIND_IP_KEY; import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; @@ -75,6 +80,8 @@ public class ServiceConfigTest { private ServiceConfig service2 = new ServiceConfig(); private ServiceConfig delayService = new ServiceConfig(); + private final EventDispatcher eventDispatcher = EventDispatcher.getDefaultExtension(); + @BeforeEach public void setUp() throws Exception { MockProtocol2.delegate = protocolDelegate; @@ -135,8 +142,20 @@ public void tearDown() { @Test public void testExport() throws Exception { + + AtomicReference reference = new AtomicReference(); + + eventDispatcher.addEventListener(new EventListener() { + @Override + public void onEvent(ServiceConfigExportedEvent event) { + reference.set(event.getServiceConfig()); + } + }); + service.export(); + assertEquals(service, reference.get()); + assertThat(service.getExportedUrls(), hasSize(1)); URL url = service.toUrl(); assertThat(url.getProtocol(), equalTo("mockprotocol2")); @@ -178,8 +197,32 @@ public void testDelayExport() throws Exception { public void testUnexport() throws Exception { System.setProperty(SHUTDOWN_WAIT_KEY, "0"); try { + AtomicReference reference = new AtomicReference(); + + eventDispatcher.addEventListener(new EventListener() { + @Override + public void onEvent(ServiceConfigExportedEvent event) { + reference.set(event.getServiceConfig()); + } + }); + service.export(); + + assertEquals(service, reference.get()); + + assertTrue(reference.compareAndSet(service, null)); + + eventDispatcher.addEventListener(new EventListener() { + @Override + public void onEvent(ServiceConfigUnexportedEvent event) { + reference.set(event.getServiceConfig()); + } + }); + service.unexport(); + + assertEquals(service, reference.get()); + Thread.sleep(1000); Mockito.verify(exporter, Mockito.atLeastOnce()).unexport(); } finally { From 737da2b9bcf12927fe9cca7c044ecc4d2635f9a3 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Tue, 21 May 2019 01:34:47 +0800 Subject: [PATCH 05/46] Polish apache/incubator-dubbo#3984 : Add Service registration and discovery implementation for Zookeeper --- .../common/function/ThrowableConsumer.java | 66 ++++++ .../common/function/ThrowableFunction.java | 71 ++++++ dubbo-dependencies-bom/pom.xml | 11 + .../dubbo-registry-zookeeper/pom.xml | 4 + .../registry/zookeeper/ZookeeperInstance.java | 77 +++++++ .../zookeeper/ZookeeperServiceDiscovery.java | 160 ++++++++++++++ ...ookeeperServiceDiscoveryChangeWatcher.java | 68 ++++++ .../util/CuratorFrameworkParams.java | 102 +++++++++ .../zookeeper/util/CuratorFrameworkUtils.java | 122 +++++++++++ .../ZookeeperServiceDiscoveryTest.java | 206 ++++++++++++++++++ 10 files changed, 887 insertions(+) create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableConsumer.java create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableFunction.java create mode 100644 dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperInstance.java create mode 100644 dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscovery.java create mode 100644 dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryChangeWatcher.java create mode 100644 dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkParams.java create mode 100644 dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtils.java create mode 100644 dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryTest.java diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableConsumer.java b/dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableConsumer.java new file mode 100644 index 00000000000..317d0456998 --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableConsumer.java @@ -0,0 +1,66 @@ +/* + * 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.common.function; + +import java.util.function.Consumer; +import java.util.function.Function; + +/** + * {@link Consumer} with {@link Throwable} + * + * @param the source type + * @see Function + * @see Throwable + * @since 2.7.2 + */ +@FunctionalInterface +public interface ThrowableConsumer { + + /** + * Applies this function to the given argument. + * + * @param t the function argument + * @throws Throwable if met with any error + */ + void accept(T t) throws Throwable; + + /** + * Executes {@link ThrowableConsumer} + * + * @param t the function argument + * @throws RuntimeException wrappers {@link Throwable} + */ + default void execute(T t) throws RuntimeException { + try { + accept(t); + } catch (Throwable e) { + throw new RuntimeException(e.getMessage(), e.getCause()); + } + } + + /** + * Executes {@link ThrowableConsumer} + * + * @param t the function argument + * @param consumer {@link ThrowableConsumer} + * @param the source type + * @return the result after execution + */ + static void execute(T t, ThrowableConsumer consumer) { + consumer.execute(t); + } +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableFunction.java b/dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableFunction.java new file mode 100644 index 00000000000..1acd3fa137f --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableFunction.java @@ -0,0 +1,71 @@ +/* + * 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.common.function; + +import java.util.function.Function; + +/** + * {@link Function} with {@link Throwable} + * + * @param the source type + * @param the return type + * @see Function + * @see Throwable + * @since 2.7.2 + */ +@FunctionalInterface +public interface ThrowableFunction { + + /** + * Applies this function to the given argument. + * + * @param t the function argument + * @return the function result + * @throws Throwable if met with any error + */ + R apply(T t) throws Throwable; + + /** + * Executes {@link ThrowableFunction} + * + * @param t the function argument + * @return the function result + * @throws RuntimeException wrappers {@link Throwable} + */ + default R execute(T t) throws RuntimeException { + R result = null; + try { + result = apply(t); + } catch (Throwable e) { + throw new RuntimeException(e.getCause()); + } + return result; + } + + /** + * Executes {@link ThrowableFunction} + * + * @param t the function argument + * @param function {@link ThrowableFunction} + * @param the source type + * @param the return type + * @return the result after execution + */ + static R execute(T t, ThrowableFunction function) { + return function.execute(t); + } +} diff --git a/dubbo-dependencies-bom/pom.xml b/dubbo-dependencies-bom/pom.xml index ef42a6e4517..e250644f506 100644 --- a/dubbo-dependencies-bom/pom.xml +++ b/dubbo-dependencies-bom/pom.xml @@ -228,6 +228,17 @@ + + org.apache.curator + curator-x-discovery + ${curator_version} + + + org.apache.zookeeper + zookeeper + + + redis.clients jedis diff --git a/dubbo-registry/dubbo-registry-zookeeper/pom.xml b/dubbo-registry/dubbo-registry-zookeeper/pom.xml index 3aa13d3fcfd..cf3a1a90e1d 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/pom.xml +++ b/dubbo-registry/dubbo-registry-zookeeper/pom.xml @@ -39,6 +39,10 @@ dubbo-remoting-zookeeper ${project.parent.version} + + org.apache.curator + curator-x-discovery + org.apache.curator curator-test diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperInstance.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperInstance.java new file mode 100644 index 00000000000..71cca53a394 --- /dev/null +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperInstance.java @@ -0,0 +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.registry.zookeeper; + +import java.util.HashMap; +import java.util.Map; + +/** + * Represents the default payload of a registered service in Zookeeper. + *

+ * It's compatible with Spring Cloud + * + * @since 2.7.2 + */ +public class ZookeeperInstance { + + private String id; + + private String name; + + private Map metadata = new HashMap<>(); + + @SuppressWarnings("unused") + private ZookeeperInstance() { + } + + public ZookeeperInstance(String id, String name, Map metadata) { + this.id = id; + this.name = name; + this.metadata = metadata; + } + + public String getId() { + return this.id; + } + + public String getName() { + return this.name; + } + + public void setId(String id) { + this.id = id; + } + + public void setName(String name) { + this.name = name; + } + + public Map getMetadata() { + return this.metadata; + } + + public void setMetadata(Map metadata) { + this.metadata = metadata; + } + + @Override + public String toString() { + return "ZookeeperInstance{" + "id='" + this.id + '\'' + ", name='" + this.name + + '\'' + ", metadata=" + this.metadata + '}'; + } + +} diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscovery.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscovery.java new file mode 100644 index 00000000000..d9d6df0c35f --- /dev/null +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscovery.java @@ -0,0 +1,160 @@ +/* + * 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.zookeeper; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.function.ThrowableConsumer; +import org.apache.dubbo.common.function.ThrowableFunction; +import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.event.EventDispatcher; +import org.apache.dubbo.registry.client.EventPublishingServiceRegistry; +import org.apache.dubbo.registry.client.ServiceDiscovery; +import org.apache.dubbo.registry.client.ServiceInstance; +import org.apache.dubbo.registry.client.event.ServiceDiscoveryChangeListener; + +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.api.CuratorWatcher; +import org.apache.zookeeper.KeeperException; + +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import static org.apache.dubbo.common.function.ThrowableFunction.execute; +import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.ROOT_PATH; +import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkUtils.build; +import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkUtils.buildCuratorFramework; +import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkUtils.buildServiceDiscovery; + +/** + * Zookeeper {@link ServiceDiscovery} implementation based on + * Apache Curator X Discovery + */ +public class ZookeeperServiceDiscovery extends EventPublishingServiceRegistry implements ServiceDiscovery { + + private final Logger logger = LoggerFactory.getLogger(getClass()); + + private final CuratorFramework curatorFramework; + + private final String rootPath; + + private final org.apache.curator.x.discovery.ServiceDiscovery serviceDiscovery; + + private final EventDispatcher dispatcher; + + /** + * The Key is watched Zookeeper path, the value is an instance of {@link CuratorWatcher} + */ + private final Map watcherCaches = new ConcurrentHashMap<>(); + + public ZookeeperServiceDiscovery(URL registerURL) throws Exception { + this.curatorFramework = buildCuratorFramework(registerURL); + this.rootPath = ROOT_PATH.getParameterValue(registerURL); + this.serviceDiscovery = buildServiceDiscovery(curatorFramework, rootPath); + this.dispatcher = EventDispatcher.getDefaultExtension(); + } + + @Override + protected void doRegister(ServiceInstance serviceInstance) throws RuntimeException { + doInServiceRegistry(serviceDiscovery -> { + serviceDiscovery.registerService(build(serviceInstance)); + }); + } + + @Override + protected void doUpdate(ServiceInstance serviceInstance) throws RuntimeException { + doInServiceRegistry(serviceDiscovery -> { + serviceDiscovery.updateService(build(serviceInstance)); + }); + } + + @Override + protected void doUnregister(ServiceInstance serviceInstance) throws RuntimeException { + doInServiceRegistry(serviceDiscovery -> { + serviceDiscovery.unregisterService(build(serviceInstance)); + }); + } + + @Override + protected void doStart() { + doInServiceRegistry(serviceDiscovery -> { + serviceDiscovery.start(); + }); + } + + @Override + protected void doStop() { + doInServiceRegistry(serviceDiscovery -> { + serviceDiscovery.close(); + }); + } + + @Override + public Set getServices() { + return doInServiceDiscovery(s -> new LinkedHashSet<>(s.queryForNames())); + } + + @Override + public List getInstances(String serviceName) throws NullPointerException { + return doInServiceDiscovery(s -> build(s.queryForInstances(serviceName))); + } + + @Override + public void addServiceDiscoveryChangeListener(String serviceName, ServiceDiscoveryChangeListener listener) + throws NullPointerException, IllegalArgumentException { + addServiceWatcherIfAbsent(serviceName); + dispatcher.addEventListener(listener); + } + + private void doInServiceRegistry(ThrowableConsumer consumer) { + ThrowableConsumer.execute(serviceDiscovery, s -> { + consumer.accept(s); + }); + } + + private R doInServiceDiscovery(ThrowableFunction function) { + return execute(serviceDiscovery, function); + } + + private void addWatcherIfAbsent(String path, CuratorWatcher watcher) { + if (!watcherCaches.containsKey(path)) { + try { + curatorFramework.getChildren().usingWatcher(watcher).forPath(path); + watcherCaches.put(path, watcher); + } catch (KeeperException.NoNodeException e) { + // ignored + if (logger.isErrorEnabled()) { + logger.error(e.getMessage()); + } + } catch (Exception e) { + throw new IllegalStateException(e.getMessage(), e); + } + } + } + + private void addServiceWatcherIfAbsent(String serviceName) { + addWatcherIfAbsent(buildServicePath(serviceName), + new ZookeeperServiceDiscoveryChangeWatcher(this, serviceName, dispatcher)); + } + + private String buildServicePath(String serviceName) { + return rootPath + "/" + serviceName; + } +} \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryChangeWatcher.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryChangeWatcher.java new file mode 100644 index 00000000000..8e055b65b6d --- /dev/null +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryChangeWatcher.java @@ -0,0 +1,68 @@ +/* + * 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.zookeeper; + +import org.apache.dubbo.event.EventDispatcher; +import org.apache.dubbo.registry.client.ServiceDiscovery; +import org.apache.dubbo.registry.client.ServiceInstance; +import org.apache.dubbo.registry.client.event.ServiceDiscoveryChangeEvent; + +import org.apache.curator.framework.api.CuratorWatcher; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher; + +import java.util.Collection; + +import static org.apache.zookeeper.Watcher.Event.EventType.NodeChildrenChanged; +import static org.apache.zookeeper.Watcher.Event.EventType.NodeDataChanged; + +/** + * Zookeeper {@link ServiceDiscovery} Change {@link CuratorWatcher watcher} only interests in + * {@link Watcher.Event.EventType#NodeChildrenChanged} and {@link Watcher.Event.EventType#NodeDataChanged} event types, + * which will multicast a {@link ServiceDiscoveryChangeEvent} when the service node has been changed. + * + * @since 2.7.2 + */ +public class ZookeeperServiceDiscoveryChangeWatcher implements CuratorWatcher { + + private final ZookeeperServiceDiscovery zookeeperServiceDiscovery; + + private final String serviceName; + + private final EventDispatcher dispatcher; + + public ZookeeperServiceDiscoveryChangeWatcher(ZookeeperServiceDiscovery zookeeperServiceDiscovery, + String serviceName, EventDispatcher dispatcher) { + this.zookeeperServiceDiscovery = zookeeperServiceDiscovery; + this.serviceName = serviceName; + this.dispatcher = dispatcher; + } + + @Override + public void process(WatchedEvent event) throws Exception { + + Watcher.Event.EventType eventType = event.getType(); + + if (NodeChildrenChanged.equals(eventType) || NodeDataChanged.equals(eventType)) { + dispatcher.dispatch(new ServiceDiscoveryChangeEvent(serviceName, getServiceInstances(serviceName))); + } + } + + private Collection getServiceInstances(String serviceName) { + return zookeeperServiceDiscovery.getInstances(serviceName); + } +} diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkParams.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkParams.java new file mode 100644 index 00000000000..7e9db4c54e6 --- /dev/null +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkParams.java @@ -0,0 +1,102 @@ +/* + * 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.zookeeper.util; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.registry.client.ServiceInstance; + +import org.apache.curator.framework.CuratorFramework; + +import java.util.concurrent.TimeUnit; +import java.util.function.Function; + +/** + * The enumeration for the parameters of {@link CuratorFramework} + * + * @see CuratorFramework + * @since 2.7.2 + */ +public enum CuratorFrameworkParams { + + /** + * The root path of Dubbo Service + */ + ROOT_PATH("rootPath", "/services", value -> value), + + /** + * The host of current {@link ServiceInstance service instance} that will be registered + */ + INSTANCE_HOST("instanceHost", null, value -> value), + + /** + * The port of current {@link ServiceInstance service instance} that will be registered + */ + INSTANCE_PORT("instancePort", null, value -> value), + + /** + * Initial amount of time to wait between retries + */ + BASE_SLEEP_TIME("baseSleepTimeMs", 50, Integer::valueOf), + + /** + * Max number of times to retry. + */ + MAX_RETRIES("maxRetries", 10, Integer::valueOf), + + /** + * Max time in ms to sleep on each retry. + */ + MAX_SLEEP("maxSleepMs", 500, Integer::valueOf), + + /** + * Wait time to block on connection to Zookeeper. + */ + BLOCK_UNTIL_CONNECTED_WAIT("blockUntilConnectedWait", 10, Integer::valueOf), + + /** + * The unit of time related to blocking on connection to Zookeeper. + */ + BLOCK_UNTIL_CONNECTED_UNIT("blockUntilConnectedUnit", TimeUnit.SECONDS, TimeUnit::valueOf), + + ; + + private final String name; + + private final Object defaultValue; + + private final Function converter; + + CuratorFrameworkParams(String name, T defaultValue, Function converter) { + this.name = name; + this.defaultValue = defaultValue; + this.converter = (Function) converter; + } + + /** + * Get the parameter value from the specified {@link URL} + * + * @param url the Dubbo registry {@link URL} + * @param the type of value + * @return the parameter value if present, or return null + */ + public T getParameterValue(URL url) { + String param = url.getParameter(name); + Object value = param != null ? converter.apply(param) : defaultValue; + return (T) value; + } +} + diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtils.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtils.java new file mode 100644 index 00000000000..bc466b8dcdd --- /dev/null +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtils.java @@ -0,0 +1,122 @@ +/* + * 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.zookeeper.util; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.registry.client.DefaultServiceInstance; +import org.apache.dubbo.registry.client.ServiceInstance; +import org.apache.dubbo.registry.zookeeper.ZookeeperInstance; +import org.apache.dubbo.registry.zookeeper.ZookeeperServiceDiscovery; + +import org.apache.curator.RetryPolicy; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.CuratorFrameworkFactory; +import org.apache.curator.retry.ExponentialBackoffRetry; +import org.apache.curator.x.discovery.ServiceDiscovery; +import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; +import org.apache.curator.x.discovery.ServiceInstanceBuilder; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.apache.curator.x.discovery.ServiceInstance.builder; +import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.BASE_SLEEP_TIME; +import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.BLOCK_UNTIL_CONNECTED_UNIT; +import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.BLOCK_UNTIL_CONNECTED_WAIT; +import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.MAX_RETRIES; +import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.MAX_SLEEP; + +/** + * Curator Framework Utilities Class + * + * @since 2.7.2 + */ +public abstract class CuratorFrameworkUtils { + + public static ZookeeperServiceDiscovery buildZookeeperServiceDiscovery(URL registerURL) throws Exception { + return new ZookeeperServiceDiscovery(registerURL); + } + + public static ServiceDiscovery buildServiceDiscovery(CuratorFramework curatorFramework, + String basePath) { + return ServiceDiscoveryBuilder.builder(ZookeeperInstance.class) + .client(curatorFramework) + .basePath(basePath) + .build(); + } + + public static CuratorFramework buildCuratorFramework(URL registerURL) throws Exception { + CuratorFramework curatorFramework = CuratorFrameworkFactory.builder() + .connectString(registerURL.getIp() + ":" + registerURL.getPort()) + .retryPolicy(buildRetryPolicy(registerURL)) + .build(); + curatorFramework.start(); + curatorFramework.blockUntilConnected(BLOCK_UNTIL_CONNECTED_WAIT.getParameterValue(registerURL), + BLOCK_UNTIL_CONNECTED_UNIT.getParameterValue(registerURL)); + return curatorFramework; + } + + public static RetryPolicy buildRetryPolicy(URL registerURL) { + int baseSleepTimeMs = BASE_SLEEP_TIME.getParameterValue(registerURL); + int maxRetries = MAX_RETRIES.getParameterValue(registerURL); + int getMaxSleepMs = MAX_SLEEP.getParameterValue(registerURL); + return new ExponentialBackoffRetry(baseSleepTimeMs, maxRetries, getMaxSleepMs); + } + + + public static List build(Collection> + instances) { + return instances.stream().map(CuratorFrameworkUtils::build).collect(Collectors.toList()); + } + + public static ServiceInstance build(org.apache.curator.x.discovery.ServiceInstance instance) { + String name = instance.getName(); + String host = instance.getAddress(); + int port = instance.getPort(); + ZookeeperInstance zookeeperInstance = instance.getPayload(); + DefaultServiceInstance serviceInstance = new DefaultServiceInstance(instance.getId(), name, host, port); + serviceInstance.setMetadata(zookeeperInstance.getMetadata()); + return serviceInstance; + } + + public static org.apache.curator.x.discovery.ServiceInstance build(ServiceInstance serviceInstance) { + ServiceInstanceBuilder builder = null; + String serviceName = serviceInstance.getServiceName(); + String host = serviceInstance.getHost(); + int port = serviceInstance.getPort(); + Map metadata = serviceInstance.getMetadata(); + String id = generateId(host, port); + ZookeeperInstance zookeeperInstance = new ZookeeperInstance(null, serviceName, metadata); + try { + builder = builder() + .id(id) + .name(serviceName) + .address(host) + .port(port) + .payload(zookeeperInstance); + } catch (Exception e) { + throw new RuntimeException(e); + } + return builder.build(); + } + + public static final String generateId(String host, int port) { + return host + ":" + port; + } +} diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryTest.java b/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryTest.java new file mode 100644 index 00000000000..e74425f9f2a --- /dev/null +++ b/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryTest.java @@ -0,0 +1,206 @@ +/* + * 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.zookeeper; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.utils.Page; +import org.apache.dubbo.registry.client.DefaultServiceInstance; +import org.apache.dubbo.registry.client.ServiceInstance; + +import org.apache.curator.test.TestingServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; + +import static java.util.Arrays.asList; +import static org.apache.dubbo.common.utils.NetUtils.getAvailablePort; +import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkUtils.buildZookeeperServiceDiscovery; +import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkUtils.generateId; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@link ZookeeperServiceDiscovery} Test + * + * @since 2.7.2 + */ +public class ZookeeperServiceDiscoveryTest { + + private static final String SERVICE_NAME = "A"; + + private static final String LOCALHOST = "127.0.0.1"; + + private TestingServer zkServer; + private int zkServerPort; + private URL registryUrl; + + private ZookeeperServiceDiscovery discovery; + + @BeforeEach + public void init() throws Exception { + zkServerPort = getAvailablePort(); + zkServer = new TestingServer(zkServerPort, true); + zkServer.start(); + + this.registryUrl = URL.valueOf("zookeeper://127.0.0.1:" + zkServerPort); + this.discovery = buildZookeeperServiceDiscovery(registryUrl); + this.discovery.start(); + } + + @AfterEach + public void close() throws IOException { + discovery.stop(); + zkServer.stop(); + } + + @Test + public void testRegistration() { + + DefaultServiceInstance serviceInstance = createServiceInstance(SERVICE_NAME, LOCALHOST, 8080); + + discovery.register(serviceInstance); + + List serviceInstances = discovery.getInstances(SERVICE_NAME); + + assertTrue(serviceInstances.contains(serviceInstance)); + assertEquals(asList(serviceInstance), serviceInstances); + + Map metadata = new HashMap<>(); + metadata.put("message", "Hello,World"); + serviceInstance.setMetadata(metadata); + + discovery.update(serviceInstance); + + serviceInstances = discovery.getInstances(SERVICE_NAME); + + assertEquals(serviceInstance, serviceInstances.get(0)); + + discovery.unregister(serviceInstance); + + serviceInstances = discovery.getInstances(SERVICE_NAME); + + assertTrue(serviceInstances.isEmpty()); + } + + private DefaultServiceInstance createServiceInstance(String serviceName, String host, int port) { + return new DefaultServiceInstance(generateId(host, port), serviceName, host, port); + } + + @Test + public void testGetInstances() throws InterruptedException { + + List instances = asList( + createServiceInstance(SERVICE_NAME, LOCALHOST, 8080), + createServiceInstance(SERVICE_NAME, LOCALHOST, 8081), + createServiceInstance(SERVICE_NAME, LOCALHOST, 8082) + ); + + instances.forEach(discovery::register); + + List serviceInstances = new LinkedList<>(); + + CountDownLatch latch = new CountDownLatch(1); + + // Add Listener + discovery.addServiceDiscoveryChangeListener(SERVICE_NAME, event -> { + serviceInstances.addAll(event.getServiceInstances()); + latch.countDown(); + }); + + discovery.register(createServiceInstance(SERVICE_NAME, LOCALHOST, 8082)); + discovery.update(createServiceInstance(SERVICE_NAME, LOCALHOST, 8082)); + + latch.await(); + + assertFalse(serviceInstances.isEmpty()); + + // offset starts 0 + int offset = 0; + // requestSize > total elements + int requestSize = 5; + + Page page = discovery.getInstances(SERVICE_NAME, offset, requestSize); + assertEquals(0, page.getRequestOffset()); + assertEquals(5, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(3, page.getData().size()); + assertTrue(page.hasData()); + + for (ServiceInstance instance : page.getData()) { + assertTrue(instances.contains(instance)); + } + + // requestSize < total elements + requestSize = 2; + + page = discovery.getInstances(SERVICE_NAME, offset, requestSize); + assertEquals(0, page.getRequestOffset()); + assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(2, page.getData().size()); + assertTrue(page.hasData()); + + for (ServiceInstance instance : page.getData()) { + assertTrue(instances.contains(instance)); + } + + offset = 1; + page = discovery.getInstances(SERVICE_NAME, offset, requestSize); + assertEquals(1, page.getRequestOffset()); + assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(2, page.getData().size()); + assertTrue(page.hasData()); + + for (ServiceInstance instance : page.getData()) { + assertTrue(instances.contains(instance)); + } + + offset = 2; + page = discovery.getInstances(SERVICE_NAME, offset, requestSize); + assertEquals(2, page.getRequestOffset()); + assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(1, page.getData().size()); + assertTrue(page.hasData()); + + offset = 3; + page = discovery.getInstances(SERVICE_NAME, offset, requestSize); + assertEquals(3, page.getRequestOffset()); + assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(0, page.getData().size()); + assertFalse(page.hasData()); + + offset = 5; + page = discovery.getInstances(SERVICE_NAME, offset, requestSize); + assertEquals(5, page.getRequestOffset()); + assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getTotalSize()); + assertEquals(0, page.getData().size()); + assertFalse(page.hasData()); + + } +} From 839f7a34451560f75a71eb3f7e6f0b70f94b8718 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Tue, 21 May 2019 10:24:02 +0800 Subject: [PATCH 06/46] Polish apache/incubator-dubbo#4104 : To add initialized and destroyed events for ReferenceConfig --- .../apache/dubbo/config/ReferenceConfig.java | 37 +++++++++++--- .../event/ReferenceConfigDestroyedEvent.java | 41 ++++++++++++++++ .../ReferenceConfigInitializedEvent.java | 48 +++++++++++++++++++ .../dubbo/config/ReferenceConfigTest.java | 48 ++++++++++++++++--- 4 files changed, 162 insertions(+), 12 deletions(-) create mode 100644 dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ReferenceConfigDestroyedEvent.java create mode 100644 dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ReferenceConfigInitializedEvent.java diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index 45f24cf0657..b5b7c0f8f3a 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -27,7 +27,11 @@ import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.context.ConfigManager; +import org.apache.dubbo.config.event.ReferenceConfigDestroyedEvent; +import org.apache.dubbo.config.event.ReferenceConfigInitializedEvent; import org.apache.dubbo.config.support.Parameter; +import org.apache.dubbo.event.Event; +import org.apache.dubbo.event.EventDispatcher; import org.apache.dubbo.metadata.integration.MetadataReportService; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Invoker; @@ -62,18 +66,18 @@ import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SEMICOLON_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.CLUSTER_KEY; -import static org.apache.dubbo.config.Constants.DUBBO_IP_TO_REGISTRY; -import static org.apache.dubbo.common.constants.RegistryConstants.REFER_KEY; -import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.REFER_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; -import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL; import static org.apache.dubbo.common.utils.NetUtils.isInvalidLocalHost; +import static org.apache.dubbo.config.Constants.DUBBO_IP_TO_REGISTRY; +import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY; +import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL; /** * ReferenceConfig @@ -117,6 +121,11 @@ public class ReferenceConfig extends AbstractReferenceConfig { */ private final List urls = new ArrayList(); + /** + * The {@link EventDispatcher} + */ + private final EventDispatcher eventDispatcher = EventDispatcher.getDefaultExtension(); + /** * The interface name of the reference service */ @@ -267,6 +276,9 @@ public synchronized void destroy() { } invoker = null; ref = null; + + // dispatch a ReferenceConfigDestroyedEvent since 2.7.2 + dispatch(new ReferenceConfigDestroyedEvent(this)); } private void init() { @@ -331,6 +343,9 @@ private void init() { String serviceKey = URL.buildKey(interfaceName, group, version); ApplicationModel.initConsumerModel(serviceKey, buildConsumerModel(serviceKey, attributes)); initialized = true; + + // dispatch a ReferenceConfigInitializedEvent since 2.7.2 + dispatch(new ReferenceConfigInitializedEvent(this, invoker)); } private ConsumerModel buildConsumerModel(String serviceKey, Map attributes) { @@ -373,7 +388,7 @@ private T createProxy(Map map) { } } else { // assemble URL from register center's configuration // if protocols not injvm checkRegistry - if (!LOCAL_PROTOCOL.equalsIgnoreCase(getProtocol())){ + if (!LOCAL_PROTOCOL.equalsIgnoreCase(getProtocol())) { checkRegistry(); List us = loadRegistries(false); if (CollectionUtils.isNotEmpty(us)) { @@ -660,4 +675,14 @@ private void resolveFile() { } } } + + /** + * Dispatch an {@link Event event} + * + * @param event an {@link Event event} + * @since 2.7.2 + */ + protected void dispatch(Event event) { + eventDispatcher.dispatch(event); + } } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ReferenceConfigDestroyedEvent.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ReferenceConfigDestroyedEvent.java new file mode 100644 index 00000000000..58b871ea7e9 --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ReferenceConfigDestroyedEvent.java @@ -0,0 +1,41 @@ +/* + * 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.config.event; + +import org.apache.dubbo.config.ReferenceConfig; +import org.apache.dubbo.config.annotation.Reference; +import org.apache.dubbo.event.Event; + +/** + * The {@link ReferenceConfig Dubbo service ReferenceConfig} destroyed {@link Event event} + * + * @see Reference + * @see ReferenceConfig#destroy() + * @see Event + * @since 2.7.2 + */ +public class ReferenceConfigDestroyedEvent extends Event { + + public ReferenceConfigDestroyedEvent(ReferenceConfig referenceConfig) { + super(referenceConfig); + } + + public ReferenceConfig getReferenceConfig() { + return (ReferenceConfig) getSource(); + } + +} \ No newline at end of file diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ReferenceConfigInitializedEvent.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ReferenceConfigInitializedEvent.java new file mode 100644 index 00000000000..dcf02cfec77 --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ReferenceConfigInitializedEvent.java @@ -0,0 +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.config.event; + +import org.apache.dubbo.config.ReferenceConfig; +import org.apache.dubbo.config.annotation.Reference; +import org.apache.dubbo.event.Event; +import org.apache.dubbo.rpc.Invoker; + +/** + * The {@link ReferenceConfig Dubbo service ReferenceConfig} initialized {@link Event event} + * + * @see Reference + * @see ReferenceConfig#get() + * @see Event + * @since 2.7.2 + */ +public class ReferenceConfigInitializedEvent extends Event { + + private final Invoker invoker; + + public ReferenceConfigInitializedEvent(ReferenceConfig referenceConfig, Invoker invoker) { + super(referenceConfig); + this.invoker = invoker; + } + + public ReferenceConfig getReferenceConfig() { + return (ReferenceConfig) getSource(); + } + + public Invoker getInvoker() { + return invoker; + } +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java index d1e02636dd7..f9afb355945 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java @@ -21,20 +21,30 @@ import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.api.DemoService; import org.apache.dubbo.config.context.ConfigManager; +import org.apache.dubbo.config.event.ReferenceConfigDestroyedEvent; +import org.apache.dubbo.config.event.ReferenceConfigInitializedEvent; import org.apache.dubbo.config.provider.impl.DemoServiceImpl; +import org.apache.dubbo.event.EventDispatcher; +import org.apache.dubbo.event.EventListener; 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.concurrent.atomic.AtomicReference; + import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL; +import static org.junit.jupiter.api.Assertions.assertEquals; public class ReferenceConfigTest { + private final EventDispatcher eventDispatcher = EventDispatcher.getDefaultExtension(); + @BeforeEach public void setUp() { ConfigManager.getInstance().clear(); + eventDispatcher.removeAllEventListeners(); } @AfterEach @@ -67,12 +77,38 @@ public void testInjvm() throws Exception { rc.setInterface(DemoService.class.getName()); rc.setInjvm(false); + AtomicReference reference = new AtomicReference<>(); + + eventDispatcher.addEventListener(new EventListener() { + @Override + public void onEvent(ReferenceConfigInitializedEvent event) { + reference.set(event.getReferenceConfig()); + } + }); + try { System.setProperty("java.net.preferIPv4Stack", "true"); demoService.export(); rc.get(); + + assertEquals(rc, reference.get()); + + reference.compareAndSet(rc, null); + Assertions.assertTrue(!LOCAL_PROTOCOL.equalsIgnoreCase( rc.getInvoker().getUrl().getProtocol())); + + eventDispatcher.addEventListener(new EventListener() { + @Override + public void onEvent(ReferenceConfigDestroyedEvent event) { + reference.set(event.getReferenceConfig()); + } + }); + + rc.destroy(); + + assertEquals(rc, reference.get()); + } finally { System.clearProperty("java.net.preferIPv4Stack"); demoService.unexport(); @@ -134,17 +170,17 @@ public void testConstructWithReferenceAnnotation() throws NoSuchFieldException { Reference reference = getClass().getDeclaredField("innerTest").getAnnotation(Reference.class); ReferenceConfig referenceConfig = new ReferenceConfig(reference); Assertions.assertTrue(referenceConfig.getMethods().size() == 1); - Assertions.assertEquals(((MethodConfig) referenceConfig.getMethods().get(0)).getName(), "sayHello"); + assertEquals(((MethodConfig) referenceConfig.getMethods().get(0)).getName(), "sayHello"); Assertions.assertTrue(((MethodConfig) referenceConfig.getMethods().get(0)).getTimeout() == 1300); Assertions.assertTrue(((MethodConfig) referenceConfig.getMethods().get(0)).getRetries() == 4); - Assertions.assertEquals(((MethodConfig) referenceConfig.getMethods().get(0)).getLoadbalance(), "random"); + assertEquals(((MethodConfig) referenceConfig.getMethods().get(0)).getLoadbalance(), "random"); Assertions.assertTrue(((MethodConfig) referenceConfig.getMethods().get(0)).getActives() == 3); Assertions.assertTrue(((MethodConfig) referenceConfig.getMethods().get(0)).getExecutes() == 5); Assertions.assertTrue(((MethodConfig) referenceConfig.getMethods().get(0)).isAsync()); - Assertions.assertEquals(((MethodConfig) referenceConfig.getMethods().get(0)).getOninvoke(), "i"); - Assertions.assertEquals(((MethodConfig) referenceConfig.getMethods().get(0)).getOnreturn(), "r"); - Assertions.assertEquals(((MethodConfig) referenceConfig.getMethods().get(0)).getOnthrow(), "t"); - Assertions.assertEquals(((MethodConfig) referenceConfig.getMethods().get(0)).getCache(), "c"); + assertEquals(((MethodConfig) referenceConfig.getMethods().get(0)).getOninvoke(), "i"); + assertEquals(((MethodConfig) referenceConfig.getMethods().get(0)).getOnreturn(), "r"); + assertEquals(((MethodConfig) referenceConfig.getMethods().get(0)).getOnthrow(), "t"); + assertEquals(((MethodConfig) referenceConfig.getMethods().get(0)).getCache(), "c"); } From bc41e2d00c98a2d2e44a7c175e69a7d699bf78ba Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Tue, 21 May 2019 10:53:31 +0800 Subject: [PATCH 07/46] Polish apache/incubator-dubbo#3946 : Refactor Dubbo metadata service --- dubbo-metadata/pom.xml | 18 +--- .../{export => }/MetadataServiceExporter.java | 21 +---- ...bo.metadata.export.MetadataServiceExporter | 1 - .../dubbo/metadata/export/MockRegistry.java | 87 ------------------- .../metadata/export/MockRegistryFactory.java | 45 ---------- .../org.apache.dubbo.registry.RegistryFactory | 1 - 6 files changed, 4 insertions(+), 169 deletions(-) rename dubbo-metadata/src/main/java/org/apache/dubbo/metadata/{export => }/MetadataServiceExporter.java (66%) delete mode 100644 dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.export.MetadataServiceExporter delete mode 100644 dubbo-metadata/src/test/java/org/apache/dubbo/metadata/export/MockRegistry.java delete mode 100644 dubbo-metadata/src/test/java/org/apache/dubbo/metadata/export/MockRegistryFactory.java delete mode 100644 dubbo-metadata/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory diff --git a/dubbo-metadata/pom.xml b/dubbo-metadata/pom.xml index 08ff7f234e0..9b52640cbe3 100644 --- a/dubbo-metadata/pom.xml +++ b/dubbo-metadata/pom.xml @@ -32,26 +32,12 @@ The metadata module of Dubbo project - - org.apache.dubbo - dubbo-config-api - ${revision} - true - - org.apache.dubbo - dubbo-rpc-dubbo + dubbo-rpc-api ${revision} - test - - - - org.apache.dubbo - dubbo-remoting-netty4 - ${revision} - test + true diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/export/MetadataServiceExporter.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceExporter.java similarity index 66% rename from dubbo-metadata/src/main/java/org/apache/dubbo/metadata/export/MetadataServiceExporter.java rename to dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceExporter.java index b99727a7267..5f756a2b76c 100644 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/export/MetadataServiceExporter.java +++ b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceExporter.java @@ -14,17 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metadata.export; +package org.apache.dubbo.metadata; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.extension.SPI; -import org.apache.dubbo.metadata.MetadataService; import java.util.List; -import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; - /** * The exporter of {@link MetadataService} * @@ -33,7 +29,7 @@ * @see #unexport() * @since 2.7.2 */ -@SPI("default") +@SPI public interface MetadataServiceExporter { /** @@ -47,17 +43,4 @@ public interface MetadataServiceExporter { * Unexports the {@link MetadataService} */ void unexport(); - - - /** - * Get {@link ExtensionLoader#getDefaultExtension() the defautl extension} of {@link MetadataServiceExporter} - * - * @return non-null - * @see MetadataServiceExporter - * @see ConfigurableMetadataServiceExporter - * @see ExtensionLoader - */ - static MetadataServiceExporter getDefaultExtension() { - return getExtensionLoader(MetadataServiceExporter.class).getDefaultExtension(); - } } diff --git a/dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.export.MetadataServiceExporter b/dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.export.MetadataServiceExporter deleted file mode 100644 index fd3aaa3a0bf..00000000000 --- a/dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.export.MetadataServiceExporter +++ /dev/null @@ -1 +0,0 @@ -default=org.apache.dubbo.metadata.export.ConfigurableMetadataServiceExporter \ No newline at end of file diff --git a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/export/MockRegistry.java b/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/export/MockRegistry.java deleted file mode 100644 index 5d30385115d..00000000000 --- a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/export/MockRegistry.java +++ /dev/null @@ -1,87 +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.export; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.registry.NotifyListener; -import org.apache.dubbo.registry.Registry; - -import java.util.ArrayList; -import java.util.List; - -public class MockRegistry implements Registry { - - private URL url; - - private List registered = new ArrayList(); - - private List subscribered = new ArrayList(); - - public MockRegistry(URL url) { - if (url == null) { - throw new NullPointerException(); - } - this.url = url; - } - - public List getRegistered() { - return registered; - } - - public List getSubscribered() { - return subscribered; - } - - public URL getUrl() { - return url; - } - - @Override - public boolean isAvailable() { - return true; - } - - @Override - public void destroy() { - - } - - @Override - public void register(URL url) { - registered.add(url); - } - - @Override - public void unregister(URL url) { - registered.remove(url); - } - - @Override - public void subscribe(URL url, NotifyListener listener) { - subscribered.add(url); - } - - @Override - public void unsubscribe(URL url, NotifyListener listener) { - subscribered.remove(url); - } - - @Override - public List lookup(URL url) { - return null; - } -} diff --git a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/export/MockRegistryFactory.java b/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/export/MockRegistryFactory.java deleted file mode 100644 index fbbae0cc7a5..00000000000 --- a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/export/MockRegistryFactory.java +++ /dev/null @@ -1,45 +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.export; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.registry.Registry; -import org.apache.dubbo.registry.RegistryFactory; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -public class MockRegistryFactory implements RegistryFactory { - - private static final Map registries = new HashMap(); - - public static Collection getCachedRegistry() { - return registries.values(); - } - - public static void cleanCachedRegistry() { - registries.clear(); - } - - @Override - public Registry getRegistry(URL url) { - MockRegistry registry = new MockRegistry(url); - registries.put(url, registry); - return registry; - } -} diff --git a/dubbo-metadata/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory b/dubbo-metadata/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory deleted file mode 100644 index 011c931b965..00000000000 --- a/dubbo-metadata/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory +++ /dev/null @@ -1 +0,0 @@ -mock=org.apache.dubbo.metadata.export.MockRegistryFactory \ No newline at end of file From 4c8516c9f483e41ef52c929877ded17100b10d14 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Tue, 21 May 2019 10:55:20 +0800 Subject: [PATCH 08/46] Polish apache/incubator-dubbo#3946 : To Add MetadataServiceExporter into dubbo-config-api --- dubbo-config/dubbo-config-api/pom.xml | 10 +++++++++- .../ConfigurableMetadataServiceExporter.java | 3 ++- ...rg.apache.dubbo.metadata.MetadataServiceExporter | 1 + .../ConfigurableMetadataServiceExporterTest.java | 13 ++++++------- 4 files changed, 18 insertions(+), 9 deletions(-) rename {dubbo-metadata/src/main/java/org/apache/dubbo/metadata/export => dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata}/ConfigurableMetadataServiceExporter.java (97%) create mode 100644 dubbo-config/dubbo-config-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.MetadataServiceExporter rename {dubbo-metadata/src/test/java/org/apache/dubbo/metadata/export => dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metadata}/ConfigurableMetadataServiceExporterTest.java (86%) diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml index 3a4584d90c3..0b145d8cb22 100644 --- a/dubbo-config/dubbo-config-api/pom.xml +++ b/dubbo-config/dubbo-config-api/pom.xml @@ -14,7 +14,8 @@ See the License for the specific language governing permissions and limitations under the License. --> - + 4.0.0 org.apache.dubbo @@ -64,6 +65,13 @@ dubbo-filter-cache ${project.parent.version} + + + org.apache.dubbo + dubbo-metadata + ${project.parent.version} + + org.apache.dubbo diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/export/ConfigurableMetadataServiceExporter.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java similarity index 97% rename from dubbo-metadata/src/main/java/org/apache/dubbo/metadata/export/ConfigurableMetadataServiceExporter.java rename to dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java index b15a025ecef..d3e4226767a 100644 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/export/ConfigurableMetadataServiceExporter.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metadata.export; +package org.apache.dubbo.config.metadata; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; @@ -27,6 +27,7 @@ import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.metadata.LocalMetadataService; import org.apache.dubbo.metadata.MetadataService; +import org.apache.dubbo.metadata.MetadataServiceExporter; import java.util.ArrayList; import java.util.List; diff --git a/dubbo-config/dubbo-config-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.MetadataServiceExporter b/dubbo-config/dubbo-config-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.MetadataServiceExporter new file mode 100644 index 00000000000..30626fd41fc --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.MetadataServiceExporter @@ -0,0 +1 @@ +default=org.apache.dubbo.config.metadata.ConfigurableMetadataServiceExporter \ No newline at end of file diff --git a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/export/ConfigurableMetadataServiceExporterTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporterTest.java similarity index 86% rename from dubbo-metadata/src/test/java/org/apache/dubbo/metadata/export/ConfigurableMetadataServiceExporterTest.java rename to dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporterTest.java index 24d56ed37e4..48f3f38c068 100644 --- a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/export/ConfigurableMetadataServiceExporterTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporterTest.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metadata.export; +package org.apache.dubbo.config.metadata; import org.apache.dubbo.common.URL; import org.apache.dubbo.config.ApplicationConfig; @@ -22,6 +22,7 @@ import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.metadata.MetadataService; +import org.apache.dubbo.metadata.MetadataServiceExporter; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -31,8 +32,6 @@ import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_PROTOCOL; -import static org.apache.dubbo.metadata.export.MetadataServiceExporter.getDefaultExtension; import static org.junit.jupiter.api.Assertions.assertEquals; /** @@ -57,20 +56,20 @@ public static void init() { private static ProtocolConfig protocolConfig() { ProtocolConfig protocolConfig = new ProtocolConfig(); - protocolConfig.setName(DUBBO_PROTOCOL); + protocolConfig.setName("mockprotocol"); protocolConfig.setPort(20880); return protocolConfig; } private static RegistryConfig registryConfig() { RegistryConfig registryConfig = new RegistryConfig(); - registryConfig.setAddress("mock://127.0.0.1"); + registryConfig.setAddress("mockregistry://127.0.0.1"); return registryConfig; } @Test public void testExportAndUnexport() { - MetadataServiceExporter exporter = getDefaultExtension(); + MetadataServiceExporter exporter = new ConfigurableMetadataServiceExporter(); List urls = exporter.export(); assertEquals(1, urls.size()); @@ -81,7 +80,7 @@ public void testExportAndUnexport() { assertEquals(MetadataService.class.getName(), url.getServiceInterface()); assertEquals("test", url.getParameter(GROUP_KEY)); assertEquals(MetadataService.VERSION, url.getParameter(VERSION_KEY)); - assertEquals(DUBBO_PROTOCOL, url.getProtocol()); + assertEquals("mockprotocol", url.getProtocol()); exporter.unexport(); } From ab6a81827041443e6cbabbcc79ddea65373ed157 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Tue, 21 May 2019 10:57:06 +0800 Subject: [PATCH 09/46] Update ${project.parent.version} --- dubbo-event/pom.xml | 2 +- dubbo-metadata/pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dubbo-event/pom.xml b/dubbo-event/pom.xml index 7f30db48794..017f0e79fde 100644 --- a/dubbo-event/pom.xml +++ b/dubbo-event/pom.xml @@ -35,7 +35,7 @@ org.apache.dubbo dubbo-common - ${revision} + ${project.parent.version} true diff --git a/dubbo-metadata/pom.xml b/dubbo-metadata/pom.xml index 9b52640cbe3..144ca1fda49 100644 --- a/dubbo-metadata/pom.xml +++ b/dubbo-metadata/pom.xml @@ -36,7 +36,7 @@ org.apache.dubbo dubbo-rpc-api - ${revision} + ${project.parent.version} true From beb570d4941a2c53471a591b189ae66469d88ce3 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Tue, 21 May 2019 23:37:35 +0800 Subject: [PATCH 10/46] Polish apache/incubator-dubbo#3946 : Refactor Dubbo metadata service --- .../apache/dubbo/metadata/MetadataService.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataService.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataService.java index a1cf75db8f1..4cbbae57835 100644 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataService.java +++ b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataService.java @@ -19,6 +19,9 @@ import org.apache.dubbo.common.URL; import java.util.List; +import java.util.stream.Collectors; + +import static java.util.stream.StreamSupport.stream; /** * A framework interface of Dubbo Metadata Service defines the contract of Dubbo Services registartion and subscription @@ -132,4 +135,17 @@ default List getExportedURLs(String serviceInterface, String group, Stri * @see URL */ List getExportedURLs(String serviceInterface, String group, String version, String protocol); + + + /** + * Convert the multiple {@link URL urls} to a {@link List list} of {@link URL urls} + * + * @param urls the strings presents the {@link URL Dubbo URLs} + * @return non-null + */ + static List toURLs(Iterable urls) { + return stream(urls.spliterator(), false) + .map(URL::valueOf) + .collect(Collectors.toList()); + } } From f4a54909d0deee69fcc4cef48a893baf3f7b0e55 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Wed, 22 May 2019 14:18:43 +0800 Subject: [PATCH 11/46] Polish apache/incubator-dubbo/#4096 : Remove the duplicated word --- .../src/main/java/org/apache/dubbo/event/Listenable.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dubbo-event/src/main/java/org/apache/dubbo/event/Listenable.java b/dubbo-event/src/main/java/org/apache/dubbo/event/Listenable.java index 9b854ac2203..1857ac85f3f 100644 --- a/dubbo-event/src/main/java/org/apache/dubbo/event/Listenable.java +++ b/dubbo-event/src/main/java/org/apache/dubbo/event/Listenable.java @@ -69,7 +69,7 @@ default void addEventListeners(Iterable listeners) throws NullPointerExceptio } /** - * Remove a a {@link EventListener Dubbo event listener} + * Remove a {@link EventListener Dubbo event listener} * * @param listener a {@link EventListener Dubbo event listener} * @return If remove successfully, return true. From a5da6957becb253930b70702ae157a031df8734b Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Thu, 23 May 2019 09:39:18 +0800 Subject: [PATCH 12/46] Polish apache/incubator-dubbo#4119 : DynamicConfiguration adds the publish and multiple get configuration methods --- .../configcenter/DynamicConfiguration.java | 72 +++++++++++++++++-- .../support/nop/NopDynamicConfiguration.java | 21 +++++- .../nop/NopDynamicConfigurationTest.java | 70 ++++++++++++++++++ 3 files changed, 157 insertions(+), 6 deletions(-) create mode 100644 dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfigurationTest.java diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/DynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/DynamicConfiguration.java index 23fc0f5e8bd..0c833af7e82 100644 --- a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/DynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/DynamicConfiguration.java @@ -19,7 +19,12 @@ import org.apache.dubbo.common.config.Configuration; import org.apache.dubbo.common.config.Environment; +import java.util.Collections; import java.util.Optional; +import java.util.Set; +import java.util.SortedMap; +import java.util.SortedSet; +import java.util.TreeMap; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; @@ -28,12 +33,13 @@ *
* From the use scenario internally in framework, there're mainly three kinds of methods: *

    - *
  • 1. getConfig, get governance rules or single config item from Config Center.
  • - *
  • 2. getConfigFile, get configuration file from Config Center at start up.
  • - *
  • 3. addListener/removeListener, add or remove listeners for governance rules or config items that need to watch.
  • + *
  • 1. getConfig, get governance rules or single config item from Config Center.
  • + *
  • 2. getConfigFile, get configuration file from Config Center at start up.
  • + *
  • 3. addListener/removeListener, add or remove listeners for governance rules or config items that need to watch.
  • *
*/ public interface DynamicConfiguration extends Configuration { + String DEFAULT_GROUP = "dubbo"; /** @@ -113,7 +119,7 @@ default String getConfig(String key, String group) { /** * {@see #getConfig(String, String, long)} - * + *

* This method are mostly used to get a compound config file, such as a complete dubbo.properties file. */ default String getConfigs(String key, String group) throws IllegalStateException { @@ -122,11 +128,67 @@ default String getConfigs(String key, String group) throws IllegalStateException /** * {@see #getConfig(String, String, long)} - * + *

* This method are mostly used to get a compound config file, such as a complete dubbo.properties file. */ String getConfigs(String key, String group, long timeout) throws IllegalStateException; + /** + * Publish Config mapped to the given key and the given group. + * + * @param key the key to represent a configuration + * @param group the group where the key belongs to + * @param content the content of configuration + * @return true if success, or false + * @throws UnsupportedOperationException If the under layer does not support + * @since 2.7.2 + */ + default boolean publishConfig(String key, String group, String content) throws UnsupportedOperationException { + throw new UnsupportedOperationException("No support"); + } + + /** + * Get the config keys by the specified group + * + * @param group the specified group + * @return the read-only non-null sorted {@link Set set} of config keys + * @throws UnsupportedOperationException If the under layer does not support + * @since 2.7.2 + */ + default SortedSet getConfigKeys(String group) throws UnsupportedOperationException { + throw new UnsupportedOperationException("No support"); + } + + /** + * Get the {@link SortedMap} with with config keys and contents value by the specified group + * + * @param group the specified group + * @return the read-only non-null sorted {@link SortedMap map} + * @throws UnsupportedOperationException If the under layer does not support + * @since 2.7.2 + */ + default SortedMap getConfigs(String group) throws UnsupportedOperationException { + return getConfigs(group, -1); + } + + /** + * Get the {@link SortedMap} with with config keys and content value by the specified group + * + * @param group the specified group + * @param timeout the millisecond for timeout + * @return the read-only non-null sorted {@link SortedMap map} + * @throws UnsupportedOperationException If the under layer does not support + * @throws IllegalStateException If timeout exceeds + * @since 2.7.2 + */ + default SortedMap getConfigs(String group, long timeout) throws UnsupportedOperationException, + IllegalStateException { + SortedMap configs = new TreeMap<>(); + SortedSet configKeys = getConfigKeys(group); + configKeys.forEach(key -> configs.put(key, getConfig(key, group, timeout))); + return Collections.unmodifiableSortedMap(configs); + } + /** * Find DynamicConfiguration instance * diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfiguration.java index dbb91fdffee..52c309a437d 100644 --- a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfiguration.java @@ -20,6 +20,10 @@ import org.apache.dubbo.configcenter.ConfigurationListener; import org.apache.dubbo.configcenter.DynamicConfiguration; +import java.util.SortedSet; + +import static java.util.Collections.emptySortedSet; + /** * The default extension of {@link DynamicConfiguration}. If user does not specify a config centre, or specifies one * that is not a valid extension, it will default to this one. @@ -30,7 +34,6 @@ public NopDynamicConfiguration(URL url) { // no-op } - @Override public Object getInternalProperty(String key) { return null; @@ -55,4 +58,20 @@ public String getConfig(String key, String group, long timeout) throws IllegalSt public String getConfigs(String key, String group, long timeout) throws IllegalStateException { return null; } + + /** + * @since 2.7.2 + */ + @Override + public boolean publishConfig(String key, String group, String content) { + return true; + } + + /** + * @since 2.7.2 + */ + @Override + public SortedSet getConfigKeys(String group) { + return emptySortedSet(); + } } diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfigurationTest.java new file mode 100644 index 00000000000..7ba5bbef917 --- /dev/null +++ b/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfigurationTest.java @@ -0,0 +1,70 @@ +/* + * 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.nop; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@link NopDynamicConfiguration} Test + * + * @since 2.7.2 + */ +public class NopDynamicConfigurationTest { + + private NopDynamicConfiguration configuration = new NopDynamicConfiguration(null); + + @Test + public void testGetInternalProperty() { + assertNull(configuration.getInternalProperty(null)); + } + + @Test + public void testGetConfig() { + assertNull(configuration.getConfig(null, null, -1)); + } + + + @Test + public void testGetConfigs() { + assertNull(configuration.getConfigs(null, null, -1)); + } + + @Test + public void testAddListener() { + configuration.addListener(null, null, null); + } + + @Test + public void testRemoveListener() { + configuration.removeListener(null, null, null); + } + + @Test + public void testPublishConfig() { + assertTrue(configuration.publishConfig(null, null, null)); + } + + @Test + public void testGetConfigKeys() { + assertTrue(configuration.getConfigKeys(null).isEmpty()); + } + + +} From 38941421df86a5f47b45534d603cb4730dbf295c Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Thu, 23 May 2019 09:41:53 +0800 Subject: [PATCH 13/46] Polish apache/incubator-dubbo#4120 : To add DynamicConfiguration implementation for Zookeeper --- .../ZookeeperDynamicConfiguration.java | 73 +++++++++++++++---- .../ZookeeperDynamicConfigurationTest.java | 39 ++++++++++ 2 files changed, 96 insertions(+), 16 deletions(-) diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java index a06537b432c..5b034ca3740 100644 --- a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java @@ -27,16 +27,25 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; +import java.util.SortedSet; +import java.util.TreeSet; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.Executors; +import static java.util.Collections.emptySortedSet; +import static java.util.Collections.unmodifiableSortedSet; +import static org.apache.dubbo.common.utils.CollectionUtils.isEmpty; import static org.apache.dubbo.configcenter.Constants.CONFIG_NAMESPACE_KEY; /** * */ public class ZookeeperDynamicConfiguration implements DynamicConfiguration { + + private static final String EMPTY_STRING = ""; + private static final Logger logger = LoggerFactory.getLogger(ZookeeperDynamicConfiguration.class); private Executor executor; @@ -91,12 +100,53 @@ public void removeListener(String key, String group, ConfigurationListener liste @Override public String getConfig(String key, String group, long timeout) throws IllegalStateException { + String path = buildPath(key, group); + return (String) getInternalProperty(path); + } + + /** + * For zookeeper, {@link #getConfig(String, String, long)} and {@link #getConfigs(String, String, long)} have the same meaning. + * + * @param key + * @param group + * @param timeout + * @return + * @throws IllegalStateException + */ + @Override + public String getConfigs(String key, String group, long timeout) throws IllegalStateException { + return getConfig(key, group, timeout); + } + + @Override + public boolean publishConfig(String key, String group, String content) { + String path = buildPath(key, group); + zkClient.create(path, content, true); + return true; + } + + @Override + public SortedSet getConfigKeys(String group) { + String path = buildPath(group); + List nodes = zkClient.getChildren(path); + return isEmpty(nodes) ? emptySortedSet() : unmodifiableSortedSet(new TreeSet<>(nodes)); + } + + /** + * Build the config node path by the specified key and group + * + * @param key the key to represent a configuration + * @param group the group where the key belongs to + * @return + */ + protected String buildPath(String key, String group) { + String path = null; /** * when group is not null, we are getting startup configs from Config Center, for example: * group=dubbo, key=dubbo.properties */ if (StringUtils.isNotEmpty(group)) { - key = group + "/" + key; + path = group + "/" + key; } /** * when group is null, we are fetching governance rules, for example: @@ -105,23 +155,14 @@ public String getConfig(String key, String group, long timeout) throws IllegalSt */ else { int i = key.lastIndexOf("."); - key = key.substring(0, i) + "/" + key.substring(i + 1); + path = key.substring(0, i) + "/" + key.substring(i + 1); } - - return (String) getInternalProperty(rootPath + "/" + key); + return buildPath(path); } - /** - * For zookeeper, {@link #getConfig(String, String, long)} and {@link #getConfigs(String, String, long)} have the same meaning. - * - * @param key - * @param group - * @param timeout - * @return - * @throws IllegalStateException - */ - @Override - public String getConfigs(String key, String group, long timeout) throws IllegalStateException { - return (String) getConfig(key, group, timeout); + protected String buildPath(String relativePath) { + String path = rootPath + "/" + relativePath; + return path; } + } diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/test/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/test/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationTest.java index 64e0becc64f..df440acc620 100644 --- a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/test/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationTest.java +++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/test/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationTest.java @@ -35,8 +35,14 @@ import java.util.HashMap; import java.util.Map; +import java.util.Set; +import java.util.TreeSet; import java.util.concurrent.CountDownLatch; +import static java.util.Arrays.asList; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * TODO refactor using mockito */ @@ -122,6 +128,39 @@ public void testAddListener() throws Exception { Assertions.assertEquals("new value2", listener4.getValue()); } + @Test + public void testPublishConfig() { + String key = "user-service"; + String group = "org.apache.dubbo.service.UserService"; + String content = "test"; + + assertTrue(configuration.publishConfig(key, group, content)); + assertEquals("test", configuration.getConfigs(key, group)); + } + + @Test + public void testGetConfigKeysAndContents() { + + String key = "user-service"; + String group = "org.apache.dubbo.service.UserService"; + String content = "test"; + + String key2 = "user-service-1"; + + assertTrue(configuration.publishConfig(key, group, content)); + assertTrue(configuration.publishConfig(key2, group, content)); + + Set configKeys = configuration.getConfigKeys(group); + + assertEquals(new TreeSet(asList(key, key2)), configKeys); + + Map configs = configuration.getConfigs(group); + + assertEquals(configs.keySet(), configKeys); + + configs.forEach((k, value) -> assertEquals(content, value)); + } + private class TestListener implements ConfigurationListener { private CountDownLatch latch; private String value; From d450c7d7bebd2339983dd56825b88d388d3b89c7 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Thu, 23 May 2019 09:50:08 +0800 Subject: [PATCH 14/46] Polish apache/incubator-dubbo#4121 : Add the mapping from service metadata to service name --- dubbo-metadata/pom.xml | 21 ++++ ...ynamicConfigurationServiceNameMapping.java | 95 +++++++++++++++ .../dubbo/metadata/ServiceNameMapping.java | 64 ++++++++++ ...g.apache.dubbo.metadata.ServiceNameMapping | 1 + ...icConfigurationServiceNameMappingTest.java | 114 ++++++++++++++++++ 5 files changed, 295 insertions(+) create mode 100644 dubbo-metadata/src/main/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMapping.java create mode 100644 dubbo-metadata/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java create mode 100644 dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.ServiceNameMapping create mode 100644 dubbo-metadata/src/test/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMappingTest.java diff --git a/dubbo-metadata/pom.xml b/dubbo-metadata/pom.xml index 144ca1fda49..9a690ae58a5 100644 --- a/dubbo-metadata/pom.xml +++ b/dubbo-metadata/pom.xml @@ -33,6 +33,13 @@ + + org.apache.dubbo + dubbo-config-api + ${project.parent.version} + true + + org.apache.dubbo dubbo-rpc-api @@ -40,6 +47,20 @@ true + + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.parent.version} + test + + + + org.apache.curator + curator-test + test + + \ No newline at end of file diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMapping.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMapping.java new file mode 100644 index 00000000000..4c171bf224a --- /dev/null +++ b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMapping.java @@ -0,0 +1,95 @@ +/* + * 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; + +import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.configcenter.DynamicConfiguration; +import org.apache.dubbo.rpc.model.ApplicationModel; + +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.Set; + +import static org.apache.dubbo.common.utils.StringUtils.isBlank; + +/** + * The {@link ServiceNameMapping} implementation based on {@link DynamicConfiguration} + */ +public class DynamicConfigurationServiceNameMapping implements ServiceNameMapping { + + private static final String SEPARATOR = ":"; + + private static final String EMPTY = ""; + + private final Logger logger = LoggerFactory.getLogger(getClass()); + + @Override + public void map(String serviceInterface, String group, String version, String protocol) { + + DynamicConfiguration dynamicConfiguration = DynamicConfiguration.getDynamicConfiguration(); + + // the Dubbo Service Key as group + // the service(application) name as key + // It does matter whatever the content is, we just need a record + String key = ApplicationModel.getApplication(); + String content = String.valueOf(System.currentTimeMillis()); + execute(() -> { + dynamicConfiguration.publishConfig(key, buildGroup(serviceInterface, group, version, protocol), content); + if (logger.isInfoEnabled()) { + logger.info(String.format("The Dubbo service key[%s] mapped to service name[%s] with content : %s", + key, group, content)); + } + }); + } + + @Override + public Set get(String serviceInterface, String group, String version, String protocol) { + + DynamicConfiguration dynamicConfiguration = DynamicConfiguration.getDynamicConfiguration(); + + String key = ApplicationModel.getApplication(); + Set serviceNames = new LinkedHashSet<>(); + execute(() -> { + Set keys = dynamicConfiguration.getConfigKeys(buildGroup(serviceInterface, group, version, protocol)); + serviceNames.addAll(keys); + }); + return Collections.unmodifiableSet(serviceNames); + } + + protected static String buildGroup(String serviceInterface, String group, String version, String protocol) { + StringBuilder groupBuilder = new StringBuilder(serviceInterface) + .append(SEPARATOR).append(defaultString(group)) + .append(SEPARATOR).append(defaultString(version)) + .append(SEPARATOR).append(defaultString(protocol)); + return groupBuilder.toString(); + } + + private static String defaultString(String value) { + return isBlank(value) ? EMPTY : value; + } + + private void execute(Runnable runnable) { + try { + runnable.run(); + } catch (Throwable e) { + if (logger.isWarnEnabled()) { + logger.warn(e.getMessage(), e); + } + } + } +} diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java new file mode 100644 index 00000000000..5bbfb23c95c --- /dev/null +++ b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java @@ -0,0 +1,64 @@ +/* + * 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; + +import org.apache.dubbo.common.extension.SPI; + +import java.util.Set; + +import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; + +/** + * The interface for Dubbo service name Mapping + * + * @since 2.7.2 + */ +@SPI("default") +public interface ServiceNameMapping { + + /** + * Map the specified Dubbo service interface, group, version and protocol to current Dubbo service name + * + * @param serviceInterface the class name of Dubbo service interface + * @param group the group of Dubbo service interface (optional) + * @param version the version of Dubbo service interface version (optional) + * @param protocol the protocol of Dubbo service interface exported (optional) + */ + void map(String serviceInterface, String group, String version, String protocol); + + /** + * Get the service names from the specified Dubbo service interface, group, version and protocol + * + * @param serviceInterface the class name of Dubbo service interface + * @param group the group of Dubbo service interface (optional) + * @param version the version of Dubbo service interface version (optional) + * @param protocol the protocol of Dubbo service interface exported (optional) + * @return + */ + Set get(String serviceInterface, String group, String version, String protocol); + + + /** + * Get the default extension of {@link ServiceNameMapping} + * + * @return non-null {@link ServiceNameMapping} + * @see DynamicConfigurationServiceNameMapping + */ + static ServiceNameMapping getDefaultExtension() { + return getExtensionLoader(ServiceNameMapping.class).getDefaultExtension(); + } +} diff --git a/dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.ServiceNameMapping b/dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.ServiceNameMapping new file mode 100644 index 00000000000..3975068fc93 --- /dev/null +++ b/dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.ServiceNameMapping @@ -0,0 +1 @@ +default=org.apache.dubbo.metadata.DynamicConfigurationServiceNameMapping \ No newline at end of file diff --git a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMappingTest.java b/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMappingTest.java new file mode 100644 index 00000000000..e341d777b31 --- /dev/null +++ b/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMappingTest.java @@ -0,0 +1,114 @@ +/* + * 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; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.config.Environment; +import org.apache.dubbo.common.utils.NetUtils; +import org.apache.dubbo.configcenter.DynamicConfiguration; +import org.apache.dubbo.configcenter.DynamicConfigurationFactory; +import org.apache.dubbo.rpc.model.ApplicationModel; + +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.CuratorFrameworkFactory; +import org.apache.curator.retry.ExponentialBackoffRetry; +import org.apache.curator.test.TestingServer; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.Set; +import java.util.TreeSet; + +import static java.util.Arrays.asList; +import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; +import static org.apache.dubbo.metadata.DynamicConfigurationServiceNameMapping.buildGroup; +import static org.apache.dubbo.metadata.ServiceNameMapping.getDefaultExtension; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * {@link DynamicConfigurationServiceNameMapping} Test + * + * @since 2.7.2 + */ +public class DynamicConfigurationServiceNameMappingTest { + + private static CuratorFramework client; + + private static URL configUrl; + private static int zkServerPort = NetUtils.getAvailablePort(); + private static TestingServer zkServer; + + private final ServiceNameMapping serviceNameMapping = getDefaultExtension(); + + @BeforeAll + public static void setUp() throws Exception { + + zkServer = new TestingServer(zkServerPort, true); + + client = CuratorFrameworkFactory.newClient("localhost:" + zkServerPort, 60 * 1000, 60 * 1000, + new ExponentialBackoffRetry(1000, 3)); + + client.start(); + + configUrl = URL.valueOf("zookeeper://localhost:" + zkServerPort); + + DynamicConfiguration configuration = getExtensionLoader(DynamicConfigurationFactory.class) + .getExtension(configUrl.getProtocol()) + .getDynamicConfiguration(configUrl); + + Environment.getInstance().setDynamicConfiguration(configuration); + } + + @AfterAll + public static void tearDown() throws Exception { + zkServer.stop(); + } + + @Test + public void testBuildGroup() { + assertEquals("test:::", buildGroup("test", null, null, null)); + assertEquals("test:default::", buildGroup("test", "default", null, null)); + assertEquals("test:default:1.0.0:", buildGroup("test", "default", "1.0.0", null)); + assertEquals("test:default:1.0.0:dubbo", buildGroup("test", "default", "1.0.0", "dubbo")); + } + + @Test + public void testMapAndGet() { + + String serviceName = "test"; + String serviceName2 = "test2"; + + ApplicationModel.setApplication(serviceName); + + String serviceInterface = "org.apache.dubbo.service.UserService"; + String group = null; + String version = null; + String protocol = null; + + serviceNameMapping.map(serviceInterface, group, version, protocol); + + ApplicationModel.setApplication(serviceName2); + + serviceNameMapping.map(serviceInterface, group, version, protocol); + + Set serviceNames = serviceNameMapping.get(serviceInterface, group, version, protocol); + + assertEquals(new TreeSet(asList(serviceName, serviceName2)), serviceNames); + + } +} From 21c97c881e77fcc25a3712593ade0a83b895580f Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Thu, 23 May 2019 13:48:14 +0800 Subject: [PATCH 15/46] Polish apache/incubator-dubbo/#3790 : Dependencies with no license --- dubbo-registry/dubbo-registry-nacos/pom.xml | 43 ------------------- .../DemoServiceConsumerBootstrap.java | 4 -- .../dubbo/demo/service/DemoService.java | 8 +--- .../test/resources/provider-config.properties | 3 -- 4 files changed, 1 insertion(+), 57 deletions(-) diff --git a/dubbo-registry/dubbo-registry-nacos/pom.xml b/dubbo-registry/dubbo-registry-nacos/pom.xml index b8c952d267b..675901e2ec3 100644 --- a/dubbo-registry/dubbo-registry-nacos/pom.xml +++ b/dubbo-registry/dubbo-registry-nacos/pom.xml @@ -92,49 +92,6 @@ - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - test - - - - org.jboss.resteasy - resteasy-jaxrs - test - - - - org.jboss.resteasy - resteasy-client - test - - - - org.jboss.resteasy - resteasy-netty4 - test - - - - javax.validation - validation-api - test - - - - org.jboss.resteasy - resteasy-jackson-provider - test - - - - org.jboss.resteasy - resteasy-jaxb-provider - test - - org.springframework spring-test diff --git a/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/demo/consumer/DemoServiceConsumerBootstrap.java b/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/demo/consumer/DemoServiceConsumerBootstrap.java index b411d4a80f0..f11bdb5df3f 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/demo/consumer/DemoServiceConsumerBootstrap.java +++ b/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/demo/consumer/DemoServiceConsumerBootstrap.java @@ -37,14 +37,10 @@ public class DemoServiceConsumerBootstrap { @Reference(version = "${demo.service.version}") private DemoService demoService; - @Reference(version = "${demo.service.version}", protocol = "rest") - private DemoService restDemoService; - @PostConstruct public void init() throws InterruptedException { for (int j = 0; j < 10; j++) { System.out.println(demoService.sayName("小马哥(mercyblitz)")); - System.out.println(restDemoService.sayName("小马哥(mercyblitz)")); } Thread.sleep(TimeUnit.SECONDS.toMillis(5)); } diff --git a/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/demo/service/DemoService.java b/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/demo/service/DemoService.java index 0c808779311..77ac1b60e21 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/demo/service/DemoService.java +++ b/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/demo/service/DemoService.java @@ -16,19 +16,13 @@ */ package org.apache.dubbo.demo.service; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.QueryParam; - /** * DemoService * * @since 2.6.5 */ -@Path("/demo-service") public interface DemoService { - @GET - String sayName(@QueryParam("name") String name); + String sayName(String name); } \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-nacos/src/test/resources/provider-config.properties b/dubbo-registry/dubbo-registry-nacos/src/test/resources/provider-config.properties index e2dd335b0ed..7e2046b5c40 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/test/resources/provider-config.properties +++ b/dubbo-registry/dubbo-registry-nacos/src/test/resources/provider-config.properties @@ -6,9 +6,6 @@ dubbo.registry.address=127.0.0.1:8848 ## Exports multiple protocols ### Dubbo Protocol using random port dubbo.protocols.dubbo.port=-1 -### REST protocol -dubbo.protocols.rest.port=9090 -dubbo.protocols.rest.server=netty # Provider @Service info demo.service.version=1.0.0 demo.service.name=demoService \ No newline at end of file From fd1150f3b243e978437018d2bb9cd6ccf57e14e3 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Thu, 23 May 2019 13:49:11 +0800 Subject: [PATCH 16/46] Polish apache/incubator-dubbo#4071 : @Reference can't match the local @Service beans --- .../annotation/AnnotationBeanNameBuilder.java | 142 ------------------ .../ReferenceAnnotationBeanPostProcessor.java | 10 +- .../ServiceAnnotationBeanPostProcessor.java | 14 +- .../annotation/ServiceBeanNameBuilder.java | 112 ++++++++++++++ ...t.java => ServiceBeanNameBuilderTest.java} | 29 ++-- 5 files changed, 134 insertions(+), 173 deletions(-) delete mode 100644 dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationBeanNameBuilder.java create mode 100644 dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java rename dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/{AnnotationBeanNameBuilderTest.java => ServiceBeanNameBuilderTest.java} (67%) diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationBeanNameBuilder.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationBeanNameBuilder.java deleted file mode 100644 index 6e18e2a3471..00000000000 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationBeanNameBuilder.java +++ /dev/null @@ -1,142 +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.config.spring.beans.factory.annotation; - -import org.apache.dubbo.common.constants.CommonConstants; -import org.apache.dubbo.config.annotation.Reference; -import org.apache.dubbo.config.annotation.Service; -import org.apache.dubbo.registry.Registry; - -import org.springframework.core.env.Environment; - -import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; -import static org.apache.dubbo.config.spring.util.AnnotationUtils.resolveInterfaceName; -import static org.springframework.util.StringUtils.arrayToCommaDelimitedString; -import static org.springframework.util.StringUtils.hasText; - -/** - * The Bean Name Builder for the annotations {@link Service} and {@link Reference} - *

- * The naming rule is consistent with the the implementation {@link Registry} that is based on the service-name aware - * infrastructure, e.g Spring Cloud, Cloud Native and so on. - *

- * The pattern of bean name : ${category}:${protocol}:${serviceInterface}:${version}:${group}. - *

- * ${version} and ${group} are optional. - * - * @since 2.6.6 - */ -class AnnotationBeanNameBuilder { - - private static final String SEPARATOR = ":"; - - // Required properties - - private final String category; - - private final String protocol; - - private final String interfaceClassName; - - // Optional properties - - private String version; - - private String group; - - private Environment environment; - - private AnnotationBeanNameBuilder(String category, String protocol, String interfaceClassName) { - this.category = category; - this.protocol = protocol; - this.interfaceClassName = interfaceClassName; - } - - private AnnotationBeanNameBuilder(Service service, Class interfaceClass) { - this(PROVIDERS_CATEGORY, resolveProtocol(service.protocol()), resolveInterfaceName(service, interfaceClass)); - this.group(service.group()); - this.version(service.version()); - } - - private AnnotationBeanNameBuilder(Reference reference, Class interfaceClass) { - this(CONSUMERS_CATEGORY, resolveProtocol(reference.protocol()), resolveInterfaceName(reference, interfaceClass)); - this.group(reference.group()); - this.version(reference.version()); - } - - public static AnnotationBeanNameBuilder create(Service service, Class interfaceClass) { - return new AnnotationBeanNameBuilder(service, interfaceClass); - } - - public static AnnotationBeanNameBuilder create(Reference reference, Class interfaceClass) { - return new AnnotationBeanNameBuilder(reference, interfaceClass); - } - - private static void append(StringBuilder builder, String value) { - if (hasText(value)) { - builder.append(SEPARATOR).append(value); - } - } - - public AnnotationBeanNameBuilder group(String group) { - this.group = group; - return this; - } - - public AnnotationBeanNameBuilder version(String version) { - this.version = version; - return this; - } - - public AnnotationBeanNameBuilder environment(Environment environment) { - this.environment = environment; - return this; - } - - /** - * Resolve the protocol - * - * @param protocols one or more protocols - * @return if protocols == null, it will return - * {@link CommonConstants#DEFAULT_PROTOCOL "dubbo"} as the default protocol - * @see CommonConstants#DEFAULT_PROTOCOL - */ - private static String resolveProtocol(String... protocols) { - String protocol = arrayToCommaDelimitedString(protocols); - return hasText(protocol) ? protocol : DEFAULT_PROTOCOL; - } - - /** - * Build bean name while resolve the placeholders if possible. - * - * @return pattern : ${category}:${protocol}:${serviceInterface}:${version}:${group} - */ - public String build() { - // Append the required properties - StringBuilder beanNameBuilder = new StringBuilder(category); - append(beanNameBuilder, protocol); - append(beanNameBuilder, interfaceClassName); - // Append the optional properties - append(beanNameBuilder, version); - append(beanNameBuilder, group); - String beanName = beanNameBuilder.toString(); - // Resolve placeholders - return environment != null ? environment.resolvePlaceholders(beanName) : beanName; - } -} diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java index 7c3a6b9b87d..b40948de95a 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java @@ -41,6 +41,8 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import static org.apache.dubbo.config.spring.beans.factory.annotation.ServiceBeanNameBuilder.create; + /** * {@link org.springframework.beans.factory.config.BeanPostProcessor} implementation * that Consumer service {@link Reference} annotated fields @@ -178,16 +180,14 @@ protected String buildInjectedObjectCacheKey(Reference reference, Object bean, S return buildReferencedBeanName(reference, injectedType) + "#source=" + (injectedElement.getMember()) + - "#attributes=" + AnnotationUtils.getAttributes(reference,getEnvironment(),true); + "#attributes=" + AnnotationUtils.getAttributes(reference, getEnvironment(), true); } private String buildReferencedBeanName(Reference reference, Class injectedType) { - AnnotationBeanNameBuilder builder = AnnotationBeanNameBuilder.create(reference, injectedType); - - builder.environment(getEnvironment()); + ServiceBeanNameBuilder serviceBeanNameBuilder = create(reference, injectedType, getEnvironment()); - return getEnvironment().resolvePlaceholders(builder.build()); + return serviceBeanNameBuilder.build(); } private ReferenceBean buildReferenceBeanIfAbsent(String referencedBeanName, Reference reference, diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java index 305e3724132..e12db85fa7b 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java @@ -60,6 +60,7 @@ import java.util.Map; import java.util.Set; +import static org.apache.dubbo.config.spring.beans.factory.annotation.ServiceBeanNameBuilder.create; import static org.apache.dubbo.config.spring.util.ObjectUtils.of; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; import static org.springframework.context.annotation.AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR; @@ -259,7 +260,7 @@ private void registerServiceBean(BeanDefinitionHolder beanDefinitionHolder, Bean buildServiceBeanDefinition(service, interfaceClass, annotatedServiceBeanName); // ServiceBean Bean name - String beanName = generateServiceBeanName(service, interfaceClass, annotatedServiceBeanName); + String beanName = generateServiceBeanName(service, interfaceClass); if (scanner.checkCandidate(beanName, serviceBeanDefinition)) { // check duplicated candidate bean registry.registerBeanDefinition(beanName, serviceBeanDefinition); @@ -285,19 +286,14 @@ private void registerServiceBean(BeanDefinitionHolder beanDefinitionHolder, Bean * Generates the bean name of {@link ServiceBean} * * @param service - * @param interfaceClass the class of interface annotated {@link Service} - * @param annotatedServiceBeanName the bean name of annotated {@link Service} + * @param interfaceClass the class of interface annotated {@link Service} * @return ServiceBean@interfaceClassName#annotatedServiceBeanName * @since 2.5.9 */ - private String generateServiceBeanName(Service service, Class interfaceClass, String annotatedServiceBeanName) { - - AnnotationBeanNameBuilder builder = AnnotationBeanNameBuilder.create(service, interfaceClass); - - builder.environment(environment); + private String generateServiceBeanName(Service service, Class interfaceClass) { + ServiceBeanNameBuilder builder = create(service, interfaceClass, environment); return builder.build(); - } private Class resolveServiceInterfaceClass(Class annotatedServiceBeanClass, Service service) { diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java new file mode 100644 index 00000000000..5d272515ab3 --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java @@ -0,0 +1,112 @@ +/* + * 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.config.spring.beans.factory.annotation; + +import org.apache.dubbo.config.annotation.Reference; +import org.apache.dubbo.config.annotation.Service; +import org.apache.dubbo.config.spring.ReferenceBean; +import org.apache.dubbo.config.spring.ServiceBean; + +import org.springframework.core.env.Environment; +import org.springframework.util.StringUtils; + +import static org.apache.dubbo.config.spring.util.AnnotationUtils.resolveInterfaceName; + +/** + * Dubbo {@link Service @Service} Bean Builder + * + * @see Service + * @see Reference + * @see ServiceBean + * @see ReferenceBean + * @since 2.6.5 + */ +public class ServiceBeanNameBuilder { + + private static final String SEPARATOR = ":"; + + private final String interfaceClassName; + + private final Environment environment; + + // Optional + private String version; + + private String group; + + private ServiceBeanNameBuilder(String interfaceClassName, Environment environment) { + this.interfaceClassName = interfaceClassName; + this.environment = environment; + } + + private ServiceBeanNameBuilder(Class interfaceClass, Environment environment) { + this(interfaceClass.getName(), environment); + } + + private ServiceBeanNameBuilder(Service service, Class interfaceClass, Environment environment) { + this(resolveInterfaceName(service, interfaceClass), environment); + this.group(service.group()); + this.version(service.version()); + } + + private ServiceBeanNameBuilder(Reference reference, Class interfaceClass, Environment environment) { + this(resolveInterfaceName(reference, interfaceClass), environment); + this.group(reference.group()); + this.version(reference.version()); + } + + public static ServiceBeanNameBuilder create(Class interfaceClass, Environment environment) { + return new ServiceBeanNameBuilder(interfaceClass, environment); + } + + public static ServiceBeanNameBuilder create(Service service, Class interfaceClass, Environment environment) { + return new ServiceBeanNameBuilder(service, interfaceClass, environment); + } + + public static ServiceBeanNameBuilder create(Reference reference, Class interfaceClass, Environment environment) { + return new ServiceBeanNameBuilder(reference, interfaceClass, environment); + } + + private static void append(StringBuilder builder, String value) { + if (StringUtils.hasText(value)) { + builder.append(value).append(SEPARATOR); + } + } + + public ServiceBeanNameBuilder group(String group) { + this.group = group; + return this; + } + + public ServiceBeanNameBuilder version(String version) { + this.version = version; + return this; + } + + public String build() { + StringBuilder beanNameBuilder = new StringBuilder("ServiceBean").append(SEPARATOR); + // Required + append(beanNameBuilder, interfaceClassName); + // Optional + append(beanNameBuilder, version); + append(beanNameBuilder, group); + // Build and remove last ":" + String rawBeanName = beanNameBuilder.substring(0, beanNameBuilder.length() - 1); + // Resolve placeholders + return environment.resolvePlaceholders(rawBeanName); + } +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationBeanNameBuilderTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilderTest.java similarity index 67% rename from dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationBeanNameBuilderTest.java rename to dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilderTest.java index 2e79109ab33..747fc1e2693 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationBeanNameBuilderTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilderTest.java @@ -27,18 +27,18 @@ import org.springframework.mock.env.MockEnvironment; import org.springframework.util.ReflectionUtils; -import static org.apache.dubbo.config.spring.beans.factory.annotation.AnnotationBeanNameBuilderTest.GROUP; -import static org.apache.dubbo.config.spring.beans.factory.annotation.AnnotationBeanNameBuilderTest.VERSION; +import static org.apache.dubbo.config.spring.beans.factory.annotation.ServiceBeanNameBuilderTest.GROUP; +import static org.apache.dubbo.config.spring.beans.factory.annotation.ServiceBeanNameBuilderTest.VERSION; /** - * {@link AnnotationBeanNameBuilder} Test + * {@link ServiceBeanNameBuilder} Test * - * @see AnnotationBeanNameBuilder + * @see ServiceBeanNameBuilder * @since 2.6.6 */ @Service(interfaceClass = DemoService.class, group = GROUP, version = VERSION, application = "application", module = "module", registry = {"1", "2", "3"}) -public class AnnotationBeanNameBuilderTest { +public class ServiceBeanNameBuilderTest { @Reference(interfaceClass = DemoService.class, group = "DUBBO", version = "${dubbo.version}", application = "application", module = "module", registry = {"1", "2", "3"}) @@ -58,25 +58,20 @@ public void prepare() { @Test public void testServiceAnnotation() { - Service service = AnnotationUtils.getAnnotation(AnnotationBeanNameBuilderTest.class, Service.class); - AnnotationBeanNameBuilder builder = AnnotationBeanNameBuilder.create(service, INTERFACE_CLASS); - Assert.assertEquals("providers:dubbo:org.apache.dubbo.config.spring.api.DemoService:1.0.0:DUBBO", + Service service = AnnotationUtils.getAnnotation(ServiceBeanNameBuilderTest.class, Service.class); + ServiceBeanNameBuilder builder = ServiceBeanNameBuilder.create(service, INTERFACE_CLASS, environment); + Assert.assertEquals("ServiceBean:org.apache.dubbo.config.spring.api.DemoService:1.0.0:DUBBO", builder.build()); - builder.environment(environment); - Assert.assertEquals("providers:dubbo:org.apache.dubbo.config.spring.api.DemoService:1.0.0:DUBBO", + Assert.assertEquals("ServiceBean:org.apache.dubbo.config.spring.api.DemoService:1.0.0:DUBBO", builder.build()); } @Test public void testReferenceAnnotation() { - Reference reference = AnnotationUtils.getAnnotation(ReflectionUtils.findField(AnnotationBeanNameBuilderTest.class, "INTERFACE_CLASS"), Reference.class); - AnnotationBeanNameBuilder builder = AnnotationBeanNameBuilder.create(reference, INTERFACE_CLASS); - Assert.assertEquals("consumers:dubbo:org.apache.dubbo.config.spring.api.DemoService:${dubbo.version}:DUBBO", - builder.build()); - - builder.environment(environment); - Assert.assertEquals("consumers:dubbo:org.apache.dubbo.config.spring.api.DemoService:1.0.0:DUBBO", + Reference reference = AnnotationUtils.getAnnotation(ReflectionUtils.findField(ServiceBeanNameBuilderTest.class, "INTERFACE_CLASS"), Reference.class); + ServiceBeanNameBuilder builder = ServiceBeanNameBuilder.create(reference, INTERFACE_CLASS, environment); + Assert.assertEquals("ServiceBean:org.apache.dubbo.config.spring.api.DemoService:1.0.0:DUBBO", builder.build()); } From fc0b29d4914543e0d9d14690335f2cfac492cba7 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Wed, 29 May 2019 13:17:19 +0800 Subject: [PATCH 17/46] Update version to be 2.7.3 --- dubbo-all/pom.xml | 8 ++++---- .../apache/dubbo/common/function/ThrowableConsumer.java | 2 +- .../apache/dubbo/common/function/ThrowableFunction.java | 2 +- .../java/org/apache/dubbo/common/utils/DefaultPage.java | 2 +- .../src/main/java/org/apache/dubbo/common/utils/Page.java | 2 +- .../java/org/apache/dubbo/common/utils/ReflectUtils.java | 4 ++-- dubbo-dependencies-bom/pom.xml | 2 +- dubbo-dependencies/dubbo-dependencies-zookeeper/pom.xml | 2 +- .../org/apache/dubbo/event/AbstractEventDispatcher.java | 2 +- .../org/apache/dubbo/event/DirectEventDispatcher.java | 2 +- .../src/main/java/org/apache/dubbo/event/Event.java | 2 +- .../main/java/org/apache/dubbo/event/EventDispatcher.java | 2 +- .../main/java/org/apache/dubbo/event/EventListener.java | 2 +- .../main/java/org/apache/dubbo/event/GenericEvent.java | 2 +- .../src/main/java/org/apache/dubbo/event/Listenable.java | 2 +- .../org/apache/dubbo/event/ParallelEventDispatcher.java | 2 +- .../org/apache/dubbo/event/DirectEventDispatcherTest.java | 2 +- .../src/test/java/org/apache/dubbo/event/EchoEvent.java | 2 +- .../java/org/apache/dubbo/event/EchoEventListener.java | 2 +- .../java/org/apache/dubbo/event/EchoEventListener2.java | 2 +- .../java/org/apache/dubbo/event/EventDispatcherTest.java | 2 +- .../java/org/apache/dubbo/event/EventListenerTest.java | 2 +- .../java/org/apache/dubbo/event/GenericEventTest.java | 2 +- .../apache/dubbo/event/ParallelEventDispatcherTest.java | 2 +- .../dubbo/metadata/InMemoryLocalMetadataService.java | 2 +- .../org/apache/dubbo/metadata/LocalMetadataService.java | 2 +- .../java/org/apache/dubbo/metadata/MetadataService.java | 2 +- .../apache/dubbo/metadata/MetadataServiceExporter.java | 2 +- .../org/apache/dubbo/metadata/ServiceNameMapping.java | 2 +- .../DynamicConfigurationServiceNameMappingTest.java | 2 +- .../dubbo/metadata/InMemoryLocalMetadataServiceTest.java | 2 +- .../apache/dubbo/metadata/LocalMetadataServiceTest.java | 2 +- dubbo-rpc/dubbo-rpc-xml/README.md | 2 +- 33 files changed, 37 insertions(+), 37 deletions(-) diff --git a/dubbo-all/pom.xml b/dubbo-all/pom.xml index 6ae3fbf0909..ca2e1f3e5ad 100644 --- a/dubbo-all/pom.xml +++ b/dubbo-all/pom.xml @@ -500,7 +500,7 @@ true - + org.apache.dubbo dubbo-event @@ -649,7 +649,7 @@ org.apache.dubbo:dubbo-serialization-native-hession org.apache.dubbo:dubbo-rpc-native-thrift - + org.apache.dubbo:dubbo-event org.apache.dubbo:dubbo-metadata @@ -777,13 +777,13 @@ META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory - + META-INF/dubbo/internal/org.apache.dubbo.event.EventDispatcher - META-INF/dubbo/internal/org.apache.dubbo.metadata.export.MetadataServiceExporter + META-INF/dubbo/internal/org.apache.dubbo.metadata.MetadataServiceExporter diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableConsumer.java b/dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableConsumer.java index 317d0456998..28561bb0603 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableConsumer.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableConsumer.java @@ -25,7 +25,7 @@ * @param the source type * @see Function * @see Throwable - * @since 2.7.2 + * @since 2.7.3 */ @FunctionalInterface public interface ThrowableConsumer { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableFunction.java b/dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableFunction.java index 1acd3fa137f..eb7171d9e2b 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableFunction.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/function/ThrowableFunction.java @@ -25,7 +25,7 @@ * @param the return type * @see Function * @see Throwable - * @since 2.7.2 + * @since 2.7.3 */ @FunctionalInterface public interface ThrowableFunction { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DefaultPage.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DefaultPage.java index 71dd2afe895..a1c6d97387b 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DefaultPage.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DefaultPage.java @@ -22,7 +22,7 @@ /** * The default implementation of {@link Page} * - * @since 2.7.2 + * @since 2.7.3 */ public class DefaultPage implements Page, Serializable { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Page.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Page.java index 58a4249195d..f899b696834 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Page.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Page.java @@ -21,7 +21,7 @@ /** * The model class of pagination * - * @since 2.7.2 + * @since 2.7.3 */ public interface Page { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java index bac04c907a6..437f1318cd6 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java @@ -1133,7 +1133,7 @@ public static Type[] getReturnTypes(Method method) { * * @param sourceClass the source {@link Class class} * @return non-null read-only {@link Set} - * @since 2.7.2 + * @since 2.7.3 */ public static Set findParameterizedTypes(Class sourceClass) { // Add Generic Interfaces @@ -1166,7 +1166,7 @@ public static Set findParameterizedTypes(Class sourceClass * @param matchType the type to match * @param the type to match * @return non-null read-only {@link Set} - * @since 2.7.2 + * @since 2.7.3 */ public static Set> findHierarchicalTypes(Class sourceClass, Class matchType) { if (sourceClass == null) { diff --git a/dubbo-dependencies-bom/pom.xml b/dubbo-dependencies-bom/pom.xml index e250644f506..b372a7b2b36 100644 --- a/dubbo-dependencies-bom/pom.xml +++ b/dubbo-dependencies-bom/pom.xml @@ -153,7 +153,7 @@ 6.1.26 2.0 1.1.0 - 2.7.2-SNAPSHOT + 2.7.3-SNAPSHOT diff --git a/dubbo-dependencies/dubbo-dependencies-zookeeper/pom.xml b/dubbo-dependencies/dubbo-dependencies-zookeeper/pom.xml index 66dba910f4f..968e5e35bcb 100644 --- a/dubbo-dependencies/dubbo-dependencies-zookeeper/pom.xml +++ b/dubbo-dependencies/dubbo-dependencies-zookeeper/pom.xml @@ -32,7 +32,7 @@ pom - 2.7.2-SNAPSHOT + 2.7.3-SNAPSHOT 1.1.0 diff --git a/dubbo-event/src/main/java/org/apache/dubbo/event/AbstractEventDispatcher.java b/dubbo-event/src/main/java/org/apache/dubbo/event/AbstractEventDispatcher.java index 8989f29a0aa..4b714f79636 100644 --- a/dubbo-event/src/main/java/org/apache/dubbo/event/AbstractEventDispatcher.java +++ b/dubbo-event/src/main/java/org/apache/dubbo/event/AbstractEventDispatcher.java @@ -39,7 +39,7 @@ * @see ServiceLoader * @see EventListener * @see Event - * @since 2.7.2 + * @since 2.7.3 */ public abstract class AbstractEventDispatcher implements EventDispatcher { diff --git a/dubbo-event/src/main/java/org/apache/dubbo/event/DirectEventDispatcher.java b/dubbo-event/src/main/java/org/apache/dubbo/event/DirectEventDispatcher.java index 91282b34c6e..f19390ce784 100644 --- a/dubbo-event/src/main/java/org/apache/dubbo/event/DirectEventDispatcher.java +++ b/dubbo-event/src/main/java/org/apache/dubbo/event/DirectEventDispatcher.java @@ -20,7 +20,7 @@ * Direct {@link EventDispatcher} implementation uses current thread execution model * * @see EventDispatcher - * @since 2.7.2 + * @since 2.7.3 */ public final class DirectEventDispatcher extends AbstractEventDispatcher { diff --git a/dubbo-event/src/main/java/org/apache/dubbo/event/Event.java b/dubbo-event/src/main/java/org/apache/dubbo/event/Event.java index 13f2aec16e1..c91f287b9bb 100644 --- a/dubbo-event/src/main/java/org/apache/dubbo/event/Event.java +++ b/dubbo-event/src/main/java/org/apache/dubbo/event/Event.java @@ -21,7 +21,7 @@ /** * An event object of Dubbo is based on the Java standard {@link EventObject event} * - * @since 2.7.2 + * @since 2.7.3 */ public abstract class Event extends EventObject { diff --git a/dubbo-event/src/main/java/org/apache/dubbo/event/EventDispatcher.java b/dubbo-event/src/main/java/org/apache/dubbo/event/EventDispatcher.java index ab3a2e4998b..ece1f5a09b0 100644 --- a/dubbo-event/src/main/java/org/apache/dubbo/event/EventDispatcher.java +++ b/dubbo-event/src/main/java/org/apache/dubbo/event/EventDispatcher.java @@ -27,7 +27,7 @@ * @see Event * @see EventListener * @see DirectEventDispatcher - * @since 2.7.2 + * @since 2.7.3 */ @SPI("direct") public interface EventDispatcher extends Listenable> { diff --git a/dubbo-event/src/main/java/org/apache/dubbo/event/EventListener.java b/dubbo-event/src/main/java/org/apache/dubbo/event/EventListener.java index 92c35b9c882..d3c0ae371a3 100644 --- a/dubbo-event/src/main/java/org/apache/dubbo/event/EventListener.java +++ b/dubbo-event/src/main/java/org/apache/dubbo/event/EventListener.java @@ -33,7 +33,7 @@ * @param the concrete class of {@link Event Dubbo Event} * @see Event * @see java.util.EventListener - * @since 2.7.2 + * @since 2.7.3 */ @FunctionalInterface public interface EventListener extends java.util.EventListener, Comparable> { diff --git a/dubbo-event/src/main/java/org/apache/dubbo/event/GenericEvent.java b/dubbo-event/src/main/java/org/apache/dubbo/event/GenericEvent.java index 591bcebb086..a7e68506a21 100644 --- a/dubbo-event/src/main/java/org/apache/dubbo/event/GenericEvent.java +++ b/dubbo-event/src/main/java/org/apache/dubbo/event/GenericEvent.java @@ -20,7 +20,7 @@ * Generic {@link Event Dubbo event} * * @param the type of event source - * @since 2.7.2 + * @since 2.7.3 */ public class GenericEvent extends Event { diff --git a/dubbo-event/src/main/java/org/apache/dubbo/event/Listenable.java b/dubbo-event/src/main/java/org/apache/dubbo/event/Listenable.java index 1857ac85f3f..845cd99fcfb 100644 --- a/dubbo-event/src/main/java/org/apache/dubbo/event/Listenable.java +++ b/dubbo-event/src/main/java/org/apache/dubbo/event/Listenable.java @@ -27,7 +27,7 @@ * Dubbo Event Listenable * * @see EventDispatcher - * @since 2.7.2 + * @since 2.7.3 */ public interface Listenable> { diff --git a/dubbo-event/src/main/java/org/apache/dubbo/event/ParallelEventDispatcher.java b/dubbo-event/src/main/java/org/apache/dubbo/event/ParallelEventDispatcher.java index f7b0f329763..73288ea4f13 100644 --- a/dubbo-event/src/main/java/org/apache/dubbo/event/ParallelEventDispatcher.java +++ b/dubbo-event/src/main/java/org/apache/dubbo/event/ParallelEventDispatcher.java @@ -22,7 +22,7 @@ * Parallel {@link EventDispatcher} implementation uses {@link ForkJoinPool#commonPool() JDK common thread pool} * * @see ForkJoinPool#commonPool() - * @since 2.7.2 + * @since 2.7.3 */ public class ParallelEventDispatcher extends AbstractEventDispatcher { diff --git a/dubbo-event/src/test/java/org/apache/dubbo/event/DirectEventDispatcherTest.java b/dubbo-event/src/test/java/org/apache/dubbo/event/DirectEventDispatcherTest.java index c3cc7323df2..ae7a9e8a225 100644 --- a/dubbo-event/src/test/java/org/apache/dubbo/event/DirectEventDispatcherTest.java +++ b/dubbo-event/src/test/java/org/apache/dubbo/event/DirectEventDispatcherTest.java @@ -29,7 +29,7 @@ /** * {@link DirectEventDispatcher} Test * - * @since 2.7.2 + * @since 2.7.3 */ public class DirectEventDispatcherTest { diff --git a/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEvent.java b/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEvent.java index 785d411f256..01f1ab07f5a 100644 --- a/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEvent.java +++ b/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEvent.java @@ -19,7 +19,7 @@ /** * Echo {@link Event} * - * @since 2.7.2 + * @since 2.7.3 */ class EchoEvent extends Event { diff --git a/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEventListener.java b/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEventListener.java index f88b9df3318..5d6beb236c2 100644 --- a/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEventListener.java +++ b/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEventListener.java @@ -21,7 +21,7 @@ /** * {@link EchoEvent} {@link EventListener} * - * @since 2.7.2 + * @since 2.7.3 */ public class EchoEventListener extends AbstractEventListener implements Serializable { diff --git a/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEventListener2.java b/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEventListener2.java index f30327c4852..df991e59135 100644 --- a/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEventListener2.java +++ b/dubbo-event/src/test/java/org/apache/dubbo/event/EchoEventListener2.java @@ -23,7 +23,7 @@ /** * {@link EchoEvent} {@link EventListener} 2 * - * @since 2.7.2 + * @since 2.7.3 */ public class EchoEventListener2 extends Vector> implements Serializable, Comparable>, EventListener { diff --git a/dubbo-event/src/test/java/org/apache/dubbo/event/EventDispatcherTest.java b/dubbo-event/src/test/java/org/apache/dubbo/event/EventDispatcherTest.java index b8d57f93992..001bfc29376 100644 --- a/dubbo-event/src/test/java/org/apache/dubbo/event/EventDispatcherTest.java +++ b/dubbo-event/src/test/java/org/apache/dubbo/event/EventDispatcherTest.java @@ -26,7 +26,7 @@ * {@link EventDispatcher} Test * * @see DirectEventDispatcher - * @since 2.7.2 + * @since 2.7.3 */ public class EventDispatcherTest { diff --git a/dubbo-event/src/test/java/org/apache/dubbo/event/EventListenerTest.java b/dubbo-event/src/test/java/org/apache/dubbo/event/EventListenerTest.java index eb3d27b02ea..fc831dda02d 100644 --- a/dubbo-event/src/test/java/org/apache/dubbo/event/EventListenerTest.java +++ b/dubbo-event/src/test/java/org/apache/dubbo/event/EventListenerTest.java @@ -24,7 +24,7 @@ /** * {@link EventListener} Test * - * @since 2.7.2 + * @since 2.7.3 */ public class EventListenerTest { diff --git a/dubbo-event/src/test/java/org/apache/dubbo/event/GenericEventTest.java b/dubbo-event/src/test/java/org/apache/dubbo/event/GenericEventTest.java index 92970343f1c..384893fbee2 100644 --- a/dubbo-event/src/test/java/org/apache/dubbo/event/GenericEventTest.java +++ b/dubbo-event/src/test/java/org/apache/dubbo/event/GenericEventTest.java @@ -24,7 +24,7 @@ /** * {@link GenericEvent} Test * - * @since 2.7.2 + * @since 2.7.3 */ public class GenericEventTest { diff --git a/dubbo-event/src/test/java/org/apache/dubbo/event/ParallelEventDispatcherTest.java b/dubbo-event/src/test/java/org/apache/dubbo/event/ParallelEventDispatcherTest.java index 755d482d2a8..ae59729fd4b 100644 --- a/dubbo-event/src/test/java/org/apache/dubbo/event/ParallelEventDispatcherTest.java +++ b/dubbo-event/src/test/java/org/apache/dubbo/event/ParallelEventDispatcherTest.java @@ -28,7 +28,7 @@ /** * {@link ParallelEventDispatcher} Test * - * @since 2.7.2 + * @since 2.7.3 */ public class ParallelEventDispatcherTest { diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java index 1f90543eb6b..01d6e8bf53b 100644 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java +++ b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java @@ -37,7 +37,7 @@ * exported. * * @see MetadataService - * @since 2.7.2 + * @since 2.7.3 */ public class InMemoryLocalMetadataService implements LocalMetadataService { diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/LocalMetadataService.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/LocalMetadataService.java index 97636338959..172409524ec 100644 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/LocalMetadataService.java +++ b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/LocalMetadataService.java @@ -27,7 +27,7 @@ * Local {@link MetadataService} that extends {@link MetadataService} and provides the modification, which is used for * Dubbo's consumers and providers. * - * @since 2.7.2 + * @since 2.7.3 */ @SPI("default") public interface LocalMetadataService extends MetadataService { diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataService.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataService.java index 4cbbae57835..81b4b3a90c9 100644 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataService.java +++ b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataService.java @@ -33,7 +33,7 @@ * also providers the fine-grain methods for the precise queries. * * @see InMemoryLocalMetadataService - * @since 2.7.2 + * @since 2.7.3 */ public interface MetadataService { diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceExporter.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceExporter.java index 5f756a2b76c..07190f53f8a 100644 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceExporter.java +++ b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceExporter.java @@ -27,7 +27,7 @@ * @see MetadataService * @see #export() * @see #unexport() - * @since 2.7.2 + * @since 2.7.3 */ @SPI public interface MetadataServiceExporter { diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java index 5bbfb23c95c..a642f3d2a92 100644 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java +++ b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java @@ -25,7 +25,7 @@ /** * The interface for Dubbo service name Mapping * - * @since 2.7.2 + * @since 2.7.3 */ @SPI("default") public interface ServiceNameMapping { diff --git a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMappingTest.java b/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMappingTest.java index e341d777b31..95e7a1689ad 100644 --- a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMappingTest.java +++ b/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMappingTest.java @@ -43,7 +43,7 @@ /** * {@link DynamicConfigurationServiceNameMapping} Test * - * @since 2.7.2 + * @since 2.7.3 */ public class DynamicConfigurationServiceNameMappingTest { diff --git a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/InMemoryLocalMetadataServiceTest.java b/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/InMemoryLocalMetadataServiceTest.java index 835a0d56e3c..406e4aeb98e 100644 --- a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/InMemoryLocalMetadataServiceTest.java +++ b/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/InMemoryLocalMetadataServiceTest.java @@ -36,7 +36,7 @@ /** * {@link InMemoryLocalMetadataService} Test * - * @since 2.7.2 + * @since 2.7.3 */ public class InMemoryLocalMetadataServiceTest { diff --git a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java b/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java index 937ddce985f..508a9598738 100644 --- a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java +++ b/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java @@ -23,7 +23,7 @@ /** * {@link LocalMetadataService} Test * - * @since 2.7.2 + * @since 2.7.3 */ public class LocalMetadataServiceTest { diff --git a/dubbo-rpc/dubbo-rpc-xml/README.md b/dubbo-rpc/dubbo-rpc-xml/README.md index 17c022c5fac..67cec24638a 100644 --- a/dubbo-rpc/dubbo-rpc-xml/README.md +++ b/dubbo-rpc/dubbo-rpc-xml/README.md @@ -8,7 +8,7 @@ A RPC Extension for XML-RPC(http://ws.apache.org/xmlrpc) org.apache.dubbo dubbo-rpc - 2.7.2-SNAPSHOT + 2.7.3-SNAPSHOT ``` From 1814cf134834d04c08b9e30e5772717420b1b288 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Fri, 31 May 2019 10:50:17 +0800 Subject: [PATCH 18/46] Polish apache/incubator-dubbo#3946 : Add thread-safe and performance optimization --- .../InMemoryLocalMetadataService.java | 115 ++++++++++++------ .../dubbo/metadata/MetadataService.java | 2 +- 2 files changed, 76 insertions(+), 41 deletions(-) diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java index 01d6e8bf53b..d4cd227e465 100644 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java +++ b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java @@ -17,26 +17,32 @@ package org.apache.dubbo.metadata; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.LoggerFactory; import java.util.Collection; -import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; -import java.util.Set; +import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; +import static java.util.Collections.emptyList; import static java.util.Collections.unmodifiableList; import static org.apache.dubbo.common.URL.buildKey; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; +import static org.apache.dubbo.common.utils.CollectionUtils.isEmpty; /** * The {@link LocalMetadataService} implementation stores the metadata of Dubbo services in memory locally when they * exported. * * @see MetadataService + * @see LocalMetadataService * @since 2.7.3 */ public class InMemoryLocalMetadataService implements LocalMetadataService { @@ -46,6 +52,10 @@ public class InMemoryLocalMetadataService implements LocalMetadataService { */ static final String METADATA_SERVICE_CLASS_NAME = MetadataService.class.getName(); + private final Logger logger = LoggerFactory.getLogger(getClass()); + + private final Lock lock = new ReentrantLock(); + // =================================== Registration =================================== // /** @@ -58,11 +68,6 @@ public class InMemoryLocalMetadataService implements LocalMetadataService { // =================================== Subscription =================================== // - /** - * All subscribed service names - */ - private Set subscribedServices = new LinkedHashSet<>(); - /** * The subscribed {@link URL urls} {@link Map} of {@link MetadataService}, * whose key is the return value of {@link URL#getServiceKey()} method and value is the {@link List} of @@ -74,33 +79,18 @@ public class InMemoryLocalMetadataService implements LocalMetadataService { @Override public List getSubscribedURLs() { - return getAllServiceURLs(subscribedServiceURLs); + return getAllUnmodifiableServiceURLs(subscribedServiceURLs); } @Override public List getExportedURLs(String serviceInterface, String group, String version, String protocol) { if (ALL_SERVICE_INTERFACES.equals(serviceInterface)) { - return getAllServiceURLs(exportedServiceURLs); + return getAllUnmodifiableServiceURLs(exportedServiceURLs); } String serviceKey = buildKey(serviceInterface, group, version); return unmodifiableList(getServiceURLs(exportedServiceURLs, serviceKey, protocol)); } - protected List getServiceURLs(ConcurrentMap> exportedServiceURLs, String serviceKey, - String protocol) { - List serviceURLs = getServiceURLs(exportedServiceURLs, serviceKey); - return serviceURLs.stream().filter( - url -> protocol == null || protocol.equals(url.getParameter(PROTOCOL_KEY))) - .map(URL::toFullString) - .collect(Collectors.toList()); - } - - - private boolean isMetadataServiceURL(URL url) { - String serviceInterface = url.getServiceInterface(); - return METADATA_SERVICE_CLASS_NAME.equals(serviceInterface); - } - @Override public boolean exportURL(URL url) { if (isMetadataServiceURL(url)) { // ignore MetadataService in the export phase @@ -127,31 +117,76 @@ public boolean unsubscribeURL(URL url) { return removeURL(subscribedServiceURLs, url); } - protected boolean addURL(Map> serviceURLs, URL url) { - String serviceKey = url.getServiceKey(); - List urls = getServiceURLs(serviceURLs, serviceKey); - if (!urls.contains(url)) { - return urls.add(url); - } - return false; + private boolean addURL(Map> serviceURLs, URL url) { + return executeMutually(() -> { + List urls = serviceURLs.computeIfAbsent(url.getServiceKey(), s -> new LinkedList()); + if (!urls.contains(url)) { + return urls.add(url); + } + return false; + }); } - protected boolean removeURL(Map> serviceURLs, URL url) { - String serviceKey = url.getServiceKey(); - List urls = getServiceURLs(serviceURLs, serviceKey); - return urls.remove(url); + private boolean removeURL(Map> serviceURLs, URL url) { + return executeMutually(() -> { + List urls = serviceURLs.get(url.getServiceKey()); + if (isEmpty(urls)) { + return false; + } + return urls.remove(url); + }); } - protected List getServiceURLs(Map> serviceURLs, String serviceKey) { - return serviceURLs.computeIfAbsent(serviceKey, s -> new LinkedList()); + private boolean executeMutually(Callable callable) { + boolean success = false; + try { + lock.lock(); + try { + success = callable.call(); + } catch (Exception e) { + if (logger.isErrorEnabled()) { + logger.error(e); + } + } + } finally { + lock.unlock(); + } + return success; } - protected List getAllServiceURLs(Map> serviceURLs) { + private static List getServiceURLs(Map> exportedServiceURLs, String serviceKey, + String protocol) { + List serviceURLs = exportedServiceURLs.get(serviceKey); + + if (serviceKey == null) { + return emptyList(); + } + return serviceURLs - .values() .stream() - .flatMap(Collection::stream) + .filter(url -> isAcceptableProtocol(protocol, url)) .map(URL::toFullString) .collect(Collectors.toList()); } + + private static boolean isAcceptableProtocol(String protocol, URL url) { + return protocol == null + || protocol.equals(url.getParameter(PROTOCOL_KEY)) + || protocol.equals(url.getProtocol()); + } + + private static boolean isMetadataServiceURL(URL url) { + String serviceInterface = url.getServiceInterface(); + return METADATA_SERVICE_CLASS_NAME.equals(serviceInterface); + } + + private static List getAllUnmodifiableServiceURLs(Map> serviceURLs) { + return unmodifiableList( + serviceURLs + .values() + .stream() + .flatMap(Collection::stream) + .map(URL::toFullString) + .collect(Collectors.toList())); + } } diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataService.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataService.java index 81b4b3a90c9..f73d5f6e8cb 100644 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataService.java +++ b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataService.java @@ -32,7 +32,7 @@ * {@link #getExportedURLs()} and {@link #getSubscribedURLs()} respectively. What's more, {@link MetadataService} * also providers the fine-grain methods for the precise queries. * - * @see InMemoryLocalMetadataService + * @see LocalMetadataService * @since 2.7.3 */ public interface MetadataService { From 574e1b1959096468796a9b292103e73031a627e9 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Fri, 31 May 2019 10:52:22 +0800 Subject: [PATCH 19/46] Polish apache/incubator-dubbo#3946 : Add thread-safe and performance optimization --- .../org/apache/dubbo/metadata/InMemoryLocalMetadataService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java index d4cd227e465..a932f40f878 100644 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java +++ b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java @@ -158,7 +158,7 @@ private static List getServiceURLs(Map> exportedServic String protocol) { List serviceURLs = exportedServiceURLs.get(serviceKey); - if (serviceKey == null) { + if (serviceURLs == null) { return emptyList(); } From 07d7ebfc2b54ef93b9f5956ac56844d3381d9d09 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Fri, 31 May 2019 10:53:31 +0800 Subject: [PATCH 20/46] Polish apache/incubator-dubbo#3946 : Add thread-safe and performance optimization --- .../org/apache/dubbo/metadata/InMemoryLocalMetadataService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java index a932f40f878..13df9c52903 100644 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java +++ b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java @@ -158,7 +158,7 @@ private static List getServiceURLs(Map> exportedServic String protocol) { List serviceURLs = exportedServiceURLs.get(serviceKey); - if (serviceURLs == null) { + if (isEmpty(serviceURLs)) { return emptyList(); } From 83b232407051c5be4b94a1ffdf6902145a1ad1d6 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Fri, 31 May 2019 14:07:20 +0800 Subject: [PATCH 21/46] Update 2.7.3 --- .../apache/dubbo/configcenter/DynamicConfiguration.java | 8 ++++---- .../configcenter/support/nop/NopDynamicConfiguration.java | 4 ++-- .../support/nop/NopDynamicConfigurationTest.java | 2 +- pom.xml | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/DynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/DynamicConfiguration.java index 0c833af7e82..804dd8bd568 100644 --- a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/DynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/DynamicConfiguration.java @@ -141,7 +141,7 @@ default String getConfigs(String key, String group) throws IllegalStateException * @param content the content of configuration * @return true if success, or false * @throws UnsupportedOperationException If the under layer does not support - * @since 2.7.2 + * @since 2.7.3 */ default boolean publishConfig(String key, String group, String content) throws UnsupportedOperationException { throw new UnsupportedOperationException("No support"); @@ -153,7 +153,7 @@ default boolean publishConfig(String key, String group, String content) throws U * @param group the specified group * @return the read-only non-null sorted {@link Set set} of config keys * @throws UnsupportedOperationException If the under layer does not support - * @since 2.7.2 + * @since 2.7.3 */ default SortedSet getConfigKeys(String group) throws UnsupportedOperationException { throw new UnsupportedOperationException("No support"); @@ -165,7 +165,7 @@ default SortedSet getConfigKeys(String group) throws UnsupportedOperatio * @param group the specified group * @return the read-only non-null sorted {@link SortedMap map} * @throws UnsupportedOperationException If the under layer does not support - * @since 2.7.2 + * @since 2.7.3 */ default SortedMap getConfigs(String group) throws UnsupportedOperationException { return getConfigs(group, -1); @@ -179,7 +179,7 @@ default SortedMap getConfigs(String group) throws UnsupportedOpe * @return the read-only non-null sorted {@link SortedMap map} * @throws UnsupportedOperationException If the under layer does not support * @throws IllegalStateException If timeout exceeds - * @since 2.7.2 + * @since 2.7.3 */ default SortedMap getConfigs(String group, long timeout) throws UnsupportedOperationException, IllegalStateException { diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfiguration.java index 52c309a437d..56e1191aa5f 100644 --- a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfiguration.java @@ -60,7 +60,7 @@ public String getConfigs(String key, String group, long timeout) throws IllegalS } /** - * @since 2.7.2 + * @since 2.7.3 */ @Override public boolean publishConfig(String key, String group, String content) { @@ -68,7 +68,7 @@ public boolean publishConfig(String key, String group, String content) { } /** - * @since 2.7.2 + * @since 2.7.3 */ @Override public SortedSet getConfigKeys(String group) { diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfigurationTest.java index 7ba5bbef917..cd549dd62c1 100644 --- a/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfigurationTest.java +++ b/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfigurationTest.java @@ -24,7 +24,7 @@ /** * {@link NopDynamicConfiguration} Test * - * @since 2.7.2 + * @since 2.7.3 */ public class NopDynamicConfigurationTest { diff --git a/pom.xml b/pom.xml index edc06e12067..b1d72f67b80 100644 --- a/pom.xml +++ b/pom.xml @@ -124,7 +124,7 @@ true true - 2.7.2-SNAPSHOT + 2.7.3-SNAPSHOT From 572b256a3b7b349db7c05e5fc2b3c0bc78324f1b Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Fri, 31 May 2019 14:09:15 +0800 Subject: [PATCH 22/46] Polish apache/incubator-dubbo#4104 : To add more events for dubbo-config-api --- .../apache/dubbo/config/ReferenceConfig.java | 15 ++--- .../apache/dubbo/config/ServiceConfig.java | 9 ++- .../event/ReferenceConfigDestroyedEvent.java | 2 +- .../ReferenceConfigInitializedEvent.java | 2 +- .../event/ServiceConfigExportedEvent.java | 2 +- .../event/ServiceConfigUnexportedEvent.java | 2 +- .../listener/ServiceNameMappingListener.java | 57 +++++++++++++++++ .../ConfigurableMetadataServiceExporter.java | 2 +- ...ubboProtocolsConfigMetadataCustomizer.java | 50 +++++++++++++++ .../ServiceInstancePortCustomizer.java | 51 +++++++++++++++ .../org.apache.dubbo.event.EventListener | 1 + ....registry.client.ServiceInstanceCustomizer | 2 + .../dubbo/config/ServiceConfigTest.java | 3 +- .../ServiceNameMappingListenerTest.java | 63 +++++++++++++++++++ ...nfigurableMetadataServiceExporterTest.java | 2 +- 15 files changed, 240 insertions(+), 23 deletions(-) create mode 100644 dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/listener/ServiceNameMappingListener.java create mode 100644 dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/DubboProtocolsConfigMetadataCustomizer.java create mode 100644 dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ServiceInstancePortCustomizer.java create mode 100644 dubbo-config/dubbo-config-api/src/main/resources/META-INF/services/org.apache.dubbo.event.EventListener create mode 100644 dubbo-config/dubbo-config-api/src/main/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceInstanceCustomizer create mode 100644 dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/event/listener/ServiceNameMappingListenerTest.java diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index 0b99f114044..5b3009f142d 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -71,18 +71,13 @@ import static org.apache.dubbo.common.constants.CommonConstants.SEMICOLON_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.CLUSTER_KEY; -import static org.apache.dubbo.config.Constants.DUBBO_IP_TO_REGISTRY; -import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; -import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; -import static org.apache.dubbo.registry.Constants.CONSUMER_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMER_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.REFER_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; import static org.apache.dubbo.common.utils.NetUtils.isInvalidLocalHost; import static org.apache.dubbo.config.Constants.DUBBO_IP_TO_REGISTRY; +import static org.apache.dubbo.registry.Constants.CONSUMER_PROTOCOL; import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY; import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL; +import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; /** * ReferenceConfig @@ -282,7 +277,7 @@ public synchronized void destroy() { invoker = null; ref = null; - // dispatch a ReferenceConfigDestroyedEvent since 2.7.2 + // dispatch a ReferenceConfigDestroyedEvent since 2.7.3 dispatch(new ReferenceConfigDestroyedEvent(this)); } @@ -349,7 +344,7 @@ private void init() { ApplicationModel.initConsumerModel(serviceKey, buildConsumerModel(serviceKey, attributes)); initialized = true; - // dispatch a ReferenceConfigInitializedEvent since 2.7.2 + // dispatch a ReferenceConfigInitializedEvent since 2.7.3 dispatch(new ReferenceConfigInitializedEvent(this, invoker)); } @@ -685,7 +680,7 @@ private void resolveFile() { * Dispatch an {@link Event event} * * @param event an {@link Event event} - * @since 2.7.2 + * @since 2.7.3 */ protected void dispatch(Event event) { eventDispatcher.dispatch(event); diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index 5be6e76f959..1024bd143d0 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -78,7 +78,6 @@ import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.DUBBO_IP_TO_BIND; import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.EXPORT_KEY; import static org.apache.dubbo.common.utils.NetUtils.getAvailablePort; import static org.apache.dubbo.common.utils.NetUtils.getLocalHost; import static org.apache.dubbo.common.utils.NetUtils.isInvalidLocalHost; @@ -86,7 +85,6 @@ import static org.apache.dubbo.config.Constants.DUBBO_IP_TO_REGISTRY; import static org.apache.dubbo.config.Constants.DUBBO_PORT_TO_BIND; import static org.apache.dubbo.config.Constants.DUBBO_PORT_TO_REGISTRY; -import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY; import static org.apache.dubbo.config.Constants.MULTICAST; import static org.apache.dubbo.config.Constants.PROTOCOLS_SUFFIX; import static org.apache.dubbo.config.Constants.SCOPE_NONE; @@ -97,6 +95,7 @@ import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL; import static org.apache.dubbo.rpc.Constants.SCOPE_REMOTE; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; +import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY; /** * ServiceConfig @@ -421,7 +420,7 @@ protected synchronized void doExport() { } doExportUrls(); - // dispatch a ServiceConfigExportedEvent since 2.7.2 + // dispatch a ServiceConfigExportedEvent since 2.7.3 dispatch(new ServiceConfigExportedEvent(this)); } @@ -456,7 +455,7 @@ public synchronized void unexport() { } unexported = true; - // dispatch a ServiceConfigUnExportedEvent since 2.7.2 + // dispatch a ServiceConfigUnExportedEvent since 2.7.3 dispatch(new ServiceConfigUnexportedEvent(this)); } @@ -1069,7 +1068,7 @@ public String getPrefix() { * Dispatch an {@link Event event} * * @param event an {@link Event event} - * @since 2.7.2 + * @since 2.7.3 */ protected void dispatch(Event event) { eventDispatcher.dispatch(event); diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ReferenceConfigDestroyedEvent.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ReferenceConfigDestroyedEvent.java index 58b871ea7e9..8f07e51e510 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ReferenceConfigDestroyedEvent.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ReferenceConfigDestroyedEvent.java @@ -26,7 +26,7 @@ * @see Reference * @see ReferenceConfig#destroy() * @see Event - * @since 2.7.2 + * @since 2.7.3 */ public class ReferenceConfigDestroyedEvent extends Event { diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ReferenceConfigInitializedEvent.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ReferenceConfigInitializedEvent.java index dcf02cfec77..359c8bce60d 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ReferenceConfigInitializedEvent.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ReferenceConfigInitializedEvent.java @@ -27,7 +27,7 @@ * @see Reference * @see ReferenceConfig#get() * @see Event - * @since 2.7.2 + * @since 2.7.3 */ public class ReferenceConfigInitializedEvent extends Event { diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ServiceConfigExportedEvent.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ServiceConfigExportedEvent.java index e6e9c09a108..ebf15f359df 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ServiceConfigExportedEvent.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ServiceConfigExportedEvent.java @@ -22,7 +22,7 @@ /** * {@link ServiceConfig} event post-{@link ServiceConfig#export() export} * - * @since 2.7.2 + * @since 2.7.3 */ public class ServiceConfigExportedEvent extends Event { diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ServiceConfigUnexportedEvent.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ServiceConfigUnexportedEvent.java index f4914fe8034..15bd3e567e6 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ServiceConfigUnexportedEvent.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/ServiceConfigUnexportedEvent.java @@ -22,7 +22,7 @@ /** * {@link ServiceConfig} event post-{@link ServiceConfig#unexport() unexport} * - * @since 2.7.2 + * @since 2.7.3 */ public class ServiceConfigUnexportedEvent extends Event { diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/listener/ServiceNameMappingListener.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/listener/ServiceNameMappingListener.java new file mode 100644 index 00000000000..3295ca0d1f3 --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/listener/ServiceNameMappingListener.java @@ -0,0 +1,57 @@ +/* + * 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.config.event.listener; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.config.ServiceConfig; +import org.apache.dubbo.config.event.ServiceConfigExportedEvent; +import org.apache.dubbo.configcenter.DynamicConfiguration; +import org.apache.dubbo.event.EventListener; +import org.apache.dubbo.metadata.ServiceNameMapping; + +import java.util.List; + +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.metadata.ServiceNameMapping.getDefaultExtension; + +/** + * An {@link EventListener event listener} for mapping {@link ServiceConfig#getExportedUrls() the exported Dubbo + * service inerface} to its service name + * + * @see ServiceNameMapping + * @see ServiceConfig#getExportedUrls() + * @since 2.7.3 + */ +public class ServiceNameMappingListener implements EventListener { + + private final ServiceNameMapping serviceNameMapping = getDefaultExtension(); + + @Override + public void onEvent(ServiceConfigExportedEvent event) { + DynamicConfiguration dynamicConfiguration = DynamicConfiguration.getDynamicConfiguration(); + ServiceConfig serviceConfig = event.getServiceConfig(); + List exportedURLs = serviceConfig.getExportedUrls(); + exportedURLs.forEach(url -> { + String serviceInterface = url.getServiceInterface(); + String group = url.getParameter(GROUP_KEY); + String version = url.getParameter(VERSION_KEY); + String protocol = url.getProtocol(); + serviceNameMapping.map(serviceInterface, group, version, protocol); + }); + } +} diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java index d3e4226767a..b91be42a73b 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java @@ -44,7 +44,7 @@ * @see MetadataServiceExporter * @see ServiceConfig * @see ConfigManager - * @since 2.7.2 + * @since 2.7.3 */ public class ConfigurableMetadataServiceExporter implements MetadataServiceExporter { diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/DubboProtocolsConfigMetadataCustomizer.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/DubboProtocolsConfigMetadataCustomizer.java new file mode 100644 index 00000000000..9d00066b084 --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/DubboProtocolsConfigMetadataCustomizer.java @@ -0,0 +1,50 @@ +/* + * 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.config.metadata; + +import org.apache.dubbo.config.ProtocolConfig; +import org.apache.dubbo.config.context.ConfigManager; +import org.apache.dubbo.registry.client.ServiceInstance; +import org.apache.dubbo.registry.client.ServiceInstanceCustomizer; + +import java.util.Map; + +import static java.lang.String.valueOf; +import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.protocolPortMetadataKey; + +/** + * The {@link ServiceInstanceCustomizer customizer} to add the content of {@link ProtocolConfig protocol configs} + * into {@link ServiceInstance#getMetadata() the metadata of service instance}. + * + * @see ServiceInstanceCustomizer + * @since 2.7.3 + */ +public class DubboProtocolsConfigMetadataCustomizer implements ServiceInstanceCustomizer { + + @Override + public void customize(ServiceInstance serviceInstance) { + Map metadata = serviceInstance.getMetadata(); + ConfigManager configManager = ConfigManager.getInstance(); + configManager.getProtocols() + .values() + .forEach(protocolConfig -> { + String key = protocolPortMetadataKey((protocolConfig.getName())); + String port = valueOf(protocolConfig.getPort()); + metadata.put(key, port); + }); + } +} diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ServiceInstancePortCustomizer.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ServiceInstancePortCustomizer.java new file mode 100644 index 00000000000..61653ff7a8e --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ServiceInstancePortCustomizer.java @@ -0,0 +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.config.metadata; + +import org.apache.dubbo.config.context.ConfigManager; +import org.apache.dubbo.registry.client.DefaultServiceInstance; +import org.apache.dubbo.registry.client.ServiceInstance; +import org.apache.dubbo.registry.client.ServiceInstanceCustomizer; + +/** + * The {@link ServiceInstanceCustomizer} to customize the {@link ServiceInstance#getPort() port} of service instance. + * + * @since 2.7.3 + */ +public class ServiceInstancePortCustomizer implements ServiceInstanceCustomizer { + + @Override + public void customize(ServiceInstance serviceInstance) { + + if (serviceInstance.getPort() == null + || serviceInstance.getPort().intValue() < 1) { + return; + } + + ConfigManager.getInstance() + .getProtocols() + .values() + .stream() + .findFirst() + .ifPresent(protocolConfig -> { + if (serviceInstance instanceof DefaultServiceInstance) { + DefaultServiceInstance instance = (DefaultServiceInstance) serviceInstance; + instance.setPort(protocolConfig.getPort()); + } + }); + } +} diff --git a/dubbo-config/dubbo-config-api/src/main/resources/META-INF/services/org.apache.dubbo.event.EventListener b/dubbo-config/dubbo-config-api/src/main/resources/META-INF/services/org.apache.dubbo.event.EventListener new file mode 100644 index 00000000000..b30703bf233 --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/main/resources/META-INF/services/org.apache.dubbo.event.EventListener @@ -0,0 +1 @@ +org.apache.dubbo.config.event.listener.ServiceNameMappingListener \ No newline at end of file diff --git a/dubbo-config/dubbo-config-api/src/main/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceInstanceCustomizer b/dubbo-config/dubbo-config-api/src/main/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceInstanceCustomizer new file mode 100644 index 00000000000..d11d2432de2 --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/main/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceInstanceCustomizer @@ -0,0 +1,2 @@ +org.apache.dubbo.config.metadata.DubboProtocolsConfigMetadataCustomizer +org.apache.dubbo.config.metadata.ServiceInstancePortCustomizer \ No newline at end of file diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java index f45727dd325..1fb8209d004 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java @@ -52,9 +52,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; -import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY; import static org.apache.dubbo.common.constants.ConfigConstants.SHUTDOWN_WAIT_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.EXPORT_KEY; import static org.apache.dubbo.config.Constants.SHUTDOWN_TIMEOUT_KEY; import static org.apache.dubbo.remoting.Constants.BIND_IP_KEY; import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY; @@ -62,6 +60,7 @@ import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_BEAN; import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_DEFAULT; import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_NATIVE_JAVA; +import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/event/listener/ServiceNameMappingListenerTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/event/listener/ServiceNameMappingListenerTest.java new file mode 100644 index 00000000000..b2b981f8b62 --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/event/listener/ServiceNameMappingListenerTest.java @@ -0,0 +1,63 @@ +/* + * 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.config.event.listener; + +import org.apache.dubbo.config.ApplicationConfig; +import org.apache.dubbo.config.ProtocolConfig; +import org.apache.dubbo.config.RegistryConfig; +import org.apache.dubbo.config.ServiceConfig; +import org.apache.dubbo.config.api.DemoService; +import org.apache.dubbo.config.provider.impl.DemoServiceImpl; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * {@link ServiceNameMappingListener} Test + * + * @since 2.7.3 + */ +public class ServiceNameMappingListenerTest { + + private ServiceConfig service = new ServiceConfig(); + + @BeforeEach + public void init() { + + ApplicationConfig applicationConfig = new ApplicationConfig("app"); + + ProtocolConfig protocolConfig = new ProtocolConfig(); + protocolConfig.setName("mockprotocol"); + + RegistryConfig registry = new RegistryConfig(); + registry.setProtocol("mockprotocol"); + registry.setAddress("N/A"); + + service.setInterface(DemoService.class); + service.setRef(new DemoServiceImpl()); + service.setApplication(applicationConfig); + service.setProtocol(protocolConfig); + service.setRegistry(registry); + } + + @Test + public void testOnEvent() { + + service.export(); + + } +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporterTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporterTest.java index 48f3f38c068..66200aca1ea 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporterTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporterTest.java @@ -37,7 +37,7 @@ /** * {@link ConfigurableMetadataServiceExporter} Test * - * @since 2.7.2 + * @since 2.7.3 */ public class ConfigurableMetadataServiceExporterTest { From 9975f821a9046fd8f1e6ec54e0af1311db964115 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Fri, 31 May 2019 14:10:11 +0800 Subject: [PATCH 23/46] Polish apache/incubator-dubbo#3942 : Dubbo Cloud Native: To Add Service registration and discovery abstract --- dubbo-registry/dubbo-registry-api/pom.xml | 9 +- .../org/apache/dubbo/registry/Registry.java | 8 + .../client/CompositeServiceDiscovery.java | 118 ------ .../DefaultServiceDiscoveryFactory.java | 74 ++++ .../client/DefaultServiceInstance.java | 23 +- .../EventPublishingServiceDiscovery.java | 296 +++++++++++++++ .../EventPublishingServiceRegistry.java | 128 ------- .../registry/client/ServiceDiscovery.java | 86 +++-- .../client/ServiceDiscoveryFactory.java | 79 ++++ .../registry/client/ServiceInstance.java | 6 +- .../client/ServiceInstanceCustomizer.java | 38 ++ .../ServiceInstanceMetadataCustomizer.java | 73 ++++ .../registry/client/ServiceRegistry.java | 66 ---- .../event/ServiceDiscoveryStartedEvent.java | 52 +++ .../event/ServiceDiscoveryStartingEvent.java | 51 +++ .../event/ServiceDiscoveryStoppedEvent.java | 51 +++ .../event/ServiceDiscoveryStoppingEvent.java | 51 +++ .../client/event/ServiceInstanceEvent.java | 2 +- .../ServiceInstancePreRegisteredEvent.java | 6 +- .../event/ServiceInstanceRegisteredEvent.java | 6 +- ...java => ServiceInstancesChangedEvent.java} | 22 +- .../CustomizableServiceInstanceListener.java | 54 +++ .../ServiceInstancesChangedListener.java} | 17 +- .../metadata/MetadataServiceProxyFactory.java | 84 +++++ ...ataServiceURLParamsMetadataCustomizer.java | 64 ++++ .../ServiceInstanceMetadataUtils.java | 149 ++++++++ .../dubbo/registry/client/package-info.java | 2 +- .../support/AbstractRegistryFactory.java | 9 +- .../support/ServiceOrientedRegistry.java | 348 ++++++++++++++++++ ...bo.registry.client.ServiceDiscoveryFactory | 1 + .../org.apache.dubbo.event.EventListener | 1 + ....registry.client.ServiceInstanceCustomizer | 1 + .../client/CompositeServiceDiscoveryTest.java | 221 ----------- .../client/DefaultServiceInstanceTest.java | 2 +- .../EventPublishingServiceDiscoveryTest.java | 164 +++++++++ .../EventPublishingServiceRegistryTest.java | 77 ---- .../client/InMemoryServiceDiscovery.java | 41 ++- .../InMemoryServiceDiscoveryFactory.java | 38 ++ .../client/ServiceDiscoveryFactoryTest.java | 68 ++++ .../registry/client/ServiceDiscoveryTest.java | 125 ++++--- .../ServiceInstanceMetadataUtilsTest.java | 78 ++++ .../support/ServiceOrientedRegistryTest.java | 173 +++++++++ ...bo.registry.client.ServiceDiscoveryFactory | 1 + 43 files changed, 2210 insertions(+), 753 deletions(-) delete mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/CompositeServiceDiscovery.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceDiscoveryFactory.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceDiscovery.java delete mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceRegistry.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryFactory.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceCustomizer.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceMetadataCustomizer.java delete mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceRegistry.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStartedEvent.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStartingEvent.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStoppedEvent.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStoppingEvent.java rename dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/{ServiceDiscoveryChangeEvent.java => ServiceInstancesChangedEvent.java} (78%) create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/CustomizableServiceInstanceListener.java rename dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/{ServiceDiscoveryChangeListener.java => listener/ServiceInstancesChangedListener.java} (61%) create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxyFactory.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLParamsMetadataCustomizer.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtils.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscoveryFactory create mode 100644 dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/services/org.apache.dubbo.event.EventListener create mode 100644 dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceInstanceCustomizer delete mode 100644 dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/CompositeServiceDiscoveryTest.java create mode 100644 dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/EventPublishingServiceDiscoveryTest.java delete mode 100644 dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/EventPublishingServiceRegistryTest.java create mode 100644 dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InMemoryServiceDiscoveryFactory.java create mode 100644 dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryFactoryTest.java create mode 100644 dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtilsTest.java create mode 100644 dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/ServiceOrientedRegistryTest.java create mode 100644 dubbo-registry/dubbo-registry-api/src/test/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceDiscoveryFactory diff --git a/dubbo-registry/dubbo-registry-api/pom.xml b/dubbo-registry/dubbo-registry-api/pom.xml index d5689b334e8..44eb895b273 100644 --- a/dubbo-registry/dubbo-registry-api/pom.xml +++ b/dubbo-registry/dubbo-registry-api/pom.xml @@ -14,7 +14,8 @@ See the License for the specific language governing permissions and limitations under the License. --> - + 4.0.0 org.apache.dubbo @@ -61,6 +62,12 @@ ${project.parent.version} + + org.apache.dubbo + dubbo-metadata + ${project.parent.version} + + org.apache.curator curator-framework diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Registry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Registry.java index 835c27a291d..a35a856450b 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Registry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Registry.java @@ -18,6 +18,7 @@ import org.apache.dubbo.common.Node; import org.apache.dubbo.common.URL; +import org.apache.dubbo.registry.client.ServiceDiscovery; /** * Registry. (SPI, Prototype, ThreadSafe) @@ -26,4 +27,11 @@ * @see org.apache.dubbo.registry.support.AbstractRegistry */ public interface Registry extends Node, RegistryService { + + /** + * The parameter name of {@link ServiceDiscovery}'s type + * + * @since 2.7.3 + */ + public static final String TYPE_PARAM_NAME = "registry-type"; } \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/CompositeServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/CompositeServiceDiscovery.java deleted file mode 100644 index d01891ddb58..00000000000 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/CompositeServiceDiscovery.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.client; - -import org.apache.dubbo.common.utils.DefaultPage; -import org.apache.dubbo.common.utils.Page; -import org.apache.dubbo.registry.client.event.ServiceDiscoveryChangeListener; - -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; - -import static java.lang.String.format; -import static java.lang.String.valueOf; -import static java.util.Arrays.asList; -import static java.util.Collections.unmodifiableSet; -import static org.apache.dubbo.common.utils.CollectionUtils.isNotEmpty; -import static org.apache.dubbo.common.utils.CollectionUtils.sort; - -/** - * The serviceDiscoveries of {@link ServiceDiscovery} - * - * @since 2.7.2 - */ -public class CompositeServiceDiscovery implements ServiceDiscovery { - - private List serviceDiscoveries = new LinkedList<>(); - - public CompositeServiceDiscovery(ServiceDiscovery... serviceDiscoveries) { - this(asList(serviceDiscoveries)); - } - - public CompositeServiceDiscovery(Collection serviceDiscoveries) { - addServiceDiscoveries(serviceDiscoveries); - } - - protected void addServiceDiscoveries(Collection serviceDiscoveries) { - this.serviceDiscoveries.addAll(serviceDiscoveries); - sort(this.serviceDiscoveries); - } - - @Override - public Set getServices() { - Set allServiceNames = new TreeSet<>(); - for (ServiceDiscovery serviceDiscovery : serviceDiscoveries) { - Set serviceNames = serviceDiscovery.getServices(); - if (isNotEmpty(serviceNames)) { - allServiceNames.addAll(serviceNames); - } - } - return unmodifiableSet(allServiceNames); - } - - @Override - public List getInstances(String serviceName) throws NullPointerException { - List serviceInstances = new LinkedList<>(); - for (ServiceDiscovery serviceDiscovery : serviceDiscoveries) { - List instances = serviceDiscovery.getInstances(serviceName); - if (isNotEmpty(instances)) { - serviceInstances.addAll(instances); - } - } - return serviceInstances; - } - - @Override - public Page getInstances(String serviceName, int offset, int requestSize, boolean healthyOnly) - throws NullPointerException, IllegalArgumentException { - DefaultPage page = new DefaultPage<>(offset, requestSize); - - int totalElements = 0; - List serviceInstances = new LinkedList<>(); - - for (ServiceDiscovery serviceDiscovery : serviceDiscoveries) { - Page p = serviceDiscovery.getInstances(serviceName, offset, requestSize, healthyOnly); - totalElements += p.getTotalSize(); - if (p.hasData()) { - serviceInstances.addAll(p.getData()); - } - } - - page.setTotalSize(totalElements); - page.setData(serviceInstances); - return page; - } - - @Override - public String toString() { - return format("%s [composite : %s]", this.getClass().getSimpleName(), valueOf(serviceDiscoveries)); - } - - @Override - public int getPriority() { - return Integer.MIN_VALUE; - } - - @Override - public void addServiceDiscoveryChangeListener(String serviceName, - ServiceDiscoveryChangeListener listener) throws NullPointerException, IllegalArgumentException { - serviceDiscoveries.forEach(serviceDiscovery -> serviceDiscovery.addServiceDiscoveryChangeListener(serviceName, listener)); - } -} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceDiscoveryFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceDiscoveryFactory.java new file mode 100644 index 00000000000..2cc6dafdde0 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceDiscoveryFactory.java @@ -0,0 +1,74 @@ +/* + * 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.client; + +import org.apache.dubbo.common.URL; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.ServiceLoader; + +import static org.apache.dubbo.common.utils.CollectionUtils.sort; + +/** + * The default implementation of {@link ServiceDiscoveryFactory} as the default extension of + * {@link ServiceDiscoveryFactory}, default elements are loaded by @link ServiceLoader Java SPI} from in different + * artifacts(jars) in the class path. + * + * @see ServiceDiscoveryFactory + * @see ServiceLoader#load(Class) + * @since 2.7.3 + */ +public class DefaultServiceDiscoveryFactory implements ServiceDiscoveryFactory { + + private final List serviceDiscoveryFactories = new LinkedList<>(); + + public DefaultServiceDiscoveryFactory() { + initServiceDiscoveryFactories(); + } + + private void initServiceDiscoveryFactories() { + ServiceLoader serviceLoader = + ServiceLoader.load(ServiceDiscoveryFactory.class, getClass().getClassLoader()); + Iterator iterator = serviceLoader.iterator(); + iterator.forEachRemaining(serviceDiscoveryFactories::add); + sort(serviceDiscoveryFactories); + } + + @Override + public boolean supports(URL connectionURL) { + return serviceDiscoveryFactories + .stream() + .filter(factory -> factory.supports(connectionURL)) + .count() > 0; + } + + @Override + public ServiceDiscovery create(URL connectionURL) { + return serviceDiscoveryFactories + .stream() + .filter(factory -> factory.supports(connectionURL)) + .findFirst() // find the highest priority one + .map(factory -> factory.create(connectionURL)) // create the original instance + .map(serviceDiscovery -> new EventPublishingServiceDiscovery(serviceDiscovery)) // wrap the event-based + .orElseThrow(() -> + new IllegalStateException("The ServiceDiscovery can't be created by the connection URL[" + + connectionURL.toFullString() + "]") // If not found + ); + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceInstance.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceInstance.java index dda1faa680c..939571992aa 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceInstance.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceInstance.java @@ -23,7 +23,7 @@ /** * The default implementation of {@link ServiceInstance}. * - * @since 2.7.2 + * @since 2.7.3 */ public class DefaultServiceInstance implements ServiceInstance { @@ -33,7 +33,7 @@ public class DefaultServiceInstance implements ServiceInstance { private final String host; - private final int port; + private Integer port; private boolean enabled; @@ -41,7 +41,10 @@ public class DefaultServiceInstance implements ServiceInstance { private Map metadata = new HashMap<>(); - public DefaultServiceInstance(String id, String serviceName, String host, int port) { + public DefaultServiceInstance(String id, String serviceName, String host, Integer port) { + if (port != null && port.intValue() < 1) { + throw new IllegalArgumentException("The port must be greater than zero!"); + } this.id = id; this.serviceName = serviceName; this.host = host; @@ -50,7 +53,7 @@ public DefaultServiceInstance(String id, String serviceName, String host, int po this.healthy = true; } - public DefaultServiceInstance(String serviceName, String host, int port) { + public DefaultServiceInstance(String serviceName, String host, Integer port) { this(null, serviceName, host, port); } @@ -69,8 +72,12 @@ public String getHost() { return host; } + public void setPort(Integer port) { + this.port = port; + } + @Override - public int getPort() { + public Integer getPort() { return port; } @@ -106,16 +113,18 @@ public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof DefaultServiceInstance)) return false; DefaultServiceInstance that = (DefaultServiceInstance) o; - return getPort() == that.getPort() && + return isEnabled() == that.isEnabled() && + isHealthy() == that.isHealthy() && Objects.equals(getId(), that.getId()) && Objects.equals(getServiceName(), that.getServiceName()) && Objects.equals(getHost(), that.getHost()) && + Objects.equals(getPort(), that.getPort()) && Objects.equals(getMetadata(), that.getMetadata()); } @Override public int hashCode() { - return Objects.hash(getId(), getServiceName(), getHost(), getPort(), getMetadata()); + return Objects.hash(getId(), getServiceName(), getHost(), getPort(), isEnabled(), isHealthy(), getMetadata()); } @Override diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceDiscovery.java new file mode 100644 index 00000000000..057ae0b42e9 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceDiscovery.java @@ -0,0 +1,296 @@ +/* + * 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.client; + +import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.common.utils.Page; +import org.apache.dubbo.event.Event; +import org.apache.dubbo.event.EventDispatcher; +import org.apache.dubbo.registry.client.event.ServiceDiscoveryStartedEvent; +import org.apache.dubbo.registry.client.event.ServiceDiscoveryStartingEvent; +import org.apache.dubbo.registry.client.event.ServiceDiscoveryStoppedEvent; +import org.apache.dubbo.registry.client.event.ServiceDiscoveryStoppingEvent; +import org.apache.dubbo.registry.client.event.ServiceInstancePreRegisteredEvent; +import org.apache.dubbo.registry.client.event.ServiceInstanceRegisteredEvent; +import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; + +import static java.util.Optional.empty; +import static java.util.Optional.of; + +/** + * The decorating implementation of {@link ServiceDiscovery} to publishe the {@link Event Dubbo event} when some actions are + * executing, including: + *

    + *
  • Lifecycle actions:
  • + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    ActionbeforeAfter
    {@link #START_ACTION start}{@link ServiceDiscoveryStartingEvent}{@link ServiceDiscoveryStartedEvent}
    {@link #STOP_ACTION stop}{@link ServiceDiscoveryStoppingEvent}{@link ServiceDiscoveryStoppedEvent}
    + *
  • Registration actions:
  • + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    ActionbeforeAfter
    {@link #REGISTER_ACTION register}{@link ServiceInstancePreRegisteredEvent}{@link ServiceInstanceRegisteredEvent}
    {@link #UPDATE_ACTION update}N/AN/A
    {@link #UNREGISTER_ACTION unregister}N/AN/A
    + *
+ * + * @see ServiceDiscovery + * @see ServiceDiscoveryStartingEvent + * @see ServiceDiscoveryStartedEvent + * @see ServiceInstancePreRegisteredEvent + * @see ServiceInstanceRegisteredEvent + * @see ServiceDiscoveryStoppingEvent + * @see ServiceDiscoveryStoppedEvent + * @since 2.7.3 + */ +class EventPublishingServiceDiscovery implements ServiceDiscovery { + + /** + * @see ServiceInstancePreRegisteredEvent + * @see ServiceInstanceRegisteredEvent + */ + protected static final String REGISTER_ACTION = "register"; + + protected static final String UPDATE_ACTION = "update"; + + protected static final String UNREGISTER_ACTION = "unregister"; + + /** + * @see ServiceDiscoveryStartingEvent + * @see ServiceDiscoveryStartedEvent + */ + protected static final String START_ACTION = "start"; + + /** + * @see ServiceDiscoveryStoppingEvent + * @see ServiceDiscoveryStoppedEvent + */ + protected static final String STOP_ACTION = "stop"; + + protected final EventDispatcher eventDispatcher = EventDispatcher.getDefaultExtension(); + + protected final AtomicBoolean started = new AtomicBoolean(false); + + protected final AtomicBoolean stopped = new AtomicBoolean(false); + + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + private final ServiceDiscovery serviceDiscovery; + + protected EventPublishingServiceDiscovery(ServiceDiscovery serviceDiscovery) { + if (serviceDiscovery == null) { + throw new NullPointerException("The ServiceDiscovery argument must not be null!"); + } + this.serviceDiscovery = serviceDiscovery; + } + + @Override + public final void register(ServiceInstance serviceInstance) throws RuntimeException { + + requireStarted(REGISTER_ACTION); + requireNotStopped(REGISTER_ACTION); + + executeWithEvents( + of(new ServiceInstancePreRegisteredEvent(serviceDiscovery, serviceInstance)), + () -> serviceDiscovery.register(serviceInstance), + of(new ServiceInstanceRegisteredEvent(serviceDiscovery, serviceInstance)) + ); + } + + @Override + public final void update(ServiceInstance serviceInstance) throws RuntimeException { + + requireStarted(UPDATE_ACTION); + requireNotStopped(UPDATE_ACTION); + + executeWithEvents( + empty(), + () -> serviceDiscovery.update(serviceInstance), + empty() + ); + } + + @Override + public final void unregister(ServiceInstance serviceInstance) throws RuntimeException { + + requireStarted(UNREGISTER_ACTION); + requireNotStopped(UNREGISTER_ACTION); + + executeWithEvents( + empty(), + () -> serviceDiscovery.unregister(serviceInstance), + empty() + ); + } + + @Override + public Set getServices() { + return serviceDiscovery.getServices(); + } + + @Override + public List getInstances(String serviceName) throws NullPointerException { + return serviceDiscovery.getInstances(serviceName); + } + + @Override + public int getTotalSizeInstances(String serviceName) throws NullPointerException { + return serviceDiscovery.getTotalSizeInstances(serviceName); + } + + @Override + public Page getInstances(String serviceName, int offset, int requestSize) throws NullPointerException, IllegalArgumentException { + return serviceDiscovery.getInstances(serviceName, offset, requestSize); + } + + @Override + public Page getInstances(String serviceName, int offset, int requestSize, boolean healthyOnly) throws NullPointerException, IllegalArgumentException { + return serviceDiscovery.getInstances(serviceName, offset, requestSize, healthyOnly); + } + + @Override + public Map> getInstances(Iterable serviceNames, int offset, int requestSize) throws NullPointerException, IllegalArgumentException { + return serviceDiscovery.getInstances(serviceNames, offset, requestSize); + } + + @Override + public String toString() { + return serviceDiscovery.toString(); + } + + @Override + public void addServiceInstancesChangedListener(String serviceName, ServiceInstancesChangedListener listener) throws NullPointerException, IllegalArgumentException { + serviceDiscovery.addServiceInstancesChangedListener(serviceName, listener); + } + + @Override + public final void start() { + + requireNotStopped(START_ACTION); + + if (isStarted()) { + if (logger.isWarnEnabled()) { + logger.warn("It's ignored to start current ServiceDiscovery, because it has been started."); + } + return; + } + + executeWithEvents( + of(new ServiceDiscoveryStartingEvent(serviceDiscovery)), + serviceDiscovery::start, + of(new ServiceDiscoveryStartedEvent(serviceDiscovery)) + ); + + // doesn't start -> started + started.compareAndSet(false, true); + } + + @Override + public final void stop() { + + requireStarted(STOP_ACTION); + + if (isStopped()) { + if (logger.isWarnEnabled()) { + logger.warn("It's ignored to stop current ServiceDiscovery, because it has been stopped."); + } + return; + } + + executeWithEvents( + of(new ServiceDiscoveryStoppingEvent(serviceDiscovery)), + serviceDiscovery::stop, + of(new ServiceDiscoveryStoppedEvent(serviceDiscovery)) + ); + + // doesn't stop -> stopped + stopped.compareAndSet(false, true); + } + + protected final void executeWithEvents(Optional beforeEvent, + Runnable action, + Optional afterEvent) { + beforeEvent.ifPresent(eventDispatcher::dispatch); + action.run(); + afterEvent.ifPresent(eventDispatcher::dispatch); + } + + public final boolean isStarted() { + return started.get(); + } + + public final boolean isStopped() { + return stopped.get(); + } + + protected void requireStarted(String action) throws IllegalStateException { + if (!isStarted()) { + throw new IllegalStateException("The action[" + action + "] is rejected, because the ServiceDiscovery is not started yet."); + } + } + + protected void requireNotStopped(String action) throws IllegalStateException { + if (isStopped()) { + throw new IllegalStateException("The action[" + action + "] is rejected, because the ServiceDiscovery is stopped already."); + } + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceRegistry.java deleted file mode 100644 index f0459281dad..00000000000 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceRegistry.java +++ /dev/null @@ -1,128 +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.client; - -import org.apache.dubbo.event.Event; -import org.apache.dubbo.event.EventDispatcher; -import org.apache.dubbo.registry.client.event.ServiceInstancePreRegisteredEvent; -import org.apache.dubbo.registry.client.event.ServiceInstanceRegisteredEvent; - -import java.util.Optional; - -import static java.util.Optional.empty; -import static java.util.Optional.of; - -/** - * The abstract {@link ServiceRegistry} implementation publishes the {@link Event Dubbo event} on methods executing. - * - * @since 2.7.2 - */ -public abstract class EventPublishingServiceRegistry implements ServiceRegistry { - - private final EventDispatcher eventDispatcher = EventDispatcher.getDefaultExtension(); - - @Override - public final void register(ServiceInstance serviceInstance) throws RuntimeException { - executeWithEvents( - of(new ServiceInstancePreRegisteredEvent(this, serviceInstance)), - () -> doRegister(serviceInstance), - of(new ServiceInstanceRegisteredEvent(this, serviceInstance)) - ); - } - - @Override - public final void update(ServiceInstance serviceInstance) throws RuntimeException { - // TODO publish event - executeWithEvents( - empty(), - () -> doUpdate(serviceInstance), - empty() - ); - } - - @Override - public final void unregister(ServiceInstance serviceInstance) throws RuntimeException { - // TODO publish event - executeWithEvents( - empty(), - () -> doUnregister(serviceInstance), - empty() - ); - } - - @Override - public final void start() { - // TODO publish event - executeWithEvents( - empty(), - this::doStart, - empty() - ); - } - - @Override - public final void stop() { - // TODO publish event - executeWithEvents( - empty(), - this::doStop, - empty() - ); - } - - protected final void executeWithEvents(Optional beforeEvent, - Runnable action, - Optional afterEvent) { - beforeEvent.ifPresent(eventDispatcher::dispatch); - action.run(); - afterEvent.ifPresent(eventDispatcher::dispatch); - } - - /** - * Registers an instance of {@link ServiceInstance}. - * - * @param serviceInstance an instance of {@link ServiceInstance} to be registered - * @throws RuntimeException if failed - */ - protected abstract void doRegister(ServiceInstance serviceInstance) throws RuntimeException; - - /** - * Updates the registered {@link ServiceInstance}. - * - * @param serviceInstance the registered {@link ServiceInstance} - * @throws RuntimeException if failed - */ - protected abstract void doUpdate(ServiceInstance serviceInstance) throws RuntimeException; - - /** - * Unregisters an instance of {@link ServiceInstance}. - * - * @param serviceInstance an instance of {@link ServiceInstance} to be deregistered - * @throws RuntimeException if failed - */ - protected abstract void doUnregister(ServiceInstance serviceInstance) throws RuntimeException; - - /** - * Starts the ServiceRegistry. This is a lifecycle method. - */ - protected abstract void doStart(); - - /** - * Stops the ServiceRegistry. This is a lifecycle method. - */ - protected abstract void doStop(); -} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscovery.java index 6a1888a4039..d5755640e92 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscovery.java @@ -16,9 +16,10 @@ */ package org.apache.dubbo.registry.client; +import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.common.utils.DefaultPage; import org.apache.dubbo.common.utils.Page; -import org.apache.dubbo.registry.client.event.ServiceDiscoveryChangeListener; +import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; import java.util.ArrayList; import java.util.Iterator; @@ -27,23 +28,60 @@ import java.util.Map; import java.util.Set; -import static java.lang.Integer.compare; import static java.util.Collections.emptyList; import static java.util.Collections.unmodifiableMap; /** * The common operations of Service Discovery * - * @since 2.7.2 + * @since 2.7.3 */ -public interface ServiceDiscovery extends Comparable { +@SPI("composite") +public interface ServiceDiscovery { + + // ==================================== Lifecycle ==================================== // /** - * A human-readable description of the implementation + * Starts the ServiceRegistry. This is a lifecycle method. + */ + void start(); + + /** + * Stops the ServiceRegistry. This is a lifecycle method. + */ + void stop(); + + // ==================================================================================== // + + // =================================== Registration =================================== // + + /** + * Registers an instance of {@link ServiceInstance}. * - * @return The description. + * @param serviceInstance an instance of {@link ServiceInstance} to be registered + * @throws RuntimeException if failed */ - String toString(); + void register(ServiceInstance serviceInstance) throws RuntimeException; + + /** + * Updates the registered {@link ServiceInstance}. + * + * @param serviceInstance the registered {@link ServiceInstance} + * @throws RuntimeException if failed + */ + void update(ServiceInstance serviceInstance) throws RuntimeException; + + /** + * Unregisters an instance of {@link ServiceInstance}. + * + * @param serviceInstance an instance of {@link ServiceInstance} to be deregistered + * @throws RuntimeException if failed + */ + void unregister(ServiceInstance serviceInstance) throws RuntimeException; + + // ==================================================================================== // + + // ==================================== Discovery ===================================== // /** * Gets all service names @@ -162,34 +200,22 @@ default Map> getInstances(Iterable service } /** - * The priority of current {@link ServiceDiscovery} + * Add an instance of {@link ServiceInstancesChangedListener} for specified service * - * @return The {@link Integer#MIN_VALUE minimum integer} indicates the highest priority, in contrast, - * the lowest priority is {@link Integer#MAX_VALUE the maximum integer} + * @param serviceName the service name + * @param listener an instance of {@link ServiceInstancesChangedListener} + * @throws NullPointerException + * @throws IllegalArgumentException */ - default int getPriority() { - return Integer.MAX_VALUE; - } + void addServiceInstancesChangedListener(String serviceName, ServiceInstancesChangedListener listener) + throws NullPointerException, IllegalArgumentException; - /** - * Compares its priority - * - * @param that {@link ServiceDiscovery} - * @return - */ - @Override - default int compareTo(ServiceDiscovery that) { - return compare(this.getPriority(), that.getPriority()); - } + // ==================================================================================== // /** - * Add an instance of {@link ServiceDiscoveryChangeListener} for specified service + * A human-readable description of the implementation * - * @param serviceName the service name - * @param listener an instance of {@link ServiceDiscoveryChangeListener} - * @throws NullPointerException - * @throws IllegalArgumentException + * @return The description. */ - void addServiceDiscoveryChangeListener(String serviceName, ServiceDiscoveryChangeListener listener) - throws NullPointerException, IllegalArgumentException; + String toString(); } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryFactory.java new file mode 100644 index 00000000000..913a3ce6c28 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryFactory.java @@ -0,0 +1,79 @@ +/* + * 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.client; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.extension.SPI; + +import static java.lang.Integer.compare; +import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; + +/** + * The Factory interface to create an instance of {@link ServiceDiscovery} + * + * @see ServiceDiscovery + * @since 2.7.3 + */ +@SPI("default") +public interface ServiceDiscoveryFactory extends Comparable { + + /** + * It indicates the current implementation supports or not in the specified {@link URL connnection url}. + * + * @param connectionURL the {@link URL connection url} + * @return if supports, return true, or false + */ + boolean supports(URL connectionURL); + + /** + * Creates an instance of {@link ServiceDiscovery} if {@link #supports(URL)} returns true, + * + * @param connectionURL the {@link URL connection url} + * @return an instance of {@link ServiceDiscovery} if supported, or null + */ + ServiceDiscovery create(URL connectionURL); + + /** + * The priority of current {@link ServiceDiscoveryFactory} + * + * @return The {@link Integer#MIN_VALUE minimum integer} indicates the highest priority, in contrast, + * the lowest priority is {@link Integer#MAX_VALUE the maximum integer} + */ + default int getPriority() { + return Integer.MAX_VALUE; + } + + /** + * Compares its priority + * + * @param that {@link ServiceDiscovery} + * @return + */ + @Override + default int compareTo(ServiceDiscoveryFactory that) { + return compare(this.getPriority(), that.getPriority()); + } + + /** + * Get the default extension of {@link ServiceDiscoveryFactory} + * + * @return non-null + */ + static ServiceDiscoveryFactory getDefaultExtension() { + return getExtensionLoader(ServiceDiscoveryFactory.class).getDefaultExtension(); + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstance.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstance.java index 9006681cfe2..bcdcfd29e66 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstance.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstance.java @@ -22,7 +22,7 @@ * The model class of an instance of a service, which is used for service registration and discovery. *

* - * @since 2.7.2 + * @since 2.7.3 */ public interface ServiceInstance { @@ -50,9 +50,9 @@ public interface ServiceInstance { /** * The port of the registered service instance. * - * @return the positive integer + * @return the positive integer if present */ - int getPort(); + Integer getPort(); /** * The enable status of the registered service instance. diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceCustomizer.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceCustomizer.java new file mode 100644 index 00000000000..976eb1aafc9 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceCustomizer.java @@ -0,0 +1,38 @@ +/* + * 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.client; + +import org.apache.dubbo.registry.client.event.ServiceInstancePreRegisteredEvent; +import org.apache.dubbo.registry.client.event.listener.CustomizableServiceInstanceListener; + +/** + * The interface to customize {@link ServiceInstance the service instance} on {@link ServiceInstancePreRegisteredEvent} + * + * @see CustomizableServiceInstanceListener + * @see ServiceInstancePreRegisteredEvent + * @see ServiceInstance#getMetadata() + * @since 2.7.3 + */ +public interface ServiceInstanceCustomizer { + + /** + * Customizes {@link ServiceInstance the service instance} + * + * @param serviceInstance {@link ServiceInstance the service instance} + */ + void customize(ServiceInstance serviceInstance); +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceMetadataCustomizer.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceMetadataCustomizer.java new file mode 100644 index 00000000000..d2077b63387 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceMetadataCustomizer.java @@ -0,0 +1,73 @@ +/* + * 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.client; + +import java.util.Map; + +import static org.apache.dubbo.common.utils.StringUtils.isBlank; + +/** + * The abstract class to customize {@link ServiceInstance#getMetadata()} the service instances' metadata} + * + * @see ServiceInstance#getMetadata() + * @see ServiceInstanceCustomizer + * @since 2.7.3 + */ +public abstract class ServiceInstanceMetadataCustomizer implements ServiceInstanceCustomizer { + + @Override + public final void customize(ServiceInstance serviceInstance) { + + Map metadata = serviceInstance.getMetadata(); + + String key = buildMetadataKey(serviceInstance); + String value = buildMetadataValue(serviceInstance); + + if (!isBlank(key) && !isBlank(value)) { + String existedValue = metadata.get(key); + boolean put = existedValue == null || isOverride(); + if (put) { + metadata.put(key, value); + } + } + } + + /** + * Build the key of metadata + * + * @param serviceInstance the instance of {@link ServiceInstance} + * @return non-null key + */ + protected abstract String buildMetadataKey(ServiceInstance serviceInstance); + + /** + * Build the value of metadata + * + * @param serviceInstance the instance of {@link ServiceInstance} + * @return non-null value + */ + protected abstract String buildMetadataValue(ServiceInstance serviceInstance); + + /** + * Is override {@link ServiceInstance#getMetadata()} the service instances' metadata} or not + * + * @return default is false + */ + protected boolean isOverride() { + return false; + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceRegistry.java deleted file mode 100644 index 07b1bfceba6..00000000000 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceRegistry.java +++ /dev/null @@ -1,66 +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.client; - -/** - * The common interface to register and unregister for a service registry - * - * @since 2.7.2 - */ -public interface ServiceRegistry { - - /** - * A human-readable description of the implementation - * - * @return The description. - */ - String toString(); - - /** - * Registers an instance of {@link ServiceInstance}. - * - * @param serviceInstance an instance of {@link ServiceInstance} to be registered - * @throws RuntimeException if failed - */ - void register(ServiceInstance serviceInstance) throws RuntimeException; - - /** - * Updates the registered {@link ServiceInstance}. - * - * @param serviceInstance the registered {@link ServiceInstance} - * @throws RuntimeException if failed - */ - void update(ServiceInstance serviceInstance) throws RuntimeException; - - /** - * Unregisters an instance of {@link ServiceInstance}. - * - * @param serviceInstance an instance of {@link ServiceInstance} to be deregistered - * @throws RuntimeException if failed - */ - void unregister(ServiceInstance serviceInstance) throws RuntimeException; - - /** - * Starts the ServiceRegistry. This is a lifecycle method. - */ - void start(); - - /** - * Stops the ServiceRegistry. This is a lifecycle method. - */ - void stop(); -} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStartedEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStartedEvent.java new file mode 100644 index 00000000000..d94204427b8 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStartedEvent.java @@ -0,0 +1,52 @@ +/* + * 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.client.event; + +import org.apache.dubbo.event.Event; +import org.apache.dubbo.registry.client.ServiceDiscovery; + +import java.util.EventObject; + +/** + * The {@link ServiceDiscovery Service Discovery} Started {@link EventObject Event} + * after {@link ServiceDiscovery#start()} execution + * + * @see ServiceDiscovery#start() + * @since 2.7.3 + */ +public class ServiceDiscoveryStartedEvent extends Event { + + /** + * Constructs a prototypical Event. + * + * @param serviceDiscovery The instance of {@link ServiceDiscovery} as source + * @throws IllegalArgumentException if source is null. + */ + public ServiceDiscoveryStartedEvent(ServiceDiscovery serviceDiscovery) { + super(serviceDiscovery); + } + + /** + * Get the instance of {@link ServiceDiscovery} as source + * + * @return the instance of {@link ServiceDiscovery} as source + */ + public ServiceDiscovery getServiceDiscovery() { + return (ServiceDiscovery) getSource(); + } + +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStartingEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStartingEvent.java new file mode 100644 index 00000000000..03fdf61cd9c --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStartingEvent.java @@ -0,0 +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.registry.client.event; + +import org.apache.dubbo.event.Event; +import org.apache.dubbo.registry.client.ServiceDiscovery; + +import java.util.EventObject; + +/** + * The {@link ServiceDiscovery Service Discovery} Starting {@link EventObject Event} + * before {@link ServiceDiscovery#start()} execution + * + * @see ServiceDiscovery#start + * @since 2.7.3 + */ +public class ServiceDiscoveryStartingEvent extends Event { + + /** + * Constructs a prototypical Event. + * + * @param serviceDiscovery The instance of {@link ServiceDiscovery} as source + * @throws IllegalArgumentException if source is null. + */ + public ServiceDiscoveryStartingEvent(ServiceDiscovery serviceDiscovery) { + super(serviceDiscovery); + } + + /** + * Get the instance of {@link ServiceDiscovery} as source + * + * @return the instance of {@link ServiceDiscovery} as source + */ + public ServiceDiscovery getServiceDiscovery() { + return (ServiceDiscovery) getSource(); + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStoppedEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStoppedEvent.java new file mode 100644 index 00000000000..f9ce0634e20 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStoppedEvent.java @@ -0,0 +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.registry.client.event; + +import org.apache.dubbo.event.Event; +import org.apache.dubbo.registry.client.ServiceDiscovery; + +import java.util.EventObject; + +/** + * The {@link ServiceDiscovery Service Discovery} Stopped {@link EventObject Event} + * after {@link ServiceDiscovery#stop()} execution + * + * @see ServiceDiscovery#stop() + * @since 2.7.3 + */ +public class ServiceDiscoveryStoppedEvent extends Event { + + /** + * Constructs a prototypical Event. + * + * @param serviceDiscovery The instance of {@link ServiceDiscovery} as source + * @throws IllegalArgumentException if source is null. + */ + public ServiceDiscoveryStoppedEvent(ServiceDiscovery serviceDiscovery) { + super(serviceDiscovery); + } + + /** + * Get the instance of {@link ServiceDiscovery} as source + * + * @return the instance of {@link ServiceDiscovery} as source + */ + public ServiceDiscovery getServiceDiscovery() { + return (ServiceDiscovery) getSource(); + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStoppingEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStoppingEvent.java new file mode 100644 index 00000000000..d6e3e248fa2 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStoppingEvent.java @@ -0,0 +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.registry.client.event; + +import org.apache.dubbo.event.Event; +import org.apache.dubbo.registry.client.ServiceDiscovery; + +import java.util.EventObject; + +/** + * The {@link ServiceDiscovery Service Discovery} Stopping {@link EventObject Event} + * before {@link ServiceDiscovery#stop()} execution + * + * @see ServiceDiscovery#stop() + * @since 2.7.3 + */ +public class ServiceDiscoveryStoppingEvent extends Event { + + /** + * Constructs a prototypical Event. + * + * @param serviceDiscovery The instance of {@link ServiceDiscovery} as source + * @throws IllegalArgumentException if source is null. + */ + public ServiceDiscoveryStoppingEvent(ServiceDiscovery serviceDiscovery) { + super(serviceDiscovery); + } + + /** + * Get the instance of {@link ServiceDiscovery} as source + * + * @return the instance of {@link ServiceDiscovery} as source + */ + public ServiceDiscovery getServiceDiscovery() { + return (ServiceDiscovery) getSource(); + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstanceEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstanceEvent.java index eec9d06ac79..2533641d16b 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstanceEvent.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstanceEvent.java @@ -22,7 +22,7 @@ /** * The {@link Event Dubbo event} for {@link ServiceInstance an service instance} * - * @since 2.7.2 + * @since 2.7.3 */ public abstract class ServiceInstanceEvent extends Event { diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancePreRegisteredEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancePreRegisteredEvent.java index ef1151ad8fa..5bdc1edd08d 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancePreRegisteredEvent.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancePreRegisteredEvent.java @@ -16,14 +16,14 @@ */ package org.apache.dubbo.registry.client.event; +import org.apache.dubbo.registry.client.ServiceDiscovery; import org.apache.dubbo.registry.client.ServiceInstance; -import org.apache.dubbo.registry.client.ServiceRegistry; /** - * The before-{@link ServiceRegistry#register(ServiceInstance) register} event for {@link ServiceInstance} + * The before-{@link ServiceDiscovery#register(ServiceInstance) register} event for {@link ServiceInstance} * - * @since 2.7.2 + * @since 2.7.3 */ public class ServiceInstancePreRegisteredEvent extends ServiceInstanceEvent { diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstanceRegisteredEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstanceRegisteredEvent.java index f359d41376a..cb2f2181450 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstanceRegisteredEvent.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstanceRegisteredEvent.java @@ -16,14 +16,14 @@ */ package org.apache.dubbo.registry.client.event; +import org.apache.dubbo.registry.client.ServiceDiscovery; import org.apache.dubbo.registry.client.ServiceInstance; -import org.apache.dubbo.registry.client.ServiceRegistry; /** - * The after-{@link ServiceRegistry#register(ServiceInstance) register} event for {@link ServiceInstance} + * The after-{@link ServiceDiscovery#register(ServiceInstance) register} event for {@link ServiceInstance} * - * @since 2.7.2 + * @since 2.7.3 */ public class ServiceInstanceRegisteredEvent extends ServiceInstanceEvent { diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryChangeEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancesChangedEvent.java similarity index 78% rename from dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryChangeEvent.java rename to dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancesChangedEvent.java index 1bbf768081c..03fe3f0d1fd 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryChangeEvent.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancesChangedEvent.java @@ -18,6 +18,7 @@ import org.apache.dubbo.event.Event; import org.apache.dubbo.registry.client.ServiceInstance; +import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; import java.util.Collection; import java.util.EventObject; @@ -25,29 +26,26 @@ import static java.util.Collections.unmodifiableCollection; /** - * The Service Discovery Change {@link EventObject Event} + * The Service Instances Changed {@link EventObject Event} cause by service * - * @see ServiceDiscoveryChangeListener - * @since 2.7.2 + * @see ServiceInstancesChangedListener + * @since 2.7.3 */ -public class ServiceDiscoveryChangeEvent extends Event { +public class ServiceInstancesChangedEvent extends Event { private final String serviceName; private final Collection serviceInstances; - private final long timestamp; - /** * @param serviceName The name of service that was changed * @param serviceInstances all {@link ServiceInstance service instances} * @throws IllegalArgumentException if source is null. */ - public ServiceDiscoveryChangeEvent(String serviceName, Collection serviceInstances) { + public ServiceInstancesChangedEvent(String serviceName, Collection serviceInstances) { super(serviceName); this.serviceName = serviceName; this.serviceInstances = unmodifiableCollection(serviceInstances); - this.timestamp = System.currentTimeMillis(); } /** @@ -64,10 +62,4 @@ public Collection getServiceInstances() { return serviceInstances; } - /** - * Return the system time in milliseconds when the event happened. - */ - public long getTimestamp() { - return this.timestamp; - } -} +} \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/CustomizableServiceInstanceListener.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/CustomizableServiceInstanceListener.java new file mode 100644 index 00000000000..6bea21dae76 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/CustomizableServiceInstanceListener.java @@ -0,0 +1,54 @@ +/* + * 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.client.event.listener; + +import org.apache.dubbo.event.EventListener; +import org.apache.dubbo.registry.client.ServiceInstance; +import org.apache.dubbo.registry.client.ServiceInstanceCustomizer; +import org.apache.dubbo.registry.client.event.ServiceInstancePreRegisteredEvent; + +import java.util.Iterator; +import java.util.ServiceLoader; + +import static java.util.ServiceLoader.load; + + +/** + * An {@link EventListener event listener} to customize {@link ServiceInstance the service instance} by the instances of + * {@link ServiceInstanceCustomizer} {@link ServiceLoader SPI}. + * + * @see EventListener + * @see ServiceInstancePreRegisteredEvent + * @see ServiceInstanceCustomizer + * @since 2.7.3 + */ +public class CustomizableServiceInstanceListener implements EventListener { + + @Override + public void onEvent(ServiceInstancePreRegisteredEvent event) { + + ServiceLoader customizers = load(ServiceInstanceCustomizer.class); + + Iterator iterator = customizers.iterator(); + + while (iterator.hasNext()) { + ServiceInstanceCustomizer customizer = iterator.next(); + // customizes + customizer.customize(event.getServiceInstance()); + } + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryChangeListener.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListener.java similarity index 61% rename from dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryChangeListener.java rename to dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListener.java index 654f069ff02..50bd73bd0ab 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryChangeListener.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListener.java @@ -14,22 +14,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.registry.client.event; +package org.apache.dubbo.registry.client.event.listener; import org.apache.dubbo.event.EventListener; +import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent; /** - * The Service Discovery Change {@link EventListener Event Listener} + * The Service Discovery Changed {@link EventListener Event Listener} * - * @see ServiceDiscoveryChangeEvent - * @since 2.7.2 + * @see ServiceInstancesChangedEvent + * @since 2.7.3 */ -public interface ServiceDiscoveryChangeListener extends EventListener { +public interface ServiceInstancesChangedListener extends EventListener { /** - * On {@link ServiceDiscoveryChangeEvent the service change event} + * On {@link ServiceInstancesChangedEvent the service instances change event} * - * @param event {@link ServiceDiscoveryChangeEvent} + * @param event {@link ServiceInstancesChangedEvent} */ - void onEvent(ServiceDiscoveryChangeEvent event); + void onEvent(ServiceInstancesChangedEvent event); } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxyFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxyFactory.java new file mode 100644 index 00000000000..d2f6e649458 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxyFactory.java @@ -0,0 +1,84 @@ +/* + * 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.client.metadata; + +import org.apache.dubbo.common.URLBuilder; +import org.apache.dubbo.metadata.MetadataService; +import org.apache.dubbo.registry.client.ServiceInstance; +import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.Protocol; +import org.apache.dubbo.rpc.ProxyFactory; + +import com.alibaba.fastjson.JSON; + +import java.lang.reflect.Proxy; +import java.util.HashMap; +import java.util.Map; + +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; +import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; + +/** + * The factory of {@link MetadataService}'s {@link Proxy} + * + * @since 2.7.3 + */ +public class MetadataServiceProxyFactory { + + private static final String DUBBO_METADATA_SERVICE_PARAMS_KEY = "dubbo.metadata-service.params"; + + private final Protocol protocol; + + private final ProxyFactory proxyFactory; + + private Map> metadataServiceCache = new HashMap<>(); + + public MetadataServiceProxyFactory() { + this.protocol = getExtensionLoader(Protocol.class).getAdaptiveExtension(); + this.proxyFactory = getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + } + + public MetadataService createProxy(ServiceInstance serviceInstance) { + + URLBuilder urlBuilder = createURLBuilder(serviceInstance); + + Invoker invoker = this.protocol.refer(MetadataService.class, urlBuilder.build()); + + return proxyFactory.getProxy(invoker); + } + + + private URLBuilder createURLBuilder(ServiceInstance serviceInstance) { + String serviceName = serviceInstance.getServiceName(); + Map metadata = serviceInstance.getMetadata(); + String params = metadata.get(DUBBO_METADATA_SERVICE_PARAMS_KEY); + Map paramsMap = (Map) JSON.parse(params); + URLBuilder urlBuilder = new URLBuilder() + .setProtocol(paramsMap.get(PROTOCOL_KEY)) + .setHost(serviceInstance.getHost()) + .setPort(serviceInstance.getPort()) + .setPath(MetadataService.class.getName()) + .addParameter(GROUP_KEY, serviceName); + + // add parameters + metadata.forEach((name, value) -> urlBuilder.addParameter(name, value)); + + return urlBuilder; + } + +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLParamsMetadataCustomizer.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLParamsMetadataCustomizer.java new file mode 100644 index 00000000000..065b072f4be --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLParamsMetadataCustomizer.java @@ -0,0 +1,64 @@ +/* + * 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.client.metadata; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.metadata.LocalMetadataService; +import org.apache.dubbo.metadata.MetadataService; +import org.apache.dubbo.registry.client.ServiceInstance; +import org.apache.dubbo.registry.client.ServiceInstanceMetadataCustomizer; + +import java.util.List; + +import static org.apache.dubbo.metadata.MetadataService.toURLs; +import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getMetadataServiceParameter; + +/** + * An {@link ServiceInstanceMetadataCustomizer} to customize the {@link URL urls} of {@link MetadataService} + * into {@link ServiceInstance#getMetadata() the service instances' metadata} + * + * @see ServiceInstanceMetadataCustomizer + * @since 2.7.3 + */ +public class MetadataServiceURLParamsMetadataCustomizer extends ServiceInstanceMetadataCustomizer { + + /** + * The key of metadata JSON of {@link MetadataService}'s {@link URL} + */ + public static String METADATA_SERVICE_URL_PARAMS_KEY = "dubbo.metadata-service.url-params"; + + @Override + public String buildMetadataKey(ServiceInstance serviceInstance) { + return METADATA_SERVICE_URL_PARAMS_KEY; + } + + @Override + public String buildMetadataValue(ServiceInstance serviceInstance) { + + LocalMetadataService localMetadataService = LocalMetadataService.getDefaultExtension(); + + String serviceInterface = MetadataService.class.getName(); + + String group = serviceInstance.getServiceName(); + + String version = MetadataService.VERSION; + + List urls = localMetadataService.getExportedURLs(serviceInterface, group, version); + + return getMetadataServiceParameter(toURLs(urls)); + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtils.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtils.java new file mode 100644 index 00000000000..1d4f24ee9be --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtils.java @@ -0,0 +1,149 @@ +/* + * 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.client.metadata; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.utils.StringUtils; +import org.apache.dubbo.metadata.MetadataService; +import org.apache.dubbo.registry.client.ServiceInstance; + +import com.alibaba.fastjson.JSON; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static java.lang.String.format; +import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.RpcConstants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.common.utils.StringUtils.isBlank; +import static org.apache.dubbo.remoting.Constants.BIND_IP_KEY; +import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY; + +/** + * The Utilities class for the {@link ServiceInstance#getMetadata() metadata of the service instance} + * + * @see ServiceInstance#getMetadata() + * @see MetadataService + * @see URL + * @since 2.7.3 + */ +public class ServiceInstanceMetadataUtils { + + /** + * The prefix of protocols + */ + public static final String PROTOCOL_PREFIX = "dubbo.protocols."; + + /** + * The name {@link String#format(String, Object...) format pattern} for the protocol port + */ + public static String PROTOCOL_PORT_METADATA_KEY_PATTERN = PROTOCOL_PREFIX + "%s.port"; + + /** + * The required {@link URL} parameter names of {@link MetadataService} + */ + private static String[] METADATA_SERVICE_URL_PARAM_NAMES = { + APPLICATION_KEY, + BIND_IP_KEY, + BIND_PORT_KEY, + DUBBO_VERSION_KEY, + RELEASE_KEY, + SIDE_KEY, + VERSION_KEY + }; + + /** + * Build the metadata key of the protocol port + * + * @param protocol the name of protocol + * @return non-null + */ + public static String protocolPortMetadataKey(String protocol) { + return format(PROTOCOL_PORT_METADATA_KEY_PATTERN, protocol); + } + + /** + * The protocol port from {@link ServiceInstance the specified service instance} + * + * @param serviceInstance {@link ServiceInstance the specified service instance} + * @param protocol the protocol name + * @return The protocol port if found, or null + */ + public static Integer getProtocolPort(ServiceInstance serviceInstance, String protocol) { + Map protocolPorts = getProtocolPorts(serviceInstance); + return protocolPorts.get(protocol); + } + + /** + * Get a {@link Map} of the protocol ports from the metadata {@link Map} + * + * @param serviceInstance the {@link ServiceInstance service instance} + * @return the key is the name of protocol, and the value is the port of protocol + */ + public static Map getProtocolPorts(ServiceInstance serviceInstance) { + return getProtocolPorts(serviceInstance.getMetadata()); + } + + /** + * Get a {@link Map} of the protocol ports from the metadata {@link Map} + * + * @param metadata the metadata {@link Map} + * @return the key is the name of protocol, and the value is the port of protocol + */ + public static Map getProtocolPorts(Map metadata) { + Map protocolPorts = new LinkedHashMap<>(); + metadata.forEach((key, value) -> { + if (key.startsWith(PROTOCOL_PREFIX)) { + String[] parts = StringUtils.split(key, '.'); + String protocol = parts[2]; + protocolPorts.put(protocol, Integer.valueOf(value)); + } + }); + return protocolPorts; + } + + public static String getMetadataServiceParameter(List urls) { + Map> params = new HashMap<>(); + + urls.forEach(url -> { + String protocol = url.getProtocol(); + params.put(protocol, getParams(url, METADATA_SERVICE_URL_PARAM_NAMES)); + }); + + if (params.isEmpty()) { + return null; + } + + return JSON.toJSONString(params); + } + + private static Map getParams(URL url, String... parameterNames) { + Map params = new LinkedHashMap<>(); + for (String parameterName : parameterNames) { + String parameterValue = url.getParameter(parameterName); + if (!isBlank(parameterName)) { + params.put(parameterName, parameterValue); + } + } + return params; + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/package-info.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/package-info.java index 3283c3c0c72..7057c3b64aa 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/package-info.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/package-info.java @@ -18,6 +18,6 @@ * * The inspiration of service registration and discovery comes from * Spring Cloud Commons. * - * @since 2.7.2 + * @since 2.7.3 */ package org.apache.dubbo.registry.client; \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java index 06915098da1..2b2dab7a7b4 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java @@ -99,8 +99,13 @@ public Registry getRegistry(URL url) { if (registry != null) { return registry; } - //create registry by spi/ioc - registry = createRegistry(url); + // creates an instance of ServiceOrientedRegistry if supported + // since 2.7.3 + registry = ServiceOrientedRegistry.create(url); + if (registry == null) { // If not supported, create the default Registry + //create registry by spi/ioc + registry = createRegistry(url); + } if (registry == null) { throw new IllegalStateException("Can not create registry " + url); } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java new file mode 100644 index 00000000000..8de2a98a737 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java @@ -0,0 +1,348 @@ +/* + * 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.support; + +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.LocalMetadataService; +import org.apache.dubbo.metadata.MetadataService; +import org.apache.dubbo.metadata.ServiceNameMapping; +import org.apache.dubbo.registry.NotifyListener; +import org.apache.dubbo.registry.Registry; +import org.apache.dubbo.registry.client.ServiceDiscovery; +import org.apache.dubbo.registry.client.ServiceDiscoveryFactory; +import org.apache.dubbo.registry.client.ServiceInstance; +import org.apache.dubbo.registry.client.metadata.MetadataServiceProxyFactory; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import static java.util.Collections.emptyList; +import static java.util.Collections.unmodifiableSet; +import static java.util.stream.Collectors.toSet; +import static java.util.stream.Stream.of; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; +import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.utils.CollectionUtils.isEmpty; +import static org.apache.dubbo.common.utils.CollectionUtils.isNotEmpty; +import static org.apache.dubbo.common.utils.StringUtils.split; +import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getProtocolPort; + +/** + * Service-Oriented {@link Registry} that is dislike the traditional {@link Registry} will not communicate to + * registry immediately instead of persisting into the metadata's repository when the Dubbo service exports. + * The metadata repository will be used as the data source of Dubbo Metadata service that is about to export and be + * subscribed by the consumers. + *

+ * + * @see ServiceDiscovery + * @see FailbackRegistry + * @since 2.7.3 + */ +public class ServiceOrientedRegistry extends FailbackRegistry { + + /** + * The parameter value of {@link ServiceDiscovery}'s type + */ + public static final String TYPE_PARAM_VALUE = "service"; + + /** + * The parameter name of the subscribed service names + */ + public static final String SUBSCRIBED_SERVICE_NAMES_PARAM_NAME = "subscribed-services"; + + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + private final ServiceDiscovery serviceDiscovery; + + private final Set subscribedServices; + + private final ServiceNameMapping serviceNameMapping; + + private final LocalMetadataService localMetadataService; + + private final MetadataServiceProxyFactory metadataServiceProxyFactory; + + + public ServiceOrientedRegistry(URL url) { + super(url); + this.serviceDiscovery = buildServiceDiscovery(url); + this.subscribedServices = buildSubscribedServices(url); + this.serviceNameMapping = ServiceNameMapping.getDefaultExtension(); + this.localMetadataService = LocalMetadataService.getDefaultExtension(); + this.metadataServiceProxyFactory = new MetadataServiceProxyFactory(); + } + + private Set buildSubscribedServices(URL url) { + String[] subscribedServices = split(url.getParameter(SUBSCRIBED_SERVICE_NAMES_PARAM_NAME), ','); + return unmodifiableSet( + of(subscribedServices) + .map(String::trim) + .filter(StringUtils::isNotEmpty) + .collect(toSet())); + } + + private ServiceDiscovery buildServiceDiscovery(URL url) { + ServiceDiscoveryFactory serviceDiscoveryFactory = ServiceDiscoveryFactory.getDefaultExtension(); + ServiceDiscovery serviceDiscovery = serviceDiscoveryFactory.create(url); + serviceDiscovery.start(); + return serviceDiscovery; + } + + protected boolean shouldRegister(URL url) { + String side = url.getParameter(SIDE_KEY); + + boolean should = PROVIDER_SIDE.equals(side); // Only register the Provider. + + if (!should) { + if (logger.isDebugEnabled()) { + logger.debug(String.format("The URL[%s] should not be registered.", url.toString())); + } + } + + return should; + } + + @Override + public void doRegister(URL url) { + if (!shouldRegister(url)) { + return; + } + if (localMetadataService.exportURL(url)) { + if (logger.isInfoEnabled()) { + logger.info(String.format("The URL[%s] registered successfully.", url.toString())); + } + } else { + if (logger.isWarnEnabled()) { + logger.info(String.format("The URL[%s] has been registered.", url.toString())); + } + } + } + + @Override + public void doUnregister(URL url) { + if (!shouldRegister(url)) { + return; + } + if (localMetadataService.unexportURL(url)) { + if (logger.isInfoEnabled()) { + logger.info(String.format("The URL[%s] deregistered successfully.", url.toString())); + } + } else { + if (logger.isWarnEnabled()) { + logger.info(String.format("The URL[%s] has been deregistered.", url.toString())); + } + } + } + + @Override + public void doSubscribe(URL url, NotifyListener listener) { + subscribeURLs(url, listener); + } + + @Override + public void doUnsubscribe(URL url, NotifyListener listener) { + localMetadataService.unsubscribeURL(url); + } + + @Override + public boolean isAvailable() { + return !serviceDiscovery.getServices().isEmpty(); + } + + @Override + public void destroy() { + super.destroy(); + // stop ServiceDiscovery + serviceDiscovery.stop(); + } + + protected void subscribeURLs(URL url, NotifyListener listener) { + + Set serviceNames = getServices(url); + + serviceNames.forEach(serviceName -> subscribeURLs(url, listener, serviceName)); + + localMetadataService.subscribeURL(url); + } + + protected void subscribeURLs(URL url, NotifyListener listener, String serviceName) { + + List serviceInstances = serviceDiscovery.getInstances(serviceName); + + subscribeURLs(url, listener, serviceName, serviceInstances); + + // Add Listener + serviceDiscovery.addServiceInstancesChangedListener(serviceName, event -> { + subscribeURLs(url, listener, event.getServiceName(), new ArrayList<>(event.getServiceInstances())); + }); + } + + protected void subscribeURLs(URL url, NotifyListener listener, String serviceName, + Collection serviceInstances) { + + if (isEmpty(serviceInstances)) { + logger.warn(String.format("There is no instance in service[name : %s]", serviceName)); + return; + } + + List subscribedURLs = getSubscribedURLs(url, serviceInstances); + + listener.notify(subscribedURLs); + } + + + private List getSubscribedURLs(URL url, Collection instances) { + + List subscribedURLs = new LinkedList<>(); + + List serviceInstances = new ArrayList<>(instances); + + Iterator iterator = serviceInstances.iterator(); + + List templateURLs = null; + + // try to get the exported URLs from every instance until it's successful. + + while (iterator.hasNext()) { + + ServiceInstance serviceInstance = iterator.next(); + + templateURLs = getSubscribedURLs(url, serviceInstance); + if (isNotEmpty(templateURLs)) { + // templateURLs as the first result should be added into subscribedURLs + subscribedURLs.addAll(templateURLs); + break; + } + } + + // If templateURLs is not empty, duplicate it multiple times with different hosts and ports + + if (isNotEmpty(templateURLs)) { + + templateURLs.forEach(templateURL -> { + + String protocol = templateURL.getProtocol(); + + while (iterator.hasNext()) { + ServiceInstance serviceInstance = iterator.next(); + + String host = serviceInstance.getHost(); + Integer port = getProtocolPort(serviceInstance, protocol); + + if (port == null) { + if (logger.isWarnEnabled()) { + logger.warn(String.format("The protocol[%s] port of Dubbo service instance[host : %s] " + + "can't be resolved", protocol, host)); + } + continue; + } + + URL subscribedURL = new URL(protocol, host, port, templateURL.getParameters()); + subscribedURLs.add(subscribedURL); + } + }); + } + + + return subscribedURLs; + } + + private List getSubscribedURLs(URL url, ServiceInstance serviceInstance) { + String serviceInterface = url.getServiceInterface(); + String group = url.getParameter(GROUP_KEY); + String version = url.getParameter(VERSION_KEY); + // The subscribed protocol may be null + String protocol = url.getParameter(PROTOCOL_KEY); + + List exportedURLs = emptyList(); + + try { + MetadataService metadataService = metadataServiceProxyFactory.createProxy(serviceInstance); + List urls = metadataService.getExportedURLs(serviceInterface, group, version, protocol); + exportedURLs = urls.stream().map(URL::valueOf).collect(Collectors.toList()); + } catch (Throwable e) { + if (logger.isErrorEnabled()) { + logger.error(e.getMessage(), e); + } + } + + return exportedURLs; + } + + + protected Set getServices(URL subscribedURL) { + Set serviceNames = getSubscribedServices(); + if (isEmpty(serviceNames)) { + serviceNames = findMappedServices(subscribedURL); + } + return serviceNames; + } + + /** + * Get the subscribed service names + * + * @return non-null + */ + public Set getSubscribedServices() { + return subscribedServices; + } + + /** + * Get the mapped services name by the specified {@link URL} + * + * @param subscribedURL + * @return + */ + protected Set findMappedServices(URL subscribedURL) { + String serviceInterface = subscribedURL.getServiceInterface(); + String group = subscribedURL.getParameter(GROUP_KEY); + String version = subscribedURL.getParameter(VERSION_KEY); + String protocol = subscribedURL.getProtocol(); + return serviceNameMapping.get(serviceInterface, group, version, protocol); + } + + /** + * Create an instance of {@link ServiceOrientedRegistry} if supported + * + * @param registryURL the {@link URL url} of registry + * @return null if not supported + */ + public static ServiceOrientedRegistry create(URL registryURL) { + return supports(registryURL) ? new ServiceOrientedRegistry(registryURL) : null; + } + + /** + * Supports or not ? + * + * @param registryURL the {@link URL url} of registry + * @return if supported, return true, or false + */ + public static boolean supports(URL registryURL) { + return TYPE_PARAM_VALUE.equalsIgnoreCase(registryURL.getParameter(TYPE_PARAM_NAME)); + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscoveryFactory b/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscoveryFactory new file mode 100644 index 00000000000..d30ea0c1866 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscoveryFactory @@ -0,0 +1 @@ +default=org.apache.dubbo.registry.client.DefaultServiceDiscoveryFactory \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/services/org.apache.dubbo.event.EventListener b/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/services/org.apache.dubbo.event.EventListener new file mode 100644 index 00000000000..f2d0579d623 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/services/org.apache.dubbo.event.EventListener @@ -0,0 +1 @@ +org.apache.dubbo.registry.client.event.listener.CustomizableServiceInstanceListener \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceInstanceCustomizer b/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceInstanceCustomizer new file mode 100644 index 00000000000..a5968f9fb71 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceInstanceCustomizer @@ -0,0 +1 @@ +org.apache.dubbo.registry.client.metadata.MetadataServiceURLParamsMetadataCustomizer \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/CompositeServiceDiscoveryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/CompositeServiceDiscoveryTest.java deleted file mode 100644 index 1ed3f203b77..00000000000 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/CompositeServiceDiscoveryTest.java +++ /dev/null @@ -1,221 +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.client; - -import org.apache.dubbo.common.utils.Page; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; - -import static java.lang.Integer.MIN_VALUE; -import static java.util.Arrays.asList; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * {@link CompositeServiceDiscovery} Test - * - * @since 2.7.2 - */ -public class CompositeServiceDiscoveryTest { - - private InMemoryServiceDiscovery instance = new InMemoryServiceDiscovery(); - - private CompositeServiceDiscovery serviceDiscovery; - - @BeforeEach - public void init() { - serviceDiscovery = new CompositeServiceDiscovery(instance); - } - - @Test - public void testToString() { - assertEquals("CompositeServiceDiscovery [composite : [InMemoryServiceDiscovery]]", serviceDiscovery.toString()); - } - - @Test - public void testGetPriority() { - assertEquals(MIN_VALUE, serviceDiscovery.getPriority()); - } - - @Test - public void testGetServices() { - instance.addServiceInstance(new DefaultServiceInstance("A", "127.0.0.1", 8080)); - instance.addServiceInstance(new DefaultServiceInstance("B", "127.0.0.1", 8080)); - instance.addServiceInstance(new DefaultServiceInstance("C", "127.0.0.1", 8080)); - assertEquals(new HashSet<>(asList("A", "B", "C")), instance.getServices()); - } - - @Test - public void testGetInstances() { - - List instances = asList( - new DefaultServiceInstance("A", "127.0.0.1", 8080), - new DefaultServiceInstance("A", "127.0.0.1", 8081), - new DefaultServiceInstance("A", "127.0.0.1", 8082) - ); - - instances.forEach(instance::addServiceInstance); - - // Duplicated - instance.addServiceInstance(new DefaultServiceInstance("A", "127.0.0.1", 8080)); - // Duplicated - instance.addServiceInstance(new DefaultServiceInstance("A", "127.0.0.1", 8081)); - - // offset starts 0 - int offset = 0; - // requestSize > total elements - int requestSize = 5; - - Page page = serviceDiscovery.getInstances("A", offset, requestSize); - assertEquals(0, page.getRequestOffset()); - assertEquals(5, page.getRequestSize()); - assertEquals(3, page.getTotalSize()); - assertEquals(3, page.getData().size()); - assertTrue(page.hasData()); - - for (ServiceInstance instance : page.getData()) { - assertTrue(instances.contains(instance)); - } - - // requestSize < total elements - requestSize = 2; - - page = serviceDiscovery.getInstances("A", offset, requestSize); - assertEquals(0, page.getRequestOffset()); - assertEquals(2, page.getRequestSize()); - assertEquals(3, page.getTotalSize()); - assertEquals(2, page.getData().size()); - assertTrue(page.hasData()); - - for (ServiceInstance instance : page.getData()) { - assertTrue(instances.contains(instance)); - } - - offset = 1; - page = serviceDiscovery.getInstances("A", offset, requestSize); - assertEquals(1, page.getRequestOffset()); - assertEquals(2, page.getRequestSize()); - assertEquals(3, page.getTotalSize()); - assertEquals(2, page.getData().size()); - assertTrue(page.hasData()); - - for (ServiceInstance instance : page.getData()) { - assertTrue(instances.contains(instance)); - } - - offset = 2; - page = serviceDiscovery.getInstances("A", offset, requestSize); - assertEquals(2, page.getRequestOffset()); - assertEquals(2, page.getRequestSize()); - assertEquals(3, page.getTotalSize()); - assertEquals(1, page.getData().size()); - assertTrue(page.hasData()); - - offset = 3; - page = serviceDiscovery.getInstances("A", offset, requestSize); - assertEquals(3, page.getRequestOffset()); - assertEquals(2, page.getRequestSize()); - assertEquals(3, page.getTotalSize()); - assertEquals(0, page.getData().size()); - assertFalse(page.hasData()); - - offset = 5; - page = serviceDiscovery.getInstances("A", offset, requestSize); - assertEquals(5, page.getRequestOffset()); - assertEquals(2, page.getRequestSize()); - assertEquals(3, page.getTotalSize()); - assertEquals(0, page.getData().size()); - assertFalse(page.hasData()); - } - - @Test - public void testGetInstancesWithHealthy() { - - List instances = new LinkedList<>(asList( - new DefaultServiceInstance("A", "127.0.0.1", 8080), - new DefaultServiceInstance("A", "127.0.0.1", 8081) - )); - - - DefaultServiceInstance serviceInstance = new DefaultServiceInstance("A", "127.0.0.1", 8082); - serviceInstance.setHealthy(false); - instances.add(serviceInstance); - - instances.forEach(instance::addServiceInstance); - - // offset starts 0 - int offset = 0; - // requestSize > total elements - int requestSize = 5; - - Page page = serviceDiscovery.getInstances("A", offset, requestSize, true); - assertEquals(0, page.getRequestOffset()); - assertEquals(5, page.getRequestSize()); - assertEquals(3, page.getTotalSize()); - assertEquals(2, page.getData().size()); - assertTrue(page.hasData()); - - for (ServiceInstance instance : page.getData()) { - assertTrue(instances.contains(instance)); - } - - // requestSize < total elements - requestSize = 2; - - offset = 1; - page = serviceDiscovery.getInstances("A", offset, requestSize, true); - assertEquals(1, page.getRequestOffset()); - assertEquals(2, page.getRequestSize()); - assertEquals(3, page.getTotalSize()); - assertEquals(1, page.getData().size()); - assertTrue(page.hasData()); - - for (ServiceInstance instance : page.getData()) { - assertTrue(instances.contains(instance)); - } - - offset = 2; - page = serviceDiscovery.getInstances("A", offset, requestSize, true); - assertEquals(2, page.getRequestOffset()); - assertEquals(2, page.getRequestSize()); - assertEquals(3, page.getTotalSize()); - assertEquals(0, page.getData().size()); - assertFalse(page.hasData()); - - offset = 3; - page = serviceDiscovery.getInstances("A", offset, requestSize, true); - assertEquals(3, page.getRequestOffset()); - assertEquals(2, page.getRequestSize()); - assertEquals(3, page.getTotalSize()); - assertEquals(0, page.getData().size()); - assertFalse(page.hasData()); - - offset = 5; - page = serviceDiscovery.getInstances("A", offset, requestSize, true); - assertEquals(5, page.getRequestOffset()); - assertEquals(2, page.getRequestSize()); - assertEquals(3, page.getTotalSize()); - assertEquals(0, page.getData().size()); - assertFalse(page.hasData()); - } -} \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/DefaultServiceInstanceTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/DefaultServiceInstanceTest.java index fb31571aed2..71cc0af447d 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/DefaultServiceInstanceTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/DefaultServiceInstanceTest.java @@ -26,7 +26,7 @@ /** * {@link DefaultServiceInstance} Test * - * @since 2.7.2 + * @since 2.7.3 */ public class DefaultServiceInstanceTest { diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/EventPublishingServiceDiscoveryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/EventPublishingServiceDiscoveryTest.java new file mode 100644 index 00000000000..18a8d6188f3 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/EventPublishingServiceDiscoveryTest.java @@ -0,0 +1,164 @@ +/* + * 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.client; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.event.EventDispatcher; +import org.apache.dubbo.event.EventListener; +import org.apache.dubbo.registry.client.event.ServiceDiscoveryStartedEvent; +import org.apache.dubbo.registry.client.event.ServiceDiscoveryStartingEvent; +import org.apache.dubbo.registry.client.event.ServiceDiscoveryStoppedEvent; +import org.apache.dubbo.registry.client.event.ServiceDiscoveryStoppingEvent; +import org.apache.dubbo.registry.client.event.ServiceInstancePreRegisteredEvent; +import org.apache.dubbo.registry.client.event.ServiceInstanceRegisteredEvent; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@link EventPublishingServiceDiscovery} Test + * + * @since 2.7.3 + */ +public class EventPublishingServiceDiscoveryTest { + + private static final URL url = URL.valueOf("zookeeper://127.0.0.1:2181/"); + + private EventDispatcher eventDispatcher = EventDispatcher.getDefaultExtension(); + + private InMemoryServiceDiscovery delegate; + + private EventPublishingServiceDiscovery serviceDiscovery; + + private ServiceDiscoveryTest serviceDiscoveryTest; + + @BeforeEach + public void init() { + + // remove all EventListeners + eventDispatcher.removeAllEventListeners(); + + delegate = new InMemoryServiceDiscovery(); + + serviceDiscovery = new EventPublishingServiceDiscovery(delegate); + + serviceDiscoveryTest = new ServiceDiscoveryTest(); + + serviceDiscoveryTest.setServiceDiscovery(serviceDiscovery); + + // ServiceDiscoveryStartingEvent + eventDispatcher.addEventListener(new EventListener() { + @Override + public void onEvent(ServiceDiscoveryStartingEvent event) { + assertEquals(delegate, event.getServiceDiscovery()); + } + }); + + // ServiceDiscoveryStartedEvent + eventDispatcher.addEventListener(new EventListener() { + @Override + public void onEvent(ServiceDiscoveryStartedEvent event) { + assertEquals(delegate, event.getServiceDiscovery()); + } + }); + + // ServiceInstancePreRegisteredEvent + eventDispatcher.addEventListener(new EventListener() { + @Override + public void onEvent(ServiceInstancePreRegisteredEvent event) { + assertNotNull(event.getServiceInstance()); + } + }); + + // ServiceInstanceRegisteredEvent + eventDispatcher.addEventListener(new EventListener() { + @Override + public void onEvent(ServiceInstanceRegisteredEvent event) { + assertNotNull(event.getServiceInstance()); + } + }); + + assertFalse(serviceDiscovery.isStarted()); + assertFalse(serviceDiscovery.isStopped()); + + // test start() + serviceDiscoveryTest.init(); + + assertTrue(serviceDiscovery.isStarted()); + assertFalse(serviceDiscovery.isStopped()); + } + + @AfterEach + public void destroy() { + + // ServiceDiscoveryStoppingEvent + eventDispatcher.addEventListener(new EventListener() { + @Override + public void onEvent(ServiceDiscoveryStoppingEvent event) { + assertEquals(delegate, event.getServiceDiscovery()); + } + }); + + // ServiceDiscoveryStoppedEvent + eventDispatcher.addEventListener(new EventListener() { + @Override + public void onEvent(ServiceDiscoveryStoppedEvent event) { + assertEquals(delegate, event.getServiceDiscovery()); + } + }); + + assertTrue(serviceDiscovery.isStarted()); + assertFalse(serviceDiscovery.isStopped()); + + // test stop() + serviceDiscoveryTest.destroy(); + + assertTrue(serviceDiscovery.isStarted()); + assertTrue(serviceDiscovery.isStopped()); + } + + @Test + public void testToString() { + serviceDiscoveryTest.testToString(); + } + + @Test + public void testRegisterAndUpdateAndUnregister() { + serviceDiscoveryTest.testRegisterAndUpdateAndUnregister(); + } + + @Test + public void testGetServices() { + serviceDiscoveryTest.testGetServices(); + } + + @Test + public void testGetInstances() { + serviceDiscoveryTest.testGetInstances(); + } + + @Test + public void testGetInstancesWithHealthy() { + serviceDiscoveryTest.testGetInstancesWithHealthy(); + } +} \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/EventPublishingServiceRegistryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/EventPublishingServiceRegistryTest.java deleted file mode 100644 index 4a3f61f0b53..00000000000 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/EventPublishingServiceRegistryTest.java +++ /dev/null @@ -1,77 +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.client; - -import org.junit.jupiter.api.Test; - -import static org.apache.dubbo.registry.client.DefaultServiceInstanceTest.INSTANCE; -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * {@link EventPublishingServiceRegistry} Test - * - * @since 2.7.2 - */ -public class EventPublishingServiceRegistryTest { - - private static ServiceRegistry serviceRegistry = new DefaultServiceRegistry(); - - private ServiceInstance serviceInstance = INSTANCE; - - @Test - public void testRegister() { - serviceRegistry.register(serviceInstance); - } - - @Test - public void testUpdate() { - serviceRegistry.update(serviceInstance); - } - - @Test - public void testUnregister() { - serviceRegistry.unregister(serviceInstance); - } -} - -class DefaultServiceRegistry extends EventPublishingServiceRegistry { - - @Override - protected void doRegister(ServiceInstance serviceInstance) throws RuntimeException { - assertEquals(INSTANCE, serviceInstance); - } - - @Override - protected void doUpdate(ServiceInstance serviceInstance) throws RuntimeException { - assertEquals(INSTANCE, serviceInstance); - } - - @Override - protected void doUnregister(ServiceInstance serviceInstance) throws RuntimeException { - assertEquals(INSTANCE, serviceInstance); - } - - @Override - protected void doStart() { - - } - - @Override - protected void doStop() { - - } -} diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InMemoryServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InMemoryServiceDiscovery.java index 4311d8259fd..051b75fcd67 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InMemoryServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InMemoryServiceDiscovery.java @@ -17,7 +17,7 @@ package org.apache.dubbo.registry.client; import org.apache.dubbo.event.EventDispatcher; -import org.apache.dubbo.registry.client.event.ServiceDiscoveryChangeListener; +import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; import java.util.HashMap; import java.util.LinkedList; @@ -25,16 +25,14 @@ import java.util.Map; import java.util.Set; -import static org.apache.dubbo.event.EventDispatcher.getDefaultExtension; - /** * In-Memory {@link ServiceDiscovery} implementation * - * @since 2.7.2 + * @since 2.7.3 */ public class InMemoryServiceDiscovery implements ServiceDiscovery { - private final EventDispatcher dispatcher = getDefaultExtension(); + private final EventDispatcher dispatcher = EventDispatcher.getDefaultExtension(); private Map> repository = new HashMap<>(); @@ -48,22 +46,43 @@ public List getInstances(String serviceName) throws NullPointer return repository.computeIfAbsent(serviceName, s -> new LinkedList<>()); } - public InMemoryServiceDiscovery addServiceInstance(ServiceInstance serviceInstance) { + public String toString() { + return "InMemoryServiceDiscovery"; + } + + @Override + public void register(ServiceInstance serviceInstance) throws RuntimeException { String serviceName = serviceInstance.getServiceName(); List serviceInstances = repository.computeIfAbsent(serviceName, s -> new LinkedList<>()); if (!serviceInstances.contains(serviceInstance)) { serviceInstances.add(serviceInstance); } - return this; } - public String toString() { - return "InMemoryServiceDiscovery"; + @Override + public void update(ServiceInstance serviceInstance) throws RuntimeException { + unregister(serviceInstance); + register(serviceInstance); } @Override - public void addServiceDiscoveryChangeListener(String serviceName, ServiceDiscoveryChangeListener listener) throws NullPointerException, IllegalArgumentException { - dispatcher.addEventListener(listener); + public void unregister(ServiceInstance serviceInstance) throws RuntimeException { + String serviceName = serviceInstance.getServiceName(); + List serviceInstances = repository.computeIfAbsent(serviceName, s -> new LinkedList<>()); + serviceInstances.remove(serviceInstance); + } + + @Override + public void start() { + } + @Override + public void stop() { + } + + @Override + public void addServiceInstancesChangedListener(String serviceName, ServiceInstancesChangedListener listener) throws NullPointerException, IllegalArgumentException { + dispatcher.addEventListener(listener); + } } diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InMemoryServiceDiscoveryFactory.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InMemoryServiceDiscoveryFactory.java new file mode 100644 index 00000000000..afab3e6b646 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InMemoryServiceDiscoveryFactory.java @@ -0,0 +1,38 @@ +/* + * 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.client; + +import org.apache.dubbo.common.URL; + +/** + * {@link InMemoryServiceDiscovery} Factory + * + * @see InMemoryServiceDiscovery + * @since 2.7.3 + */ +public class InMemoryServiceDiscoveryFactory implements ServiceDiscoveryFactory { + + @Override + public boolean supports(URL connectionURL) { + return "in-memory".equalsIgnoreCase(connectionURL.getProtocol()); + } + + @Override + public ServiceDiscovery create(URL connectionURL) { + return new InMemoryServiceDiscovery(); + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryFactoryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryFactoryTest.java new file mode 100644 index 00000000000..3030bcb0214 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryFactoryTest.java @@ -0,0 +1,68 @@ +/* + * 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.client; + +import org.apache.dubbo.common.URL; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.apache.dubbo.common.URL.valueOf; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@link ServiceDiscoveryFactory} Test + * + * @since 2.7.3 + */ +public class ServiceDiscoveryFactoryTest { + + private static final URL dubboURL = valueOf("dubbo://localhost:20880"); + + private static final URL inMemoryURL = valueOf("in-memory://localhost:12345"); + + private ServiceDiscoveryFactory serviceDiscoveryFactory; + + @BeforeEach + public void init() { + serviceDiscoveryFactory = ServiceDiscoveryFactory.getDefaultExtension(); + } + + @Test + public void testClass() { + assertEquals(DefaultServiceDiscoveryFactory.class, serviceDiscoveryFactory.getClass()); + } + + @Test + public void testSupports() { + assertFalse(serviceDiscoveryFactory.supports(dubboURL)); + assertTrue(serviceDiscoveryFactory.supports(inMemoryURL)); + } + + @Test + public void testCreate() { + ServiceDiscovery serviceDiscovery = serviceDiscoveryFactory.create(inMemoryURL); + assertEquals(EventPublishingServiceDiscovery.class, serviceDiscovery.getClass()); + } + + @Test + public void testPriority() { + assertEquals(Integer.MAX_VALUE, serviceDiscoveryFactory.getPriority()); + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryTest.java index 30bdd9c9bb3..a716d802cc6 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryTest.java @@ -17,12 +17,8 @@ package org.apache.dubbo.registry.client; import org.apache.dubbo.common.utils.Page; -import org.apache.dubbo.event.EventDispatcher; -import org.apache.dubbo.event.EventListener; -import org.apache.dubbo.registry.client.event.ServiceInstanceEvent; -import org.apache.dubbo.registry.client.event.ServiceInstancePreRegisteredEvent; -import org.apache.dubbo.registry.client.event.ServiceInstanceRegisteredEvent; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -30,10 +26,7 @@ import java.util.LinkedList; import java.util.List; -import static java.lang.Integer.MAX_VALUE; import static java.util.Arrays.asList; -import static org.apache.dubbo.registry.client.DefaultServiceInstanceTest.INSTANCE; -import static org.apache.dubbo.registry.client.ServiceDiscoveryTest.handleEvent; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -41,38 +34,70 @@ /** * {@link ServiceDiscovery} Test case * - * @since 2.7.2 + * @since 2.7.3 */ public class ServiceDiscoveryTest { - private static InMemoryServiceDiscovery instance; - - private EventDispatcher dispatcher = EventDispatcher.getDefaultExtension(); + private ServiceDiscovery serviceDiscovery; @BeforeEach public void init() { - instance = new InMemoryServiceDiscovery(); - dispatcher.addEventListener(new BeforeEventListener()); - dispatcher.addEventListener(new AfterEventListener()); - dispatcher.removeAllEventListeners(); + if (serviceDiscovery == null) { + setServiceDiscovery(new InMemoryServiceDiscovery()); + } + // test start() + serviceDiscovery.start(); + } + + @AfterEach + public void destroy() { + // test stop() + serviceDiscovery.stop(); } @Test public void testToString() { - assertEquals("InMemoryServiceDiscovery", instance.toString()); + assertEquals("InMemoryServiceDiscovery", serviceDiscovery.toString()); } @Test - public void testGetPriority() { - assertEquals(MAX_VALUE, instance.getPriority()); + public void testRegisterAndUpdateAndUnregister() { + + // register + DefaultServiceInstance serviceInstance = new DefaultServiceInstance("A", "127.0.0.1", 8080); + serviceDiscovery.register(serviceInstance); + + List serviceInstances = serviceDiscovery.getInstances("A"); + + assertEquals(1, serviceInstances.size()); + assertEquals(serviceInstances.get(0), serviceInstance); + + serviceInstance.setEnabled(false); + serviceInstance.setHealthy(false); + serviceInstance.setPort(9090); + + // update + serviceDiscovery.update(serviceInstance); + + serviceInstances = serviceDiscovery.getInstances("A"); + + assertEquals(1, serviceInstances.size()); + assertEquals(serviceInstances.get(0), serviceInstance); + + // unregister + serviceDiscovery.unregister(serviceInstance); + + serviceInstances = serviceDiscovery.getInstances("A"); + assertTrue(serviceInstances.isEmpty()); } + @Test public void testGetServices() { - instance.addServiceInstance(new DefaultServiceInstance("A", "127.0.0.1", 8080)); - instance.addServiceInstance(new DefaultServiceInstance("B", "127.0.0.1", 8080)); - instance.addServiceInstance(new DefaultServiceInstance("C", "127.0.0.1", 8080)); - assertEquals(new HashSet<>(asList("A", "B", "C")), instance.getServices()); + serviceDiscovery.register(new DefaultServiceInstance("A", "127.0.0.1", 8080)); + serviceDiscovery.register(new DefaultServiceInstance("B", "127.0.0.1", 8080)); + serviceDiscovery.register(new DefaultServiceInstance("C", "127.0.0.1", 8080)); + assertEquals(new HashSet<>(asList("A", "B", "C")), serviceDiscovery.getServices()); } @Test @@ -84,19 +109,19 @@ public void testGetInstances() { new DefaultServiceInstance("A", "127.0.0.1", 8082) ); - instances.forEach(instance::addServiceInstance); + instances.forEach(serviceDiscovery::register); // Duplicated - instance.addServiceInstance(new DefaultServiceInstance("A", "127.0.0.1", 8080)); + serviceDiscovery.register(new DefaultServiceInstance("A", "127.0.0.1", 8080)); // Duplicated - instance.addServiceInstance(new DefaultServiceInstance("A", "127.0.0.1", 8081)); + serviceDiscovery.register(new DefaultServiceInstance("A", "127.0.0.1", 8081)); // offset starts 0 int offset = 0; // requestSize > total elements int requestSize = 5; - Page page = instance.getInstances("A", offset, requestSize); + Page page = serviceDiscovery.getInstances("A", offset, requestSize); assertEquals(0, page.getRequestOffset()); assertEquals(5, page.getRequestSize()); assertEquals(3, page.getTotalSize()); @@ -110,7 +135,7 @@ public void testGetInstances() { // requestSize < total elements requestSize = 2; - page = instance.getInstances("A", offset, requestSize); + page = serviceDiscovery.getInstances("A", offset, requestSize); assertEquals(0, page.getRequestOffset()); assertEquals(2, page.getRequestSize()); assertEquals(3, page.getTotalSize()); @@ -122,7 +147,7 @@ public void testGetInstances() { } offset = 1; - page = instance.getInstances("A", offset, requestSize); + page = serviceDiscovery.getInstances("A", offset, requestSize); assertEquals(1, page.getRequestOffset()); assertEquals(2, page.getRequestSize()); assertEquals(3, page.getTotalSize()); @@ -134,7 +159,7 @@ public void testGetInstances() { } offset = 2; - page = instance.getInstances("A", offset, requestSize); + page = serviceDiscovery.getInstances("A", offset, requestSize); assertEquals(2, page.getRequestOffset()); assertEquals(2, page.getRequestSize()); assertEquals(3, page.getTotalSize()); @@ -142,7 +167,7 @@ public void testGetInstances() { assertTrue(page.hasData()); offset = 3; - page = instance.getInstances("A", offset, requestSize); + page = serviceDiscovery.getInstances("A", offset, requestSize); assertEquals(3, page.getRequestOffset()); assertEquals(2, page.getRequestSize()); assertEquals(3, page.getTotalSize()); @@ -150,7 +175,7 @@ public void testGetInstances() { assertFalse(page.hasData()); offset = 5; - page = instance.getInstances("A", offset, requestSize); + page = serviceDiscovery.getInstances("A", offset, requestSize); assertEquals(5, page.getRequestOffset()); assertEquals(2, page.getRequestSize()); assertEquals(3, page.getTotalSize()); @@ -171,14 +196,14 @@ public void testGetInstancesWithHealthy() { serviceInstance.setHealthy(false); instances.add(serviceInstance); - instances.forEach(instance::addServiceInstance); + instances.forEach(serviceDiscovery::register); // offset starts 0 int offset = 0; // requestSize > total elements int requestSize = 5; - Page page = instance.getInstances("A", offset, requestSize, true); + Page page = serviceDiscovery.getInstances("A", offset, requestSize, true); assertEquals(0, page.getRequestOffset()); assertEquals(5, page.getRequestSize()); assertEquals(3, page.getTotalSize()); @@ -193,7 +218,7 @@ public void testGetInstancesWithHealthy() { requestSize = 2; offset = 1; - page = instance.getInstances("A", offset, requestSize, true); + page = serviceDiscovery.getInstances("A", offset, requestSize, true); assertEquals(1, page.getRequestOffset()); assertEquals(2, page.getRequestSize()); assertEquals(3, page.getTotalSize()); @@ -205,7 +230,7 @@ public void testGetInstancesWithHealthy() { } offset = 2; - page = instance.getInstances("A", offset, requestSize, true); + page = serviceDiscovery.getInstances("A", offset, requestSize, true); assertEquals(2, page.getRequestOffset()); assertEquals(2, page.getRequestSize()); assertEquals(3, page.getTotalSize()); @@ -213,7 +238,7 @@ public void testGetInstancesWithHealthy() { assertFalse(page.hasData()); offset = 3; - page = instance.getInstances("A", offset, requestSize, true); + page = serviceDiscovery.getInstances("A", offset, requestSize, true); assertEquals(3, page.getRequestOffset()); assertEquals(2, page.getRequestSize()); assertEquals(3, page.getTotalSize()); @@ -221,7 +246,7 @@ public void testGetInstancesWithHealthy() { assertFalse(page.hasData()); offset = 5; - page = instance.getInstances("A", offset, requestSize, true); + page = serviceDiscovery.getInstances("A", offset, requestSize, true); assertEquals(5, page.getRequestOffset()); assertEquals(2, page.getRequestSize()); assertEquals(3, page.getTotalSize()); @@ -229,25 +254,11 @@ public void testGetInstancesWithHealthy() { assertFalse(page.hasData()); } - - static void handleEvent(ServiceInstanceEvent event) { - assertEquals(INSTANCE, event.getServiceInstance()); - assertEquals(instance, event.getSource()); + public void setServiceDiscovery(ServiceDiscovery serviceDiscovery) { + this.serviceDiscovery = serviceDiscovery; } -} - -class BeforeEventListener implements EventListener { - - @Override - public void onEvent(ServiceInstancePreRegisteredEvent event) { - handleEvent(event); - } -} - -class AfterEventListener implements EventListener { - @Override - public void onEvent(ServiceInstanceRegisteredEvent event) { - handleEvent(event); + public ServiceDiscovery getServiceDiscovery() { + return serviceDiscovery; } -} +} \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtilsTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtilsTest.java new file mode 100644 index 00000000000..d581adf8718 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtilsTest.java @@ -0,0 +1,78 @@ +/* + * 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.client.metadata; + +import org.apache.dubbo.common.URL; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getProtocolPorts; +import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.protocolPortMetadataKey; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * {@link ServiceInstanceMetadataUtils} Test + * + * @since 2.7.3 + */ +public class ServiceInstanceMetadataUtilsTest { + + private static URL url = URL.valueOf("dubbo://192.168.0.102:20880/org.apache.dubbo.metadata.MetadataService?&anyhost=true&application=spring-cloud-alibaba-dubbo-provider&bind.ip=192.168.0.102&bind.port=20880&default.deprecated=false&default.dynamic=false&default.register=true&deprecated=false&dubbo=2.0.2&dynamic=false&generic=false&group=spring-cloud-alibaba-dubbo-provider&interface=org.apache.dubbo.metadata.MetadataService&methods=getAllServiceKeys,getServiceRestMetadata,getExportedURLs,getAllExportedURLs&pid=58350®ister=true&release=2.7.1&revision=1.0.0&side=provider×tamp=1557928573174&version=1.0.0"); + private static URL url2 = URL.valueOf("rest://192.168.0.102:20880/org.apache.dubbo.metadata.MetadataService?&anyhost=true&application=spring-cloud-alibaba-dubbo-provider&bind.ip=192.168.0.102&bind.port=20880&default.deprecated=false&default.dynamic=false&default.register=true&deprecated=false&dubbo=2.0.2&dynamic=false&generic=false&group=spring-cloud-alibaba-dubbo-provider&interface=org.apache.dubbo.metadata.MetadataService&methods=getAllServiceKeys,getServiceRestMetadata,getExportedURLs,getAllExportedURLs&pid=58350®ister=true&release=2.7.1&revision=1.0.0&side=provider×tamp=1557928573174&version=1.0.0"); + + private static final String VALUE = "{\"rest\":{\"application\":\"spring-cloud-alibaba-dubbo-provider\",\"bind.ip\":\"192.168.0.102\",\"bind.port\":\"20880\",\"dubbo\":\"2.0.2\",\"release\":\"2.7.1\",\"side\":\"provider\",\"version\":\"1.0.0\"},\"dubbo\":{\"application\":\"spring-cloud-alibaba-dubbo-provider\",\"bind.ip\":\"192.168.0.102\",\"bind.port\":\"20880\",\"dubbo\":\"2.0.2\",\"release\":\"2.7.1\",\"side\":\"provider\",\"version\":\"1.0.0\"}}"; + + @Test + public void testMetadataServiceURLParameters() { + + List urls = Arrays.asList(url, url2); + + String parameter = ServiceInstanceMetadataUtils.getMetadataServiceParameter(urls); + + assertEquals(VALUE, parameter); + } + + @Test + public void testProtocolPorts() { + + Map metadata = new LinkedHashMap<>(); + + String key = protocolPortMetadataKey("dubbo"); + assertEquals("dubbo.protocols.dubbo.port", key); + + metadata.put(key, "20880"); + + key = protocolPortMetadataKey("rest"); + assertEquals("dubbo.protocols.rest.port", key); + + metadata.put(key, "8080"); + + Map protocolPorts = getProtocolPorts(metadata); + + Map expected = new LinkedHashMap<>(); + + expected.put("dubbo", 20880); + expected.put("rest", 8080); + + assertEquals(expected, protocolPorts); + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/ServiceOrientedRegistryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/ServiceOrientedRegistryTest.java new file mode 100644 index 00000000000..21214d172b9 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/ServiceOrientedRegistryTest.java @@ -0,0 +1,173 @@ +/* + * 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.support; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.metadata.LocalMetadataService; +import org.apache.dubbo.registry.NotifyListener; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.LinkedList; +import java.util.List; + +import static java.util.Collections.emptyList; +import static org.apache.dubbo.common.URL.valueOf; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_PROTOCOL; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; +import static org.apache.dubbo.registry.Registry.TYPE_PARAM_NAME; +import static org.apache.dubbo.registry.support.ServiceOrientedRegistry.SUBSCRIBED_SERVICE_NAMES_PARAM_NAME; +import static org.apache.dubbo.registry.support.ServiceOrientedRegistry.TYPE_PARAM_VALUE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@link ServiceOrientedRegistry} Test + * + * @since 2.7.3 + */ +public class ServiceOrientedRegistryTest { + + private static final URL registryURL = valueOf("in-memory://localhost:12345") + .addParameter(TYPE_PARAM_NAME, TYPE_PARAM_VALUE) + .addParameter(SUBSCRIBED_SERVICE_NAMES_PARAM_NAME, "a, b , c,d,e ,"); + + private static final String SERVICE_INTERFACE = "org.apache.dubbo.metadata.MetadataService"; + + private static final String GROUP = "spring-cloud-alibaba-dubbo-provider"; + + private static final String VERSION = "1.0.0"; + + private static URL url = valueOf("dubbo://192.168.0.102:20880/" + SERVICE_INTERFACE + + "?&application=" + GROUP + + "&interface=" + SERVICE_INTERFACE + + "&group=" + GROUP + + "&version=" + VERSION + + "&methods=getAllServiceKeys,getServiceRestMetadata,getExportedURLs,getAllExportedURLs" + + "&side=" + PROVIDER_SIDE + ); + + private static URL url2 = url.setProtocol("rest"); + + private LocalMetadataService metadataService; + + private ServiceOrientedRegistry registry; + + private NotifyListener notifyListener; + + @BeforeEach + public void init() { + registry = ServiceOrientedRegistry.create(registryURL); + metadataService = LocalMetadataService.getDefaultExtension(); + notifyListener = new MyNotifyListener(); + } + + @Test + public void testSupports() { + assertTrue(ServiceOrientedRegistry.supports(registryURL)); + } + + @Test + public void testCreate() { + assertNotNull(registry); + } + + @Test + public void testRegister() { + + registry.register(url); + + List urls = metadataService.getExportedURLs(); + + assertEquals(emptyList(), urls); + assertEquals(metadataService.getExportedURLs(SERVICE_INTERFACE), urls); + assertEquals(metadataService.getExportedURLs(SERVICE_INTERFACE, GROUP), urls); + assertEquals(metadataService.getExportedURLs(SERVICE_INTERFACE, GROUP, VERSION), urls); + assertEquals(metadataService.getExportedURLs(SERVICE_INTERFACE, GROUP, VERSION, DEFAULT_PROTOCOL), urls); + + String serviceInterface = "com.acme.UserService"; + + URL newURL = url.setServiceInterface(serviceInterface).setPath(serviceInterface); + + registry.register(newURL); + + urls = metadataService.getExportedURLs(); + + assertEquals(metadataService.getExportedURLs(serviceInterface, GROUP, VERSION), urls); + assertEquals(metadataService.getExportedURLs(serviceInterface, GROUP, VERSION, DEFAULT_PROTOCOL), urls); + + } + + @Test + public void testUnregister() { + + String serviceInterface = "com.acme.UserService"; + + URL newURL = url.setServiceInterface(serviceInterface).setPath(serviceInterface); + + // register + registry.register(newURL); + + List urls = metadataService.getExportedURLs(); + + assertFalse(urls.isEmpty()); + assertEquals(metadataService.getExportedURLs(serviceInterface, GROUP, VERSION), urls); + assertEquals(metadataService.getExportedURLs(serviceInterface, GROUP, VERSION, DEFAULT_PROTOCOL), urls); + + // unregister + registry.unregister(newURL); + + urls = metadataService.getExportedURLs(); + + assertEquals(emptyList(), urls); + assertEquals(metadataService.getExportedURLs(SERVICE_INTERFACE), urls); + assertEquals(metadataService.getExportedURLs(SERVICE_INTERFACE, GROUP), urls); + assertEquals(metadataService.getExportedURLs(SERVICE_INTERFACE, GROUP, VERSION), urls); + assertEquals(metadataService.getExportedURLs(SERVICE_INTERFACE, GROUP, VERSION, DEFAULT_PROTOCOL), urls); + } + + @Test + public void testSubscribe() { + + registry.subscribe(url, new MyNotifyListener()); + + List urls = metadataService.getSubscribedURLs(); + + assertFalse(urls.isEmpty()); + assertEquals(url, urls.get(0)); + + } + + + private class MyNotifyListener implements NotifyListener { + + private List cache = new LinkedList<>(); + + @Override + public void notify(List urls) { + cache.addAll(urls); + } + + public List getURLs() { + return cache; + } + } + +} diff --git a/dubbo-registry/dubbo-registry-api/src/test/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceDiscoveryFactory b/dubbo-registry/dubbo-registry-api/src/test/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceDiscoveryFactory new file mode 100644 index 00000000000..5dc3c97161d --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/test/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceDiscoveryFactory @@ -0,0 +1 @@ +org.apache.dubbo.registry.client.InMemoryServiceDiscoveryFactory \ No newline at end of file From 1df1d1aa66a6ce5ccb948c9fae0d5b548e158d80 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Fri, 31 May 2019 14:10:39 +0800 Subject: [PATCH 24/46] Polish apache/incubator-dubbo#3984 : Add Service registration and discovery implementation for Zookeeper --- .../registry/zookeeper/ZookeeperInstance.java | 2 +- .../zookeeper/ZookeeperServiceDiscovery.java | 28 +++++------- ...ookeeperServiceDiscoveryChangeWatcher.java | 8 ++-- .../ZookeeperServiceDiscoveryFactory.java | 44 +++++++++++++++++++ .../util/CuratorFrameworkParams.java | 2 +- .../zookeeper/util/CuratorFrameworkUtils.java | 24 +++++----- ...bo.registry.client.ServiceDiscoveryFactory | 1 + .../ZookeeperServiceDiscoveryTest.java | 6 +-- 8 files changed, 77 insertions(+), 38 deletions(-) create mode 100644 dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryFactory.java create mode 100644 dubbo-registry/dubbo-registry-zookeeper/src/main/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceDiscoveryFactory diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperInstance.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperInstance.java index 71cca53a394..13e0f3b4401 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperInstance.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperInstance.java @@ -24,7 +24,7 @@ *

* It's compatible with Spring Cloud * - * @since 2.7.2 + * @since 2.7.3 */ public class ZookeeperInstance { diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscovery.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscovery.java index d9d6df0c35f..5039b0d48e6 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscovery.java @@ -22,10 +22,9 @@ import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.event.EventDispatcher; -import org.apache.dubbo.registry.client.EventPublishingServiceRegistry; import org.apache.dubbo.registry.client.ServiceDiscovery; import org.apache.dubbo.registry.client.ServiceInstance; -import org.apache.dubbo.registry.client.event.ServiceDiscoveryChangeListener; +import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.CuratorWatcher; @@ -47,7 +46,7 @@ * Zookeeper {@link ServiceDiscovery} implementation based on * Apache Curator X Discovery */ -public class ZookeeperServiceDiscovery extends EventPublishingServiceRegistry implements ServiceDiscovery { +public class ZookeeperServiceDiscovery implements ServiceDiscovery { private final Logger logger = LoggerFactory.getLogger(getClass()); @@ -64,43 +63,38 @@ public class ZookeeperServiceDiscovery extends EventPublishingServiceRegistry im */ private final Map watcherCaches = new ConcurrentHashMap<>(); - public ZookeeperServiceDiscovery(URL registerURL) throws Exception { - this.curatorFramework = buildCuratorFramework(registerURL); - this.rootPath = ROOT_PATH.getParameterValue(registerURL); + public ZookeeperServiceDiscovery(URL connectionURL) throws Exception { + this.curatorFramework = buildCuratorFramework(connectionURL); + this.rootPath = ROOT_PATH.getParameterValue(connectionURL); this.serviceDiscovery = buildServiceDiscovery(curatorFramework, rootPath); this.dispatcher = EventDispatcher.getDefaultExtension(); } - @Override - protected void doRegister(ServiceInstance serviceInstance) throws RuntimeException { + public void register(ServiceInstance serviceInstance) throws RuntimeException { doInServiceRegistry(serviceDiscovery -> { serviceDiscovery.registerService(build(serviceInstance)); }); } - @Override - protected void doUpdate(ServiceInstance serviceInstance) throws RuntimeException { + public void update(ServiceInstance serviceInstance) throws RuntimeException { doInServiceRegistry(serviceDiscovery -> { serviceDiscovery.updateService(build(serviceInstance)); }); } - @Override - protected void doUnregister(ServiceInstance serviceInstance) throws RuntimeException { + public void unregister(ServiceInstance serviceInstance) throws RuntimeException { doInServiceRegistry(serviceDiscovery -> { serviceDiscovery.unregisterService(build(serviceInstance)); }); } - @Override - protected void doStart() { + public void start() { doInServiceRegistry(serviceDiscovery -> { serviceDiscovery.start(); }); } - @Override - protected void doStop() { + public void stop() { doInServiceRegistry(serviceDiscovery -> { serviceDiscovery.close(); }); @@ -117,7 +111,7 @@ public List getInstances(String serviceName) throws NullPointer } @Override - public void addServiceDiscoveryChangeListener(String serviceName, ServiceDiscoveryChangeListener listener) + public void addServiceInstancesChangedListener(String serviceName, ServiceInstancesChangedListener listener) throws NullPointerException, IllegalArgumentException { addServiceWatcherIfAbsent(serviceName); dispatcher.addEventListener(listener); diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryChangeWatcher.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryChangeWatcher.java index 8e055b65b6d..5cab2d9a6e6 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryChangeWatcher.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryChangeWatcher.java @@ -19,7 +19,7 @@ import org.apache.dubbo.event.EventDispatcher; import org.apache.dubbo.registry.client.ServiceDiscovery; import org.apache.dubbo.registry.client.ServiceInstance; -import org.apache.dubbo.registry.client.event.ServiceDiscoveryChangeEvent; +import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.zookeeper.WatchedEvent; @@ -33,9 +33,9 @@ /** * Zookeeper {@link ServiceDiscovery} Change {@link CuratorWatcher watcher} only interests in * {@link Watcher.Event.EventType#NodeChildrenChanged} and {@link Watcher.Event.EventType#NodeDataChanged} event types, - * which will multicast a {@link ServiceDiscoveryChangeEvent} when the service node has been changed. + * which will multicast a {@link ServiceInstancesChangedEvent} when the service node has been changed. * - * @since 2.7.2 + * @since 2.7.3 */ public class ZookeeperServiceDiscoveryChangeWatcher implements CuratorWatcher { @@ -58,7 +58,7 @@ public void process(WatchedEvent event) throws Exception { Watcher.Event.EventType eventType = event.getType(); if (NodeChildrenChanged.equals(eventType) || NodeDataChanged.equals(eventType)) { - dispatcher.dispatch(new ServiceDiscoveryChangeEvent(serviceName, getServiceInstances(serviceName))); + dispatcher.dispatch(new ServiceInstancesChangedEvent(serviceName, getServiceInstances(serviceName))); } } diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryFactory.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryFactory.java new file mode 100644 index 00000000000..6cca1aa87bf --- /dev/null +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryFactory.java @@ -0,0 +1,44 @@ +/* + * 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.zookeeper; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.registry.client.ServiceDiscovery; +import org.apache.dubbo.registry.client.ServiceDiscoveryFactory; + +/** + * The zookeeper {@link ServiceDiscoveryFactory} implementation + * + * @see ServiceDiscoveryFactory + * @since 2.7.3 + */ +public class ZookeeperServiceDiscoveryFactory implements ServiceDiscoveryFactory { + + @Override + public boolean supports(URL connectionURL) { + return "zookeeper".equalsIgnoreCase(connectionURL.getProtocol()); + } + + @Override + public ServiceDiscovery create(URL connectionURL) { + try { + return new ZookeeperServiceDiscovery(connectionURL); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkParams.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkParams.java index 7e9db4c54e6..1156b1a4d84 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkParams.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkParams.java @@ -28,7 +28,7 @@ * The enumeration for the parameters of {@link CuratorFramework} * * @see CuratorFramework - * @since 2.7.2 + * @since 2.7.3 */ public enum CuratorFrameworkParams { diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtils.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtils.java index bc466b8dcdd..b45830f5bfe 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtils.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtils.java @@ -45,12 +45,12 @@ /** * Curator Framework Utilities Class * - * @since 2.7.2 + * @since 2.7.3 */ public abstract class CuratorFrameworkUtils { - public static ZookeeperServiceDiscovery buildZookeeperServiceDiscovery(URL registerURL) throws Exception { - return new ZookeeperServiceDiscovery(registerURL); + public static ZookeeperServiceDiscovery buildZookeeperServiceDiscovery(URL connectionURL) throws Exception { + return new ZookeeperServiceDiscovery(connectionURL); } public static ServiceDiscovery buildServiceDiscovery(CuratorFramework curatorFramework, @@ -61,21 +61,21 @@ public static ServiceDiscovery buildServiceDiscovery(CuratorF .build(); } - public static CuratorFramework buildCuratorFramework(URL registerURL) throws Exception { + public static CuratorFramework buildCuratorFramework(URL connectionURL) throws Exception { CuratorFramework curatorFramework = CuratorFrameworkFactory.builder() - .connectString(registerURL.getIp() + ":" + registerURL.getPort()) - .retryPolicy(buildRetryPolicy(registerURL)) + .connectString(connectionURL.getIp() + ":" + connectionURL.getPort()) + .retryPolicy(buildRetryPolicy(connectionURL)) .build(); curatorFramework.start(); - curatorFramework.blockUntilConnected(BLOCK_UNTIL_CONNECTED_WAIT.getParameterValue(registerURL), - BLOCK_UNTIL_CONNECTED_UNIT.getParameterValue(registerURL)); + curatorFramework.blockUntilConnected(BLOCK_UNTIL_CONNECTED_WAIT.getParameterValue(connectionURL), + BLOCK_UNTIL_CONNECTED_UNIT.getParameterValue(connectionURL)); return curatorFramework; } - public static RetryPolicy buildRetryPolicy(URL registerURL) { - int baseSleepTimeMs = BASE_SLEEP_TIME.getParameterValue(registerURL); - int maxRetries = MAX_RETRIES.getParameterValue(registerURL); - int getMaxSleepMs = MAX_SLEEP.getParameterValue(registerURL); + public static RetryPolicy buildRetryPolicy(URL connectionURL) { + int baseSleepTimeMs = BASE_SLEEP_TIME.getParameterValue(connectionURL); + int maxRetries = MAX_RETRIES.getParameterValue(connectionURL); + int getMaxSleepMs = MAX_SLEEP.getParameterValue(connectionURL); return new ExponentialBackoffRetry(baseSleepTimeMs, maxRetries, getMaxSleepMs); } diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceDiscoveryFactory b/dubbo-registry/dubbo-registry-zookeeper/src/main/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceDiscoveryFactory new file mode 100644 index 00000000000..9e2e9ec9c91 --- /dev/null +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceDiscoveryFactory @@ -0,0 +1 @@ +org.apache.dubbo.registry.zookeeper.ZookeeperServiceDiscoveryFactory \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryTest.java b/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryTest.java index e74425f9f2a..2e59f551cf5 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryTest.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryTest.java @@ -44,7 +44,7 @@ /** * {@link ZookeeperServiceDiscovery} Test * - * @since 2.7.2 + * @since 2.7.3 */ public class ZookeeperServiceDiscoveryTest { @@ -66,7 +66,7 @@ public void init() throws Exception { this.registryUrl = URL.valueOf("zookeeper://127.0.0.1:" + zkServerPort); this.discovery = buildZookeeperServiceDiscovery(registryUrl); - this.discovery.start(); + this.discovery.start(registryUrl); } @AfterEach @@ -124,7 +124,7 @@ public void testGetInstances() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); // Add Listener - discovery.addServiceDiscoveryChangeListener(SERVICE_NAME, event -> { + discovery.addServiceInstancesChangedListener(SERVICE_NAME, event -> { serviceInstances.addAll(event.getServiceInstances()); latch.countDown(); }); From 71a902de26b49ca906821efb981cdfb6a320cd47 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Fri, 31 May 2019 15:17:45 +0800 Subject: [PATCH 25/46] Add Bootstrap --- dubbo-bootstrap/pom.xml | 29 +++++++ .../dubbo/bootstrap/DubboBootstrap.java | 81 +++++++++++++++++++ 2 files changed, 110 insertions(+) create mode 100644 dubbo-bootstrap/pom.xml create mode 100644 dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java diff --git a/dubbo-bootstrap/pom.xml b/dubbo-bootstrap/pom.xml new file mode 100644 index 00000000000..f30963b8e4b --- /dev/null +++ b/dubbo-bootstrap/pom.xml @@ -0,0 +1,29 @@ + + + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + + 4.0.0 + + dubbo-bootstrap + jar + + dubbo-bootstrap + The bootstrap module of Dubbo project + + + + + org.apache.dubbo + dubbo-config-api + ${project.parent.version} + + + + + \ No newline at end of file diff --git a/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java new file mode 100644 index 00000000000..8b3dac232ff --- /dev/null +++ b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java @@ -0,0 +1,81 @@ +/* + * 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.bootstrap; + +import org.apache.dubbo.config.ApplicationConfig; +import org.apache.dubbo.config.ReferenceConfig; +import org.apache.dubbo.config.ServiceConfig; +import org.apache.dubbo.metadata.MetadataServiceExporter; +import org.apache.dubbo.registry.client.ServiceDiscovery; +import org.apache.dubbo.registry.client.ServiceInstance; + +import java.util.LinkedList; +import java.util.List; + +import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; + +/** + * The bootstrap class of Dubbo + * + * @since 2.7.3 + */ +public class DubboBootstrap { + + private final List> serviceConfigs = new LinkedList<>(); + + private final List> referenceConfigs = new LinkedList<>(); + + private final MetadataServiceExporter metadataServiceExporter = + getExtensionLoader(MetadataServiceExporter.class).getExtension("default"); + + private ServiceInstance serviceInstance; + + private ApplicationConfig applicationConfig; + + private String serviceDiscoveryType; + + private ServiceDiscovery serviceDiscovery; + + + public DubboBootstrap applicationConfig(ApplicationConfig applicationConfig) { + this.applicationConfig = applicationConfig; + return this; + } + + public DubboBootstrap serviceDiscoveryType(String serviceDiscoveryType) { + this.serviceDiscoveryType = serviceDiscoveryType; + return this; + } + + public void start() { + + + registerSelfInstance(); + + + metadataServiceExporter.export(); + } + + private void registerSelfInstance() { +// serviceInstance = new + } + + + public void stop() { + + } +} From 9208a3424ab8910af4b66d8da5554e8b702263b4 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Tue, 4 Jun 2019 02:11:49 +0800 Subject: [PATCH 26/46] Polish GA --- .../java/org/apache/dubbo/common/URL.java | 50 ++-- .../common/constants/RegistryConstants.java | 22 ++ dubbo-config/dubbo-config-api/pom.xml | 38 +++ ...ubboProtocolsConfigMetadataCustomizer.java | 100 ++++---- ....registry.client.ServiceInstanceCustomizer | 1 - .../dubbo/config/DubboConsumerBootstrap.java | 59 +++++ .../dubbo/config/DubboProviderBootstrap.java | 84 +++++++ .../apache/dubbo/config/api/DemoService.java | 3 + .../InMemoryLocalMetadataService.java | 20 +- .../org/apache/dubbo/registry/Registry.java | 8 - .../DefaultMetadataServiceProxyFactory.java | 42 ++++ ...tedServicesRevisionMetadataCustomizer.java | 64 +++++ .../client/metadata/MetadataServiceProxy.java | 114 +++++++++ .../metadata/MetadataServiceProxyFactory.java | 77 ++---- .../metadata/MetadataServiceURLBuilder.java | 81 +++++++ ...ataServiceURLParamsMetadataCustomizer.java | 6 +- .../ServiceInstanceMetadataUtils.java | 145 +++++++----- .../RandomServiceInstanceSelector.java | 47 ++++ .../selector/ServiceInstanceSelector.java | 43 ++++ .../support/ServiceOrientedRegistry.java | 219 ++++++++++++------ ...lient.metadata.MetadataServiceProxyFactory | 1 + ...ry.client.selector.ServiceInstanceSelector | 1 + ....registry.client.ServiceInstanceCustomizer | 3 +- .../ServiceInstanceMetadataUtilsTest.java | 44 ++-- .../support/ServiceOrientedRegistryTest.java | 10 +- .../zookeeper/ZookeeperServiceDiscovery.java | 43 ++-- 26 files changed, 997 insertions(+), 328 deletions(-) create mode 100644 dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/DubboConsumerBootstrap.java create mode 100644 dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/DubboProviderBootstrap.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/DefaultMetadataServiceProxyFactory.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ExportedServicesRevisionMetadataCustomizer.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxy.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLBuilder.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/selector/RandomServiceInstanceSelector.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/selector/ServiceInstanceSelector.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.metadata.MetadataServiceProxyFactory create mode 100644 dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.selector.ServiceInstanceSelector diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java b/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java index 1be19edc5ac..82627f228c1 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java @@ -339,6 +339,30 @@ public static String decode(String value) { } } + static String appendDefaultPort(String address, int defaultPort) { + if (address != null && address.length() > 0 && defaultPort > 0) { + int i = address.indexOf(':'); + if (i < 0) { + return address + ":" + defaultPort; + } else if (Integer.parseInt(address.substring(i + 1)) == 0) { + return address.substring(0, i + 1) + defaultPort; + } + } + return address; + } + + public static String buildKey(String path, String group, String version) { + StringBuilder buf = new StringBuilder(); + if (group != null && group.length() > 0) { + buf.append(group).append("/"); + } + buf.append(path); + if (version != null && version.length() > 0) { + buf.append(":").append(version); + } + return buf.toString(); + } + public String getProtocol() { return protocol; } @@ -452,18 +476,6 @@ public List getBackupUrls() { return urls; } - static String appendDefaultPort(String address, int defaultPort) { - if (address != null && address.length() > 0 && defaultPort > 0) { - int i = address.indexOf(':'); - if (i < 0) { - return address + ":" + defaultPort; - } else if (Integer.parseInt(address.substring(i + 1)) == 0) { - return address.substring(0, i + 1) + defaultPort; - } - } - return address; - } - public String getPath() { return path; } @@ -1325,6 +1337,7 @@ public String getEncodedServiceKey() { /** * The format of return value is '{group}/{interfaceName}:{version}' + * * @return */ public String getServiceKey() { @@ -1337,6 +1350,7 @@ public String getServiceKey() { /** * The format of return value is '{group}/{path/interfaceName}:{version}' + * * @return */ public String getPathKey() { @@ -1347,18 +1361,6 @@ public String getPathKey() { return buildKey(inf, getParameter(GROUP_KEY), getParameter(VERSION_KEY)); } - public static String buildKey(String path, String group, String version) { - StringBuilder buf = new StringBuilder(); - if (group != null && group.length() > 0) { - buf.append(group).append("/"); - } - buf.append(path); - if (version != null && version.length() > 0) { - buf.append(":").append(version); - } - return buf.toString(); - } - public String toServiceStringWithoutResolving() { return buildString(true, false, false, true); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java index 647ac81c7b9..fdf742a618e 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java @@ -52,4 +52,26 @@ public interface RegistryConstants { String OVERRIDE_PROTOCOL = "override"; String COMPATIBLE_CONFIG_KEY = "compatible_config"; + + /** + * The parameter key of Dubbo Registry type + * + * @since 2.7.3 + */ + String REGISTRY_TYPE_KEY = "registry-type"; + + /** + * The parameter value of Service-Oriented Registry type + * + * @since 2.7.3 + */ + String SERVICE_REGISTRY_TYPE = "service"; + + /** + * The parameter key of the subscribed service names for Service-Oriented Registry + * + * @since 2.7.3 + */ + public static final String SUBSCRIBED_SERVICE_NAMES_KEY = "subscribed-services"; + } diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml index 0b145d8cb22..b8f5938b112 100644 --- a/dubbo-config/dubbo-config-api/pom.xml +++ b/dubbo-config/dubbo-config-api/pom.xml @@ -79,17 +79,55 @@ ${project.parent.version} test + org.apache.dubbo dubbo-remoting-netty4 ${project.parent.version} test + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.parent.version} + test + + org.apache.dubbo dubbo-registry-multicast ${project.parent.version} test + + + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.parent.version} + test + + + + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.parent.version} + test + + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.parent.version} + test + + + + org.apache.curator + curator-test + test + diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/DubboProtocolsConfigMetadataCustomizer.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/DubboProtocolsConfigMetadataCustomizer.java index 9d00066b084..cffd33206f2 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/DubboProtocolsConfigMetadataCustomizer.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/DubboProtocolsConfigMetadataCustomizer.java @@ -1,50 +1,50 @@ -/* - * 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.config.metadata; - -import org.apache.dubbo.config.ProtocolConfig; -import org.apache.dubbo.config.context.ConfigManager; -import org.apache.dubbo.registry.client.ServiceInstance; -import org.apache.dubbo.registry.client.ServiceInstanceCustomizer; - -import java.util.Map; - -import static java.lang.String.valueOf; -import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.protocolPortMetadataKey; - -/** - * The {@link ServiceInstanceCustomizer customizer} to add the content of {@link ProtocolConfig protocol configs} - * into {@link ServiceInstance#getMetadata() the metadata of service instance}. - * - * @see ServiceInstanceCustomizer - * @since 2.7.3 - */ -public class DubboProtocolsConfigMetadataCustomizer implements ServiceInstanceCustomizer { - - @Override - public void customize(ServiceInstance serviceInstance) { - Map metadata = serviceInstance.getMetadata(); - ConfigManager configManager = ConfigManager.getInstance(); - configManager.getProtocols() - .values() - .forEach(protocolConfig -> { - String key = protocolPortMetadataKey((protocolConfig.getName())); - String port = valueOf(protocolConfig.getPort()); - metadata.put(key, port); - }); - } -} +///* +// * 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.config.metadata; +// +//import org.apache.dubbo.config.ProtocolConfig; +//import org.apache.dubbo.config.context.ConfigManager; +//import org.apache.dubbo.registry.client.ServiceInstance; +//import org.apache.dubbo.registry.client.ServiceInstanceCustomizer; +// +//import java.util.Map; +// +//import static java.lang.String.valueOf; +//import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.protocolPortMetadataKey; +// +///** +// * The {@link ServiceInstanceCustomizer customizer} to add the content of {@link ProtocolConfig protocol configs} +// * into {@link ServiceInstance#getMetadata() the metadata of service instance}. +// * +// * @see ServiceInstanceCustomizer +// * @since 2.7.3 +// */ +//public class DubboProtocolsConfigMetadataCustomizer implements ServiceInstanceCustomizer { +// +// @Override +// public void customize(ServiceInstance serviceInstance) { +// Map metadata = serviceInstance.getMetadata(); +// ConfigManager configManager = ConfigManager.getInstance(); +// configManager.getProtocols() +// .values() +// .forEach(protocolConfig -> { +// String key = protocolPortMetadataKey((protocolConfig.getName())); +// String port = valueOf(protocolConfig.getPort()); +// metadata.put(key, port); +// }); +// } +//} diff --git a/dubbo-config/dubbo-config-api/src/main/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceInstanceCustomizer b/dubbo-config/dubbo-config-api/src/main/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceInstanceCustomizer index d11d2432de2..e708dc04911 100644 --- a/dubbo-config/dubbo-config-api/src/main/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceInstanceCustomizer +++ b/dubbo-config/dubbo-config-api/src/main/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceInstanceCustomizer @@ -1,2 +1 @@ -org.apache.dubbo.config.metadata.DubboProtocolsConfigMetadataCustomizer org.apache.dubbo.config.metadata.ServiceInstancePortCustomizer \ No newline at end of file diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/DubboConsumerBootstrap.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/DubboConsumerBootstrap.java new file mode 100644 index 00000000000..ff0fa2dfe95 --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/DubboConsumerBootstrap.java @@ -0,0 +1,59 @@ +/* + * 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.config; + +import org.apache.dubbo.config.api.DemoService; + +import java.io.IOException; + +/** + * Dubbo Consumer Bootstrap + * + * @since 2.7.3 + */ +public class DubboConsumerBootstrap { + + public static void main(String[] args) throws IOException { + + ApplicationConfig application = new ApplicationConfig(); + application.setName("dubbo-consumer-demo"); + + // 连接注册中心配置 + RegistryConfig registry = new RegistryConfig(); + registry.setAddress("zookeeper://127.0.0.1:2181?registry-type=service"); + + // 服务提供者协议配置 + ProtocolConfig protocol = new ProtocolConfig(); + protocol.setName("dubbo"); + protocol.setPort(12345); + + ReferenceConfig reference = new ReferenceConfig(); // 此实例很重,封装了与注册中心的连接以及与提供者的连接,请自行缓存,否则可能造成内存和连接泄漏 + reference.setApplication(application); + reference.setRegistry(registry); // 多个注册中心可以用setRegistries() + reference.setInterface(DemoService.class); + reference.setVersion("1.0.0"); + reference.setProtocol("dubbo"); + + // 和本地bean一样使用xxxService + DemoService demoService1 = reference.get(); + + System.out.println(demoService1.sayName("Hello,World")); + + System.in.read(); + } + +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/DubboProviderBootstrap.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/DubboProviderBootstrap.java new file mode 100644 index 00000000000..ce5cd6a59ea --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/DubboProviderBootstrap.java @@ -0,0 +1,84 @@ +/* + * 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.config; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.utils.NetUtils; +import org.apache.dubbo.config.api.DemoService; +import org.apache.dubbo.config.metadata.ConfigurableMetadataServiceExporter; +import org.apache.dubbo.config.provider.impl.DemoServiceImpl; +import org.apache.dubbo.metadata.MetadataServiceExporter; +import org.apache.dubbo.registry.client.DefaultServiceInstance; +import org.apache.dubbo.registry.client.ServiceDiscovery; +import org.apache.dubbo.registry.client.ServiceDiscoveryFactory; + +import java.io.IOException; + +/** + * Dubbo Provider Bootstrap + */ +public class DubboProviderBootstrap { + + public static void main(String[] args) throws IOException { + + ApplicationConfig application = new ApplicationConfig(); + application.setName("dubbo-provider-demo"); + + URL connectionURL = URL.valueOf("zookeeper://127.0.0.1:2181?registry-type=service"); + + // 连接注册中心配置 + RegistryConfig registry = new RegistryConfig(); + registry.setAddress(connectionURL.toString()); + + // 服务提供者协议配置 + ProtocolConfig protocol = new ProtocolConfig(); + protocol.setName("dubbo"); + protocol.setPort(NetUtils.getAvailablePort()); + + DemoService demoService = new DemoServiceImpl(); + + ServiceConfig service = new ServiceConfig<>(); + service.setApplication(application); + service.setRegistry(registry); // 多个注册中心可以用setRegistries() + service.setProtocol(protocol); // 多个协议可以用setProtocols() + service.setInterface(DemoService.class); + service.setRef(demoService); + service.setVersion("1.0.0"); + + // 暴露及注册服务 + service.export(); + + MetadataServiceExporter exporter = new ConfigurableMetadataServiceExporter(); + + // 暴露 MetadataService 服务 + exporter.export(); + + ServiceDiscoveryFactory factory = ServiceDiscoveryFactory.getDefaultExtension(); + + ServiceDiscovery serviceDiscovery = factory.create(connectionURL); + + serviceDiscovery.start(); + + DefaultServiceInstance serviceInstance = new DefaultServiceInstance(application.getName(), "127.0.0.1", protocol.getPort()); + + serviceDiscovery.register(serviceInstance); + + System.in.read(); + + serviceDiscovery.stop(); + } +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/DemoService.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/DemoService.java index c5bc7226580..30d745e84aa 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/DemoService.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/DemoService.java @@ -34,4 +34,7 @@ public interface DemoService { int echo(int i); + default String name() { + return getClass().getSimpleName(); + } } \ No newline at end of file diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java index 13df9c52903..947a9fbd284 100644 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java +++ b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java @@ -93,17 +93,17 @@ public List getExportedURLs(String serviceInterface, String group, Strin @Override public boolean exportURL(URL url) { - if (isMetadataServiceURL(url)) { // ignore MetadataService in the export phase - return true; - } +// if (isMetadataServiceURL(url)) { // ignore MetadataService in the export phase +// return true; +// } return addURL(exportedServiceURLs, url); } @Override public boolean unexportURL(URL url) { - if (isMetadataServiceURL(url)) { // ignore MetadataService in the export phase - return true; - } +// if (isMetadataServiceURL(url)) { // ignore MetadataService in the export phase +// return true; +// } return removeURL(exportedServiceURLs, url); } @@ -175,10 +175,10 @@ private static boolean isAcceptableProtocol(String protocol, URL url) { || protocol.equals(url.getProtocol()); } - private static boolean isMetadataServiceURL(URL url) { - String serviceInterface = url.getServiceInterface(); - return METADATA_SERVICE_CLASS_NAME.equals(serviceInterface); - } +// private static boolean isMetadataServiceURL(URL url) { +// String serviceInterface = url.getServiceInterface(); +// return METADATA_SERVICE_CLASS_NAME.equals(serviceInterface); +// } private static List getAllUnmodifiableServiceURLs(Map> serviceURLs) { return unmodifiableList( diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Registry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Registry.java index a35a856450b..835c27a291d 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Registry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Registry.java @@ -18,7 +18,6 @@ import org.apache.dubbo.common.Node; import org.apache.dubbo.common.URL; -import org.apache.dubbo.registry.client.ServiceDiscovery; /** * Registry. (SPI, Prototype, ThreadSafe) @@ -27,11 +26,4 @@ * @see org.apache.dubbo.registry.support.AbstractRegistry */ public interface Registry extends Node, RegistryService { - - /** - * The parameter name of {@link ServiceDiscovery}'s type - * - * @since 2.7.3 - */ - public static final String TYPE_PARAM_NAME = "registry-type"; } \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/DefaultMetadataServiceProxyFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/DefaultMetadataServiceProxyFactory.java new file mode 100644 index 00000000000..65af122b097 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/DefaultMetadataServiceProxyFactory.java @@ -0,0 +1,42 @@ +/* + * 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.client.metadata; + +import org.apache.dubbo.metadata.MetadataService; +import org.apache.dubbo.registry.client.ServiceInstance; +import org.apache.dubbo.rpc.Protocol; + +import java.lang.reflect.Proxy; + +/** + * The factory of {@link MetadataService}'s {@link Proxy} + * + * @since 2.7.3 + */ +public class DefaultMetadataServiceProxyFactory implements MetadataServiceProxyFactory { + + private Protocol protocol; + + public void setProtocol(Protocol protocol) { + this.protocol = protocol; + } + + @Override + public MetadataService createProxy(ServiceInstance serviceInstance) { + return new MetadataServiceProxy(serviceInstance, protocol); + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ExportedServicesRevisionMetadataCustomizer.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ExportedServicesRevisionMetadataCustomizer.java new file mode 100644 index 00000000000..6d7b50af401 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ExportedServicesRevisionMetadataCustomizer.java @@ -0,0 +1,64 @@ +/* + * 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.client.metadata; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.compiler.support.ClassUtils; +import org.apache.dubbo.metadata.LocalMetadataService; +import org.apache.dubbo.metadata.MetadataService; +import org.apache.dubbo.registry.client.ServiceInstance; +import org.apache.dubbo.registry.client.ServiceInstanceMetadataCustomizer; + +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import static java.lang.String.valueOf; +import static java.util.Objects.hash; +import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.EXPORTED_SERVICES_REVISION_KEY; + +/** + * The customizer to a add the metadata that the reversion of Dubbo exported services calculates. + * + * @since 2.7.3 + */ +public class ExportedServicesRevisionMetadataCustomizer extends ServiceInstanceMetadataCustomizer { + + @Override + protected String buildMetadataKey(ServiceInstance serviceInstance) { + return EXPORTED_SERVICES_REVISION_KEY; + } + + @Override + protected String buildMetadataValue(ServiceInstance serviceInstance) { + LocalMetadataService localMetadataService = LocalMetadataService.getDefaultExtension(); + List exportedURLs = localMetadataService.getExportedURLs(); + Object[] data = exportedURLs.stream() + .map(URL::valueOf) + .map(URL::getServiceInterface) + .filter(name -> !MetadataService.class.getName().equals(name)) + .map(ClassUtils::forName) + .map(Class::getMethods) + .map(Arrays::asList) + .flatMap(Collection::stream) + .map(Object::toString) + .sorted() + .toArray(); + + return valueOf(hash(data)); + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxy.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxy.java new file mode 100644 index 00000000000..4cdd80b575c --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxy.java @@ -0,0 +1,114 @@ +/* + * 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.client.metadata; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.metadata.MetadataService; +import org.apache.dubbo.registry.client.ServiceInstance; +import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.Protocol; +import org.apache.dubbo.rpc.proxy.InvokerInvocationHandler; + +import java.util.Iterator; +import java.util.List; +import java.util.function.Function; + +import static java.lang.reflect.Proxy.newProxyInstance; +import static org.apache.dubbo.registry.client.metadata.MetadataServiceURLBuilder.INSTANCE; + +/** + * The Proxy object for the {@link MetadataService} whose {@link ServiceInstance} providers may export multiple + * {@link Protocol protocols} at the same time. + * + * @see ServiceInstance + * @see MetadataService + * @since 2.7.2 + */ +class MetadataServiceProxy implements MetadataService { + + private final Logger logger = LoggerFactory.getLogger(getClass()); + + private final List urls; + + private final Protocol protocol; + + public MetadataServiceProxy(ServiceInstance serviceInstance, Protocol protocol) { + this(INSTANCE.build(serviceInstance), protocol); + } + + public MetadataServiceProxy(List urls, Protocol protocol) { + this.urls = urls; + this.protocol = protocol; + } + + @Override + public String serviceName() { + return doInMetadataService(MetadataService::serviceName); + } + + @Override + public List getSubscribedURLs() { + return doInMetadataService(MetadataService::getSubscribedURLs); + } + + @Override + public List getExportedURLs(String serviceInterface, String group, String version, String protocol) { + return doInMetadataService(metadataService -> + metadataService.getExportedURLs(serviceInterface, group, version, protocol)); + } + + protected T doInMetadataService(Function callback) { + + T result = null; // execution result + + Throwable exception = null; // exception maybe present + + Iterator iterator = urls.iterator(); + + while (iterator.hasNext()) { // Executes MetadataService's method until success + URL url = iterator.next(); + Invoker invoker = null; + try { + invoker = this.protocol.refer(MetadataService.class, url); + MetadataService proxy = (MetadataService) newProxyInstance(getClass().getClassLoader(), + new Class[]{MetadataService.class}, new InvokerInvocationHandler(invoker)); + result = callback.apply(proxy); + exception = null; + } catch (Throwable e) { + exception = e; + // If met with some error, invoke next + if (logger.isErrorEnabled()) { + logger.error(e.getMessage(), e); + } + } finally { + if (invoker != null) { + // to destroy the Invoker finally + invoker.destroy(); + invoker = null; + } + } + } + + if (exception != null) { // If all executions were failed + throw new RuntimeException(exception.getMessage(), exception); + } + + return result; + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxyFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxyFactory.java index d2f6e649458..8cb803c0690 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxyFactory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxyFactory.java @@ -16,69 +16,36 @@ */ package org.apache.dubbo.registry.client.metadata; -import org.apache.dubbo.common.URLBuilder; +import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.metadata.MetadataService; import org.apache.dubbo.registry.client.ServiceInstance; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Protocol; -import org.apache.dubbo.rpc.ProxyFactory; -import com.alibaba.fastjson.JSON; - -import java.lang.reflect.Proxy; -import java.util.HashMap; -import java.util.Map; - -import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; /** - * The factory of {@link MetadataService}'s {@link Proxy} + * A factory to create a {@link MetadataService} proxy * + * @see ServiceInstance + * @see MetadataService * @since 2.7.3 */ -public class MetadataServiceProxyFactory { - - private static final String DUBBO_METADATA_SERVICE_PARAMS_KEY = "dubbo.metadata-service.params"; - - private final Protocol protocol; - - private final ProxyFactory proxyFactory; - - private Map> metadataServiceCache = new HashMap<>(); - - public MetadataServiceProxyFactory() { - this.protocol = getExtensionLoader(Protocol.class).getAdaptiveExtension(); - this.proxyFactory = getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - } - - public MetadataService createProxy(ServiceInstance serviceInstance) { - - URLBuilder urlBuilder = createURLBuilder(serviceInstance); - - Invoker invoker = this.protocol.refer(MetadataService.class, urlBuilder.build()); - - return proxyFactory.getProxy(invoker); +@SPI("default") +public interface MetadataServiceProxyFactory { + + /** + * Create a {@link MetadataService} proxy via the specified {@link ServiceInstance} + * + * @param serviceInstance the instance of {@link ServiceInstance} + * @return non-null + */ + MetadataService createProxy(ServiceInstance serviceInstance); + + /** + * Get the default extension of {@link MetadataServiceProxyFactory} + * + * @return non-null + */ + static MetadataServiceProxyFactory getDefaultExtension() { + return getExtensionLoader(MetadataServiceProxyFactory.class).getDefaultExtension(); } - - - private URLBuilder createURLBuilder(ServiceInstance serviceInstance) { - String serviceName = serviceInstance.getServiceName(); - Map metadata = serviceInstance.getMetadata(); - String params = metadata.get(DUBBO_METADATA_SERVICE_PARAMS_KEY); - Map paramsMap = (Map) JSON.parse(params); - URLBuilder urlBuilder = new URLBuilder() - .setProtocol(paramsMap.get(PROTOCOL_KEY)) - .setHost(serviceInstance.getHost()) - .setPort(serviceInstance.getPort()) - .setPath(MetadataService.class.getName()) - .addParameter(GROUP_KEY, serviceName); - - // add parameters - metadata.forEach((name, value) -> urlBuilder.addParameter(name, value)); - - return urlBuilder; - } - } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLBuilder.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLBuilder.java new file mode 100644 index 00000000000..fa6416b6c9b --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLBuilder.java @@ -0,0 +1,81 @@ +/* + * 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.client.metadata; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.URLBuilder; +import org.apache.dubbo.metadata.MetadataService; +import org.apache.dubbo.registry.client.ServiceInstance; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static java.lang.String.valueOf; +import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getMetadataServiceURLsParams; +import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getProviderHost; +import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getProviderPort; + +/** + * The {@link URL} builder for {@link MetadataService} + * + * @see MetadataService + * @since 2.7.3 + */ +class MetadataServiceURLBuilder { + + /** + * The singleton instance of {@link MetadataServiceURLBuilder} + */ + public static final MetadataServiceURLBuilder INSTANCE = new MetadataServiceURLBuilder(); + + private MetadataServiceURLBuilder() { + } + + /** + * Build the {@link URL urls} from {@link ServiceInstance#getMetadata() the metadata} of {@link ServiceInstance} + * + * @param serviceInstance {@link ServiceInstance} + * @return the not-null {@link List} + */ + public List build(ServiceInstance serviceInstance) { + + Map> paramsMap = getMetadataServiceURLsParams(serviceInstance); + + List urls = new ArrayList<>(paramsMap.size()); + + for (Map.Entry> entry : paramsMap.entrySet()) { + + URLBuilder urlBuilder = new URLBuilder(); + String protocol = entry.getKey(); + Map urlParams = entry.getValue(); + String host = getProviderHost(urlParams); + Integer port = getProviderPort(urlParams); + urlBuilder.setHost(host) + .setPort(port) + .setProtocol(protocol) + .setPath(MetadataService.class.getName()); + + // add parameters + entry.getValue().forEach((name, value) -> urlBuilder.addParameter(name, valueOf(value))); + + urls.add(urlBuilder.build()); + } + + return urls; + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLParamsMetadataCustomizer.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLParamsMetadataCustomizer.java index 065b072f4be..97ba53c3404 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLParamsMetadataCustomizer.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLParamsMetadataCustomizer.java @@ -25,6 +25,7 @@ import java.util.List; import static org.apache.dubbo.metadata.MetadataService.toURLs; +import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.METADATA_SERVICE_URL_PARAMS_KEY; import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getMetadataServiceParameter; /** @@ -36,11 +37,6 @@ */ public class MetadataServiceURLParamsMetadataCustomizer extends ServiceInstanceMetadataCustomizer { - /** - * The key of metadata JSON of {@link MetadataService}'s {@link URL} - */ - public static String METADATA_SERVICE_URL_PARAMS_KEY = "dubbo.metadata-service.url-params"; - @Override public String buildMetadataKey(ServiceInstance serviceInstance) { return METADATA_SERVICE_URL_PARAMS_KEY; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtils.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtils.java index d6288927fa3..85c3b65e829 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtils.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtils.java @@ -17,7 +17,6 @@ package org.apache.dubbo.registry.client.metadata; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.metadata.MetadataService; import org.apache.dubbo.registry.client.ServiceInstance; @@ -28,15 +27,10 @@ import java.util.List; import java.util.Map; -import static java.lang.String.format; -import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static java.lang.String.valueOf; +import static java.util.Collections.emptyMap; import static org.apache.dubbo.common.utils.StringUtils.isBlank; -import static org.apache.dubbo.remoting.Constants.BIND_IP_KEY; -import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY; -import static org.apache.dubbo.remoting.Constants.DUBBO_VERSION_KEY; +import static org.apache.dubbo.registry.integration.RegistryProtocol.DEFAULT_REGISTER_PROVIDER_KEYS; /** * The Utilities class for the {@link ServiceInstance#getMetadata() metadata of the service instance} @@ -49,76 +43,64 @@ public class ServiceInstanceMetadataUtils { /** - * The prefix of protocols + * The key of metadata JSON of {@link MetadataService}'s {@link URL} */ - public static final String PROTOCOL_PREFIX = "dubbo.protocols."; + public static String METADATA_SERVICE_URL_PARAMS_KEY = "dubbo.metadata-service.url-params"; /** - * The name {@link String#format(String, Object...) format pattern} for the protocol port + * The key of The revision for all exported Dubbo services. */ - public static String PROTOCOL_PORT_METADATA_KEY_PATTERN = PROTOCOL_PREFIX + "%s.port"; + public static String EXPORTED_SERVICES_REVISION_KEY = "dubbo.exported-services.revision"; /** - * The required {@link URL} parameter names of {@link MetadataService} + * The {@link URL url's} parameter name of Dubbo Provider host */ - private static String[] METADATA_SERVICE_URL_PARAM_NAMES = { - APPLICATION_KEY, - BIND_IP_KEY, - BIND_PORT_KEY, - DUBBO_VERSION_KEY, - RELEASE_KEY, - SIDE_KEY, - VERSION_KEY - }; + public static final String HOST_PARAM_NAME = "provider.host"; /** - * Build the metadata key of the protocol port - * - * @param protocol the name of protocol - * @return non-null + * The {@link URL url's} parameter name of Dubbo Provider port */ - public static String protocolPortMetadataKey(String protocol) { - return format(PROTOCOL_PORT_METADATA_KEY_PATTERN, protocol); - } + public static final String PORT_PARAM_NAME = "provider.port"; /** - * The protocol port from {@link ServiceInstance the specified service instance} + * Get the multiple {@link URL urls'} parameters of {@link MetadataService MetadataService's} Metadata * - * @param serviceInstance {@link ServiceInstance the specified service instance} - * @param protocol the protocol name - * @return The protocol port if found, or null + * @param serviceInstance the instance of {@link ServiceInstance} + * @return non-null {@link Map}, the key is {@link URL#getProtocol() the protocol of URL}, the value is + * {@link #getMetadataServiceURLParams(ServiceInstance, String)} */ - public static Integer getProtocolPort(ServiceInstance serviceInstance, String protocol) { - Map protocolPorts = getProtocolPorts(serviceInstance); - return protocolPorts.get(protocol); + public static Map> getMetadataServiceURLsParams(ServiceInstance serviceInstance) { + Map metadata = serviceInstance.getMetadata(); + String param = metadata.get(METADATA_SERVICE_URL_PARAMS_KEY); + return isBlank(param) ? emptyMap() : (Map) JSON.parse(param); } /** - * Get a {@link Map} of the protocol ports from the metadata {@link Map} + * Get the {@link URL url's} parameters of {@link MetadataService MetadataService's} Metadata * - * @param serviceInstance the {@link ServiceInstance service instance} - * @return the key is the name of protocol, and the value is the port of protocol + * @param serviceInstance the instance of {@link ServiceInstance} + * @return non-null {@link Map} */ - public static Map getProtocolPorts(ServiceInstance serviceInstance) { - return getProtocolPorts(serviceInstance.getMetadata()); + public static Map getMetadataServiceURLParams(ServiceInstance serviceInstance, String protocol) { + Map> params = getMetadataServiceURLsParams(serviceInstance); + return params.getOrDefault(protocol, emptyMap()); } /** - * Get a {@link Map} of the protocol ports from the metadata {@link Map} + * The provider port from {@link ServiceInstance the specified service instance} * - * @param metadata the metadata {@link Map} - * @return the key is the name of protocol, and the value is the port of protocol + * @param serviceInstance {@link ServiceInstance the specified service instance} + * @param protocol the protocol name + * @return The protocol port if found, or null */ - public static Map getProtocolPorts(Map metadata) { - Map protocolPorts = new LinkedHashMap<>(); - metadata.forEach((key, value) -> { - if (key.startsWith(PROTOCOL_PREFIX)) { - String[] parts = StringUtils.split(key, '.'); - String protocol = parts[2]; - protocolPorts.put(protocol, Integer.valueOf(value)); - } - }); - return protocolPorts; + public static Integer getProviderPort(ServiceInstance serviceInstance, String protocol) { + Map params = getMetadataServiceURLParams(serviceInstance, protocol); + return getProviderPort(params); + } + + public static String getProviderHost(ServiceInstance serviceInstance, String protocol) { + Map params = getMetadataServiceURLParams(serviceInstance, protocol); + return getProviderHost(params); } public static String getMetadataServiceParameter(List urls) { @@ -126,7 +108,7 @@ public static String getMetadataServiceParameter(List urls) { urls.forEach(url -> { String protocol = url.getProtocol(); - params.put(protocol, getParams(url, METADATA_SERVICE_URL_PARAM_NAMES)); + params.put(protocol, getParams(url)); }); if (params.isEmpty()) { @@ -136,14 +118,55 @@ public static String getMetadataServiceParameter(List urls) { return JSON.toJSONString(params); } - private static Map getParams(URL url, String... parameterNames) { + private static Map getParams(URL providerURL) { Map params = new LinkedHashMap<>(); - for (String parameterName : parameterNames) { - String parameterValue = url.getParameter(parameterName); - if (!isBlank(parameterName)) { + setDefaultParams(params, providerURL); + // set provider host + setProviderHostParam(params, providerURL); + // set provider port + setProviderPortParam(params, providerURL); + return params; + } + + public static String getProviderHost(Map params) { + return valueOf(params.get(HOST_PARAM_NAME)); + } + + public static Integer getProviderPort(Map params) { + return Integer.valueOf(valueOf(params.get(PORT_PARAM_NAME))); + } + + /** + * The revision for all exported Dubbo services from the specified {@link ServiceInstance}. + * + * @param serviceInstance the specified {@link ServiceInstance} + * @return null if not exits + */ + public static String getExportedServicesRevision(ServiceInstance serviceInstance) { + Map metadata = serviceInstance.getMetadata(); + return metadata.get(EXPORTED_SERVICES_REVISION_KEY); + } + + private static void setProviderHostParam(Map params, URL providerURL) { + params.put(HOST_PARAM_NAME, providerURL.getHost()); + } + + private static void setProviderPortParam(Map params, URL providerURL) { + params.put(PORT_PARAM_NAME, valueOf(providerURL.getPort())); + } + + /** + * Set the default parameters via the specified {@link URL providerURL} + * + * @param params the parameters + * @param providerURL the provider's {@link URL} + */ + private static void setDefaultParams(Map params, URL providerURL) { + for (String parameterName : DEFAULT_REGISTER_PROVIDER_KEYS) { + String parameterValue = providerURL.getParameter(parameterName); + if (!isBlank(parameterValue)) { params.put(parameterName, parameterValue); } } - return params; } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/selector/RandomServiceInstanceSelector.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/selector/RandomServiceInstanceSelector.java new file mode 100644 index 00000000000..1b862da2b68 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/selector/RandomServiceInstanceSelector.java @@ -0,0 +1,47 @@ +/* + * 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.client.selector; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.registry.client.ServiceInstance; + +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +/** + * The {@link ServiceInstanceSelector} implementation based on Random algorithm + * + * @see ThreadLocalRandom + * @see ServiceInstanceSelector + * @since 2.7.3 + */ +public class RandomServiceInstanceSelector implements ServiceInstanceSelector { + + @Override + public ServiceInstance select(URL registryURL, List serviceInstances) { + int size = serviceInstances.size(); + if (size < 1) { + return null; + } + int index = selectIndexRandomly(size); + return serviceInstances.get(index); + } + + protected int selectIndexRandomly(int size) { + return ThreadLocalRandom.current().nextInt(size); + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/selector/ServiceInstanceSelector.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/selector/ServiceInstanceSelector.java new file mode 100644 index 00000000000..f9d0edc1a84 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/selector/ServiceInstanceSelector.java @@ -0,0 +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.registry.client.selector; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.extension.Adaptive; +import org.apache.dubbo.common.extension.SPI; +import org.apache.dubbo.registry.client.ServiceInstance; + +import java.util.List; + +/** + * The {@link ServiceInstance} Selector + * + * @since 2.7.2 + */ +@SPI("random") +public interface ServiceInstanceSelector { + + /** + * Select an instance of {@link ServiceInstance} by the specified {@link ServiceInstance service instances} + * + * @param registryURL The {@link URL url} of registry + * @param serviceInstances the specified {@link ServiceInstance service instances} + * @return an instance of {@link ServiceInstance} if available, or null + */ + @Adaptive("service-instance-selector") + ServiceInstance select(URL registryURL, List serviceInstances); +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java index 8de2a98a737..0e7edaafd48 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java @@ -29,28 +29,42 @@ import org.apache.dubbo.registry.client.ServiceDiscoveryFactory; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.registry.client.metadata.MetadataServiceProxyFactory; +import org.apache.dubbo.registry.client.selector.ServiceInstanceSelector; import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import static java.util.Collections.emptyList; +import static java.util.Collections.emptySet; import static java.util.Collections.unmodifiableSet; import static java.util.stream.Collectors.toSet; import static java.util.stream.Stream.of; +import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_TYPE_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_TYPE; +import static org.apache.dubbo.common.constants.RegistryConstants.SUBSCRIBED_SERVICE_NAMES_KEY; +import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; import static org.apache.dubbo.common.utils.CollectionUtils.isEmpty; import static org.apache.dubbo.common.utils.CollectionUtils.isNotEmpty; +import static org.apache.dubbo.common.utils.StringUtils.isBlank; import static org.apache.dubbo.common.utils.StringUtils.split; -import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getProtocolPort; +import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getExportedServicesRevision; +import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getMetadataServiceURLsParams; +import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getProviderHost; +import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getProviderPort; /** * Service-Oriented {@link Registry} that is dislike the traditional {@link Registry} will not communicate to @@ -65,16 +79,6 @@ */ public class ServiceOrientedRegistry extends FailbackRegistry { - /** - * The parameter value of {@link ServiceDiscovery}'s type - */ - public static final String TYPE_PARAM_VALUE = "service"; - - /** - * The parameter name of the subscribed service names - */ - public static final String SUBSCRIBED_SERVICE_NAMES_PARAM_NAME = "subscribed-services"; - protected final Logger logger = LoggerFactory.getLogger(getClass()); private final ServiceDiscovery serviceDiscovery; @@ -88,19 +92,19 @@ public class ServiceOrientedRegistry extends FailbackRegistry { private final MetadataServiceProxyFactory metadataServiceProxyFactory; - public ServiceOrientedRegistry(URL url) { - super(url); - this.serviceDiscovery = buildServiceDiscovery(url); - this.subscribedServices = buildSubscribedServices(url); + public ServiceOrientedRegistry(URL registryURL) { + super(registryURL); + this.serviceDiscovery = buildServiceDiscovery(registryURL); + this.subscribedServices = buildSubscribedServices(registryURL); this.serviceNameMapping = ServiceNameMapping.getDefaultExtension(); this.localMetadataService = LocalMetadataService.getDefaultExtension(); - this.metadataServiceProxyFactory = new MetadataServiceProxyFactory(); + this.metadataServiceProxyFactory = MetadataServiceProxyFactory.getDefaultExtension(); } private Set buildSubscribedServices(URL url) { - String[] subscribedServices = split(url.getParameter(SUBSCRIBED_SERVICE_NAMES_PARAM_NAME), ','); - return unmodifiableSet( - of(subscribedServices) + String subscribedServiceNames = url.getParameter(SUBSCRIBED_SERVICE_NAMES_KEY); + return isBlank(subscribedServiceNames) ? emptySet() : + unmodifiableSet(of(split(subscribedServiceNames, ',')) .map(String::trim) .filter(StringUtils::isNotEmpty) .collect(toSet())); @@ -113,23 +117,27 @@ private ServiceDiscovery buildServiceDiscovery(URL url) { return serviceDiscovery; } - protected boolean shouldRegister(URL url) { - String side = url.getParameter(SIDE_KEY); + protected boolean shouldRegister(URL providerURL) { + String side = providerURL.getParameter(SIDE_KEY); boolean should = PROVIDER_SIDE.equals(side); // Only register the Provider. if (!should) { if (logger.isDebugEnabled()) { - logger.debug(String.format("The URL[%s] should not be registered.", url.toString())); + logger.debug(String.format("The URL[%s] should not be registered.", providerURL.toString())); } } return should; } + protected boolean shouldSubscribe(URL subscribedURL) { + return !shouldRegister(subscribedURL); + } + @Override public void doRegister(URL url) { - if (!shouldRegister(url)) { + if (!shouldRegister(url)) { // Should Not Register return; } if (localMetadataService.exportURL(url)) { @@ -161,6 +169,9 @@ public void doUnregister(URL url) { @Override public void doSubscribe(URL url, NotifyListener listener) { + if (!shouldSubscribe(url)) { // Should Not Subscribe + return; + } subscribeURLs(url, listener); } @@ -202,7 +213,7 @@ protected void subscribeURLs(URL url, NotifyListener listener, String serviceNam }); } - protected void subscribeURLs(URL url, NotifyListener listener, String serviceName, + protected void subscribeURLs(URL subscribedURL, NotifyListener listener, String serviceName, Collection serviceInstances) { if (isEmpty(serviceInstances)) { @@ -210,79 +221,157 @@ protected void subscribeURLs(URL url, NotifyListener listener, String serviceNam return; } - List subscribedURLs = getSubscribedURLs(url, serviceInstances); + List subscribedURLs = getSubscribedURLs(subscribedURL, serviceInstances); listener.notify(subscribedURLs); } - private List getSubscribedURLs(URL url, Collection instances) { + private List getSubscribedURLs(URL subscribedURL, Collection instances) { List subscribedURLs = new LinkedList<>(); + // local service instances could be mutable List serviceInstances = new ArrayList<>(instances); - Iterator iterator = serviceInstances.iterator(); - - List templateURLs = null; + /** + * A caches all revisions of exported services in different {@link ServiceInstance}s + * associating with the {@link URL urls} + */ + Map> revisionURLsCache = new HashMap<>(); // try to get the exported URLs from every instance until it's successful. - - while (iterator.hasNext()) { - - ServiceInstance serviceInstance = iterator.next(); - - templateURLs = getSubscribedURLs(url, serviceInstance); + for (int i = 0; i < serviceInstances.size(); i++) { + // select a instance of {@link ServiceInstance} + ServiceInstance selectedInstance = selectServiceInstance(serviceInstances); + List templateURLs = getTemplateURLs(subscribedURL, selectedInstance, revisionURLsCache); if (isNotEmpty(templateURLs)) { - // templateURLs as the first result should be added into subscribedURLs + // add templateURLs into subscribedURLs subscribedURLs.addAll(templateURLs); + // remove the selected ServiceInstance in this time, it remains N - 1 elements. + serviceInstances.remove(selectedInstance); break; } } - // If templateURLs is not empty, duplicate it multiple times with different hosts and ports + // Clone the subscribed URLs from the template URLs + List clonedURLs = cloneSubscribedURLs(subscribedURL, serviceInstances, revisionURLsCache); + // Add all cloned URLs into subscribedURLs + subscribedURLs.addAll(clonedURLs); + // clear all revisions + revisionURLsCache.clear(); + // clear local service instances + serviceInstances.clear(); + + return subscribedURLs; + } + + private List cloneSubscribedURLs(URL subscribedURL, Collection serviceInstances, + Map> revisionURLsCache) { + + // If revisionURLsCache is not empty, clone the template URLs to be the subscribed URLs + if (!revisionURLsCache.isEmpty()) { + + List clonedURLs = new LinkedList<>(); + + Iterator iterator = serviceInstances.iterator(); + + while (iterator.hasNext()) { + + ServiceInstance serviceInstance = iterator.next(); - if (isNotEmpty(templateURLs)) { + List templateURLs = getTemplateURLs(subscribedURL, serviceInstance, revisionURLsCache); + // The parameters of URLs that the MetadataService exported + Map> serviceURLsParams = getMetadataServiceURLsParams(serviceInstance); - templateURLs.forEach(templateURL -> { + templateURLs.forEach(templateURL -> { - String protocol = templateURL.getProtocol(); + String protocol = templateURL.getProtocol(); - while (iterator.hasNext()) { - ServiceInstance serviceInstance = iterator.next(); + Map serviceURLParams = serviceURLsParams.get(protocol); - String host = serviceInstance.getHost(); - Integer port = getProtocolPort(serviceInstance, protocol); + String host = getProviderHost(serviceURLParams); - if (port == null) { - if (logger.isWarnEnabled()) { - logger.warn(String.format("The protocol[%s] port of Dubbo service instance[host : %s] " + - "can't be resolved", protocol, host)); - } - continue; - } + Integer port = getProviderPort(serviceURLParams); - URL subscribedURL = new URL(protocol, host, port, templateURL.getParameters()); - subscribedURLs.add(subscribedURL); - } - }); + /** + * clone the subscribed {@link URL urls} based on the template {@link URL url} + */ + URL newSubscribedURL = new URL(protocol, host, port, templateURL.getParameters()); + clonedURLs.add(newSubscribedURL); + }); + } + + return clonedURLs; } + return Collections.emptyList(); + } + - return subscribedURLs; + /** + * Select one {@link ServiceInstance} from the {@link List list} + * + * @param serviceInstances the {@link List list} of {@link ServiceInstance} + * @return null if serviceInstances is empty. + */ + private ServiceInstance selectServiceInstance(List serviceInstances) { + ServiceInstanceSelector selector = getExtensionLoader(ServiceInstanceSelector.class).getAdaptiveExtension(); + return selector.select(getUrl(), serviceInstances); } - private List getSubscribedURLs(URL url, ServiceInstance serviceInstance) { - String serviceInterface = url.getServiceInterface(); - String group = url.getParameter(GROUP_KEY); - String version = url.getParameter(VERSION_KEY); - // The subscribed protocol may be null - String protocol = url.getParameter(PROTOCOL_KEY); + + /** + * Get the template {@link URL urls} from the specified {@link ServiceInstance}. + *

+ * Typically, the revisions of all {@link ServiceInstance instances} in one service are same. However, + * if one service is upgrading one or more Dubbo service interfaces, one of them may have the multiple declarations + * is deploying in the different {@link ServiceInstance service instances}, thus, it has to compare the interface + * contract one by one, the "revision" that is the number is introduced to identify all Dubbo exported interfaces in + * one {@link ServiceInstance service instance}. + *

+ * First, put the revision {@link ServiceInstance service instance} + * associating {@link #getProviderExportedURLs(URL, ServiceInstance) exported URLs} into cache. + *

+ * And then compare a new {@link ServiceInstance service instances'} revision with cached one,If they are equal, + * return the cached template {@link URL urls} immediately, or to get template {@link URL urls} that the provider + * {@link ServiceInstance instance} exported via executing {@link #getProviderExportedURLs(URL, ServiceInstance)} + * method. + *

+ * Eventually, the retrieving result will be cached and returned. + * + * @param subscribedURL the subscribed {@link URL url} + * @param selectedInstance the {@link ServiceInstance} + * @param revisionURLsCache A caches all revisions of exported services in different {@link ServiceInstance}s + * associating with the {@link URL urls} + * @return non-null {@link List} of {@link URL urls} + */ + protected List getTemplateURLs(URL subscribedURL, ServiceInstance selectedInstance, + Map> revisionURLsCache) { + // get the revision from the specified {@link ServiceInstance} + String revision = getExportedServicesRevision(selectedInstance); + return revisionURLsCache.computeIfAbsent(revision, key -> getProviderExportedURLs(subscribedURL, selectedInstance)); + } + + /** + * Get the exported {@link URL urls} from the specified provider {@link ServiceInstance instance} + * + * @param subscribedURL the subscribed {@link URL url} + * @param providerInstance the target provider {@link ServiceInstance instance} + * @return non-null {@link List} of {@link URL urls} + */ + protected List getProviderExportedURLs(URL subscribedURL, ServiceInstance providerInstance) { List exportedURLs = emptyList(); + String serviceInterface = subscribedURL.getServiceInterface(); + String group = subscribedURL.getParameter(GROUP_KEY); + String version = subscribedURL.getParameter(VERSION_KEY); + // The subscribed protocol may be null + String protocol = subscribedURL.getParameter(PROTOCOL_KEY); + try { - MetadataService metadataService = metadataServiceProxyFactory.createProxy(serviceInstance); + MetadataService metadataService = metadataServiceProxyFactory.createProxy(providerInstance); List urls = metadataService.getExportedURLs(serviceInterface, group, version, protocol); exportedURLs = urls.stream().map(URL::valueOf).collect(Collectors.toList()); } catch (Throwable e) { @@ -322,7 +411,7 @@ protected Set findMappedServices(URL subscribedURL) { String serviceInterface = subscribedURL.getServiceInterface(); String group = subscribedURL.getParameter(GROUP_KEY); String version = subscribedURL.getParameter(VERSION_KEY); - String protocol = subscribedURL.getProtocol(); + String protocol = subscribedURL.getParameter(PROTOCOL_KEY, DUBBO_PROTOCOL); return serviceNameMapping.get(serviceInterface, group, version, protocol); } @@ -343,6 +432,6 @@ public static ServiceOrientedRegistry create(URL registryURL) { * @return if supported, return true, or false */ public static boolean supports(URL registryURL) { - return TYPE_PARAM_VALUE.equalsIgnoreCase(registryURL.getParameter(TYPE_PARAM_NAME)); + return SERVICE_REGISTRY_TYPE.equalsIgnoreCase(registryURL.getParameter(REGISTRY_TYPE_KEY)); } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.metadata.MetadataServiceProxyFactory b/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.metadata.MetadataServiceProxyFactory new file mode 100644 index 00000000000..48860587024 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.metadata.MetadataServiceProxyFactory @@ -0,0 +1 @@ +default=org.apache.dubbo.registry.client.metadata.DefaultMetadataServiceProxyFactory \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.selector.ServiceInstanceSelector b/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.selector.ServiceInstanceSelector new file mode 100644 index 00000000000..d3cca8cdf63 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.selector.ServiceInstanceSelector @@ -0,0 +1 @@ +random=org.apache.dubbo.registry.client.selector.RandomServiceInstanceSelector \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceInstanceCustomizer b/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceInstanceCustomizer index a5968f9fb71..1d5b9e1281e 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceInstanceCustomizer +++ b/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceInstanceCustomizer @@ -1 +1,2 @@ -org.apache.dubbo.registry.client.metadata.MetadataServiceURLParamsMetadataCustomizer \ No newline at end of file +org.apache.dubbo.registry.client.metadata.MetadataServiceURLParamsMetadataCustomizer +org.apache.dubbo.registry.client.metadata.ExportedServicesRevisionMetadataCustomizer \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtilsTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtilsTest.java index d581adf8718..a588f3695ae 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtilsTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtilsTest.java @@ -21,12 +21,8 @@ import org.junit.jupiter.api.Test; import java.util.Arrays; -import java.util.LinkedHashMap; import java.util.List; -import java.util.Map; -import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getProtocolPorts; -import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.protocolPortMetadataKey; import static org.junit.jupiter.api.Assertions.assertEquals; /** @@ -54,25 +50,25 @@ public void testMetadataServiceURLParameters() { @Test public void testProtocolPorts() { - Map metadata = new LinkedHashMap<>(); - - String key = protocolPortMetadataKey("dubbo"); - assertEquals("dubbo.protocols.dubbo.port", key); - - metadata.put(key, "20880"); - - key = protocolPortMetadataKey("rest"); - assertEquals("dubbo.protocols.rest.port", key); - - metadata.put(key, "8080"); - - Map protocolPorts = getProtocolPorts(metadata); - - Map expected = new LinkedHashMap<>(); - - expected.put("dubbo", 20880); - expected.put("rest", 8080); - - assertEquals(expected, protocolPorts); +// Map metadata = new LinkedHashMap<>(); +// +// String key = protocolPortMetadataKey("dubbo"); +// assertEquals("dubbo.protocols.dubbo.port", key); +// +// metadata.put(key, "20880"); +// +// key = protocolPortMetadataKey("rest"); +// assertEquals("dubbo.protocols.rest.port", key); +// +// metadata.put(key, "8080"); +// +// Map protocolPorts = getProtocolPorts(metadata); +// +// Map expected = new LinkedHashMap<>(); +// +// expected.put("dubbo", 20880); +// expected.put("rest", 8080); +// +// assertEquals(expected, protocolPorts); } } diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/ServiceOrientedRegistryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/ServiceOrientedRegistryTest.java index 21214d172b9..bcbd846495e 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/ServiceOrientedRegistryTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/ServiceOrientedRegistryTest.java @@ -30,9 +30,9 @@ import static org.apache.dubbo.common.URL.valueOf; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_PROTOCOL; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; -import static org.apache.dubbo.registry.Registry.TYPE_PARAM_NAME; -import static org.apache.dubbo.registry.support.ServiceOrientedRegistry.SUBSCRIBED_SERVICE_NAMES_PARAM_NAME; -import static org.apache.dubbo.registry.support.ServiceOrientedRegistry.TYPE_PARAM_VALUE; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_TYPE_KEY; +import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_TYPE; +import static org.apache.dubbo.common.constants.RegistryConstants.SUBSCRIBED_SERVICE_NAMES_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -46,8 +46,8 @@ public class ServiceOrientedRegistryTest { private static final URL registryURL = valueOf("in-memory://localhost:12345") - .addParameter(TYPE_PARAM_NAME, TYPE_PARAM_VALUE) - .addParameter(SUBSCRIBED_SERVICE_NAMES_PARAM_NAME, "a, b , c,d,e ,"); + .addParameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE) + .addParameter(SUBSCRIBED_SERVICE_NAMES_KEY, "a, b , c,d,e ,"); private static final String SERVICE_INTERFACE = "org.apache.dubbo.metadata.MetadataService"; diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscovery.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscovery.java index 5039b0d48e6..6776a7457cf 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscovery.java @@ -22,8 +22,10 @@ import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.event.EventDispatcher; +import org.apache.dubbo.event.EventListener; 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 org.apache.curator.framework.CuratorFramework; @@ -46,7 +48,7 @@ * Zookeeper {@link ServiceDiscovery} implementation based on * Apache Curator X Discovery */ -public class ZookeeperServiceDiscovery implements ServiceDiscovery { +public class ZookeeperServiceDiscovery implements ServiceDiscovery, EventListener { private final Logger logger = LoggerFactory.getLogger(getClass()); @@ -68,6 +70,7 @@ public ZookeeperServiceDiscovery(URL connectionURL) throws Exception { this.rootPath = ROOT_PATH.getParameterValue(connectionURL); this.serviceDiscovery = buildServiceDiscovery(curatorFramework, rootPath); this.dispatcher = EventDispatcher.getDefaultExtension(); + this.dispatcher.addEventListener(this); } public void register(ServiceInstance serviceInstance) throws RuntimeException { @@ -113,7 +116,7 @@ public List getInstances(String serviceName) throws NullPointer @Override public void addServiceInstancesChangedListener(String serviceName, ServiceInstancesChangedListener listener) throws NullPointerException, IllegalArgumentException { - addServiceWatcherIfAbsent(serviceName); + registerServiceWatcher(serviceName); dispatcher.addEventListener(listener); } @@ -127,28 +130,30 @@ private R doInServiceDiscovery(ThrowableFunction + new ZookeeperServiceDiscoveryChangeWatcher(this, serviceName, dispatcher)); + try { + curatorFramework.getChildren().usingWatcher(watcher).forPath(path); + } catch (KeeperException.NoNodeException e) { + // ignored + if (logger.isErrorEnabled()) { + logger.error(e.getMessage()); } + } catch (Exception e) { + throw new IllegalStateException(e.getMessage(), e); } } - private void addServiceWatcherIfAbsent(String serviceName) { - addWatcherIfAbsent(buildServicePath(serviceName), - new ZookeeperServiceDiscoveryChangeWatcher(this, serviceName, dispatcher)); - } - private String buildServicePath(String serviceName) { return rootPath + "/" + serviceName; } + + @Override + public void onEvent(ServiceInstancesChangedEvent event) { + String serviceName = event.getServiceName(); + // re-register again + registerServiceWatcher(serviceName); + } } \ No newline at end of file From 9702156161a67e256e0044e901b801dd4ad6a222 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Tue, 4 Jun 2019 20:58:03 +0800 Subject: [PATCH 27/46] Polish apache/incubator-dubbo#4050 : Dubbo Cloud Native : Add a mechanism to upgrade Dubbo services smoothly --- .../apache/dubbo/config/api/DemoService.java | 6 +-- ...tedServicesRevisionMetadataCustomizer.java | 27 +++++++------ .../support/ServiceOrientedRegistry.java | 39 +++++++++++++++---- 3 files changed, 51 insertions(+), 21 deletions(-) diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/DemoService.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/DemoService.java index 30d745e84aa..f5afc9fefae 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/DemoService.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/DemoService.java @@ -34,7 +34,7 @@ public interface DemoService { int echo(int i); - default String name() { - return getClass().getSimpleName(); - } +// default String name() { +// return getClass().getSimpleName(); +// } } \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ExportedServicesRevisionMetadataCustomizer.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ExportedServicesRevisionMetadataCustomizer.java index 6d7b50af401..5c1cc8e9d11 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ExportedServicesRevisionMetadataCustomizer.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ExportedServicesRevisionMetadataCustomizer.java @@ -33,6 +33,8 @@ /** * The customizer to a add the metadata that the reversion of Dubbo exported services calculates. + *

+ * The reversion is calculated on the methods that all Dubbo exported interfaces declare * * @since 2.7.3 */ @@ -48,17 +50,20 @@ protected String buildMetadataValue(ServiceInstance serviceInstance) { LocalMetadataService localMetadataService = LocalMetadataService.getDefaultExtension(); List exportedURLs = localMetadataService.getExportedURLs(); Object[] data = exportedURLs.stream() - .map(URL::valueOf) - .map(URL::getServiceInterface) - .filter(name -> !MetadataService.class.getName().equals(name)) - .map(ClassUtils::forName) - .map(Class::getMethods) - .map(Arrays::asList) - .flatMap(Collection::stream) - .map(Object::toString) - .sorted() - .toArray(); + .map(URL::valueOf) // String to URL + .map(URL::getServiceInterface) // get the service interface + .filter(this::isNotMetadataService) // filter not MetadataService interface + .map(ClassUtils::forName) // load business interface class + .map(Class::getMethods) // get all public methods from business interface + .map(Arrays::asList) // Array to List + .flatMap(Collection::stream) // flat Stream to be Stream + .map(Object::toString) // Method to String + .sorted() // sort methods marking sure the calculation of reversion is stable + .toArray(); // Stream to Array + return valueOf(hash(data)); // calculate the hash code as reversion + } - return valueOf(hash(data)); + private boolean isNotMetadataService(String serviceInterface) { + return !MetadataService.class.getName().equals(serviceInterface); } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java index 0e7edaafd48..535864f7b26 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java @@ -42,6 +42,7 @@ import java.util.Set; import java.util.stream.Collectors; +import static java.lang.String.format; import static java.util.Collections.emptyList; import static java.util.Collections.emptySet; import static java.util.Collections.unmodifiableSet; @@ -142,11 +143,11 @@ public void doRegister(URL url) { } if (localMetadataService.exportURL(url)) { if (logger.isInfoEnabled()) { - logger.info(String.format("The URL[%s] registered successfully.", url.toString())); + logger.info(format("The URL[%s] registered successfully.", url.toString())); } } else { if (logger.isWarnEnabled()) { - logger.info(String.format("The URL[%s] has been registered.", url.toString())); + logger.info(format("The URL[%s] has been registered.", url.toString())); } } } @@ -158,11 +159,11 @@ public void doUnregister(URL url) { } if (localMetadataService.unexportURL(url)) { if (logger.isInfoEnabled()) { - logger.info(String.format("The URL[%s] deregistered successfully.", url.toString())); + logger.info(format("The URL[%s] deregistered successfully.", url.toString())); } } else { if (logger.isWarnEnabled()) { - logger.info(String.format("The URL[%s] has been deregistered.", url.toString())); + logger.info(format("The URL[%s] has been deregistered.", url.toString())); } } } @@ -194,11 +195,12 @@ public void destroy() { protected void subscribeURLs(URL url, NotifyListener listener) { + localMetadataService.subscribeURL(url); + Set serviceNames = getServices(url); serviceNames.forEach(serviceName -> subscribeURLs(url, listener, serviceName)); - localMetadataService.subscribeURL(url); } protected void subscribeURLs(URL url, NotifyListener listener, String serviceName) { @@ -217,7 +219,7 @@ protected void subscribeURLs(URL subscribedURL, NotifyListener listener, String Collection serviceInstances) { if (isEmpty(serviceInstances)) { - logger.warn(String.format("There is no instance in service[name : %s]", serviceName)); + logger.warn(format("There is no instance in service[name : %s]", serviceName)); return; } @@ -350,7 +352,30 @@ protected List getTemplateURLs(URL subscribedURL, ServiceInstance selectedI Map> revisionURLsCache) { // get the revision from the specified {@link ServiceInstance} String revision = getExportedServicesRevision(selectedInstance); - return revisionURLsCache.computeIfAbsent(revision, key -> getProviderExportedURLs(subscribedURL, selectedInstance)); + // try to get templateURLs from cache + List templateURLs = revisionURLsCache.get(revision); + + if (isEmpty(templateURLs)) { // not exists or getting failed last time + + if (!revisionURLsCache.isEmpty()) { // it's not first time + if (logger.isWarnEnabled()) { + logger.warn(format("The ServiceInstance[id: %s, host : %s , port : %s] has different revision : %s" + + ", please make sure the service [name : %s] is changing or not.", + selectedInstance.getId(), + selectedInstance.getHost(), + selectedInstance.getPort(), + revision, + selectedInstance.getServiceName() + )); + } + } + // get or get again + templateURLs = getProviderExportedURLs(subscribedURL, selectedInstance); + // put into cache + revisionURLsCache.put(revision, templateURLs); + } + + return templateURLs; } /** From 4c10a83926f79181f62197c765a38b7695e4446b Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Tue, 4 Jun 2019 23:25:04 +0800 Subject: [PATCH 28/46] Polish apache/incubator-dubbo#4093 : To add DubboServiceDestroyedEvent --- .../dubbo/config/DubboShutdownHook.java | 8 ++- .../event/DubboServiceDestroyedEvent.java | 32 ++++++++++++ ...ubboProtocolsConfigMetadataCustomizer.java | 50 ------------------- 3 files changed, 39 insertions(+), 51 deletions(-) create mode 100644 dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/DubboServiceDestroyedEvent.java delete mode 100644 dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/DubboProtocolsConfigMetadataCustomizer.java diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/DubboShutdownHook.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/DubboShutdownHook.java index 47c035e293c..309f9075941 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/DubboShutdownHook.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/DubboShutdownHook.java @@ -19,6 +19,8 @@ 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.config.event.DubboServiceDestroyedEvent; +import org.apache.dubbo.event.EventDispatcher; import org.apache.dubbo.registry.support.AbstractRegistryFactory; import org.apache.dubbo.rpc.Protocol; @@ -42,7 +44,9 @@ public class DubboShutdownHook extends Thread { /** * Has it already been destroyed or not? */ - private final AtomicBoolean destroyed= new AtomicBoolean(false); + private final AtomicBoolean destroyed = new AtomicBoolean(false); + + private final EventDispatcher eventDispatcher = EventDispatcher.getDefaultExtension(); private DubboShutdownHook(String name) { super(name); @@ -89,6 +93,8 @@ public void doDestroy() { AbstractRegistryFactory.destroyAll(); // destroy all the protocols destroyProtocols(); + // dispatch the DubboDestroyedEvent @since 2.7.3 + eventDispatcher.dispatch(new DubboServiceDestroyedEvent(this)); } /** diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/DubboServiceDestroyedEvent.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/DubboServiceDestroyedEvent.java new file mode 100644 index 00000000000..a3384aac8df --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/DubboServiceDestroyedEvent.java @@ -0,0 +1,32 @@ +/* + * 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.config.event; + +import org.apache.dubbo.event.Event; + +/** + * An {@link Event Dubbo event} when the Dubbo service is about to be destroyed. + * + * @see Event + * @since 2.7.3 + */ +public class DubboServiceDestroyedEvent extends Event { + + public DubboServiceDestroyedEvent(Object source) { + super(source); + } +} diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/DubboProtocolsConfigMetadataCustomizer.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/DubboProtocolsConfigMetadataCustomizer.java deleted file mode 100644 index cffd33206f2..00000000000 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/DubboProtocolsConfigMetadataCustomizer.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. -// */ -//package org.apache.dubbo.config.metadata; -// -//import org.apache.dubbo.config.ProtocolConfig; -//import org.apache.dubbo.config.context.ConfigManager; -//import org.apache.dubbo.registry.client.ServiceInstance; -//import org.apache.dubbo.registry.client.ServiceInstanceCustomizer; -// -//import java.util.Map; -// -//import static java.lang.String.valueOf; -//import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.protocolPortMetadataKey; -// -///** -// * The {@link ServiceInstanceCustomizer customizer} to add the content of {@link ProtocolConfig protocol configs} -// * into {@link ServiceInstance#getMetadata() the metadata of service instance}. -// * -// * @see ServiceInstanceCustomizer -// * @since 2.7.3 -// */ -//public class DubboProtocolsConfigMetadataCustomizer implements ServiceInstanceCustomizer { -// -// @Override -// public void customize(ServiceInstance serviceInstance) { -// Map metadata = serviceInstance.getMetadata(); -// ConfigManager configManager = ConfigManager.getInstance(); -// configManager.getProtocols() -// .values() -// .forEach(protocolConfig -> { -// String key = protocolPortMetadataKey((protocolConfig.getName())); -// String port = valueOf(protocolConfig.getPort()); -// metadata.put(key, port); -// }); -// } -//} From cafba86ea6bfdd16e6aeb439d55a1454b2606341 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Tue, 4 Jun 2019 23:25:31 +0800 Subject: [PATCH 29/46] Polish apache/incubator-dubbo#4050 : Dubbo Cloud Native : Reactor --- .../dubbo/config/event/listener/ServiceNameMappingListener.java | 2 -- .../dubbo/registry/client/metadata/MetadataServiceProxy.java | 2 +- .../dubbo/registry/client/selector/ServiceInstanceSelector.java | 2 +- 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/listener/ServiceNameMappingListener.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/listener/ServiceNameMappingListener.java index 3295ca0d1f3..bef416ad514 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/listener/ServiceNameMappingListener.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/listener/ServiceNameMappingListener.java @@ -19,7 +19,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.event.ServiceConfigExportedEvent; -import org.apache.dubbo.configcenter.DynamicConfiguration; import org.apache.dubbo.event.EventListener; import org.apache.dubbo.metadata.ServiceNameMapping; @@ -43,7 +42,6 @@ public class ServiceNameMappingListener implements EventListener exportedURLs = serviceConfig.getExportedUrls(); exportedURLs.forEach(url -> { diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxy.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxy.java index 4cdd80b575c..538365f6b96 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxy.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxy.java @@ -38,7 +38,7 @@ * * @see ServiceInstance * @see MetadataService - * @since 2.7.2 + * @since 2.7.3 */ class MetadataServiceProxy implements MetadataService { diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/selector/ServiceInstanceSelector.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/selector/ServiceInstanceSelector.java index f9d0edc1a84..195e8b318d9 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/selector/ServiceInstanceSelector.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/selector/ServiceInstanceSelector.java @@ -26,7 +26,7 @@ /** * The {@link ServiceInstance} Selector * - * @since 2.7.2 + * @since 2.7.3 */ @SPI("random") public interface ServiceInstanceSelector { From 18b69f2130be3894243e40327c5dd70aec4b0b25 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Thu, 6 Jun 2019 14:36:37 +0800 Subject: [PATCH 30/46] Polish apache/incubator-dubbo#3946 : Remove SPI --- .../java/org/apache/dubbo/metadata/MetadataServiceExporter.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceExporter.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceExporter.java index 07190f53f8a..8bbe53c6d2c 100644 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceExporter.java +++ b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceExporter.java @@ -17,7 +17,6 @@ package org.apache.dubbo.metadata; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.SPI; import java.util.List; @@ -29,7 +28,6 @@ * @see #unexport() * @since 2.7.3 */ -@SPI public interface MetadataServiceExporter { /** From 0dcd96000632b65fde5351bb90696ce6a7fb4a3c Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Fri, 7 Jun 2019 00:51:15 +0800 Subject: [PATCH 31/46] Polish apache/incubator-dubbo#4265 : [Feature] Dubbo Cloud Native - Add Bootstrap --- .../dubbo/bootstrap/AbstractSettings.java | 36 + .../dubbo/bootstrap/ApplicationSettings.java | 127 ++++ .../dubbo/bootstrap/DubboBootstrap.java | 646 +++++++++++++++++- .../dubbo/bootstrap/ProtocolSettings.java | 215 ++++++ .../dubbo/bootstrap/ReferenceSettings.java | 334 +++++++++ .../dubbo/bootstrap/RegistrySettings.java | 164 +++++ .../dubbo/bootstrap/ServiceSettings.java | 384 +++++++++++ .../org/apache/dubbo/bootstrap/Settings.java | 32 + .../dubbo/bootstrap/DubboBootstrapTest.java | 54 ++ .../DubboServiceConsumerBootstrap.java | 58 ++ .../DubboServiceProviderBootstrap.java | 52 ++ .../apache/dubbo/bootstrap/EchoService.java | 31 + .../dubbo/bootstrap/EchoServiceImpl.java | 36 + .../config/builders/AbstractBuilder.java | 13 +- .../config/builders/ProtocolBuilder.java | 8 +- .../config/builders/ReferenceBuilder.java | 4 + .../config/builders/RegistryBuilder.java | 8 +- .../dubbo/config/builders/ServiceBuilder.java | 10 +- .../ConfigurableMetadataServiceExporter.java | 51 +- .../ServiceInstancePortCustomizer.java | 6 +- ...che.dubbo.metadata.MetadataServiceExporter | 1 - ...ynamicConfigurationServiceNameMapping.java | 8 + .../support/ServiceOrientedRegistry.java | 9 + 23 files changed, 2240 insertions(+), 47 deletions(-) create mode 100644 dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/AbstractSettings.java create mode 100644 dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/ApplicationSettings.java create mode 100644 dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/ProtocolSettings.java create mode 100644 dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/ReferenceSettings.java create mode 100644 dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/RegistrySettings.java create mode 100644 dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/ServiceSettings.java create mode 100644 dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/Settings.java create mode 100644 dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboBootstrapTest.java create mode 100644 dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceConsumerBootstrap.java create mode 100644 dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceProviderBootstrap.java create mode 100644 dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/EchoService.java create mode 100644 dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/EchoServiceImpl.java delete mode 100644 dubbo-config/dubbo-config-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.MetadataServiceExporter diff --git a/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/AbstractSettings.java b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/AbstractSettings.java new file mode 100644 index 00000000000..6bb9c976bc2 --- /dev/null +++ b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/AbstractSettings.java @@ -0,0 +1,36 @@ +/* + * 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.bootstrap; + +/** + * Abstract {@link Settings} + * + * @since 2.7.3 + */ +public class AbstractSettings implements Settings { + + private final DubboBootstrap dubboBootstrap; + + public AbstractSettings(DubboBootstrap dubboBootstrap) { + this.dubboBootstrap = dubboBootstrap; + } + + @Override + public DubboBootstrap next() { + return dubboBootstrap; + } +} diff --git a/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/ApplicationSettings.java b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/ApplicationSettings.java new file mode 100644 index 00000000000..a9bc9c9467e --- /dev/null +++ b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/ApplicationSettings.java @@ -0,0 +1,127 @@ +/* + * 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.bootstrap; + +import org.apache.dubbo.config.ApplicationConfig; +import org.apache.dubbo.config.MonitorConfig; +import org.apache.dubbo.config.builders.ApplicationBuilder; + +import java.util.Map; + +/** + * {@link ApplicationConfig Application} settings + * + * @since 2.7.3 + */ +public class ApplicationSettings extends AbstractSettings { + + private final ApplicationBuilder builder; + + public ApplicationSettings(ApplicationBuilder builder, DubboBootstrap dubboBootstrap) { + super(dubboBootstrap); + this.builder = builder; + } + + public ApplicationSettings version(String version) { + builder.version(version); + return this; + } + + public ApplicationSettings owner(String owner) { + builder.owner(owner); + return this; + } + + public ApplicationSettings organization(String organization) { + builder.organization(organization); + return this; + } + + public ApplicationSettings architecture(String architecture) { + builder.architecture(architecture); + return this; + } + + public ApplicationSettings environment(String environment) { + builder.environment(environment); + return this; + } + + public ApplicationSettings compiler(String compiler) { + builder.compiler(compiler); + return this; + } + + public ApplicationSettings logger(String logger) { + builder.logger(logger); + return this; + } + + public ApplicationSettings monitor(MonitorConfig monitor) { + builder.monitor(monitor); + return this; + } + + public ApplicationSettings monitor(String monitor) { + builder.monitor(monitor); + return this; + } + + public ApplicationSettings isDefault(Boolean isDefault) { + builder.isDefault(isDefault); + return this; + } + + public ApplicationSettings dumpDirectory(String dumpDirectory) { + builder.dumpDirectory(dumpDirectory); + return this; + } + + public ApplicationSettings qosEnable(Boolean qosEnable) { + builder.qosEnable(qosEnable); + return this; + } + + public ApplicationSettings qosPort(Integer qosPort) { + builder.qosPort(qosPort); + return this; + } + + public ApplicationSettings qosAcceptForeignIp(Boolean qosAcceptForeignIp) { + builder.qosAcceptForeignIp(qosAcceptForeignIp); + return this; + } + + public ApplicationSettings shutwait(String shutwait) { + builder.shutwait(shutwait); + return this; + } + + public ApplicationSettings appendParameter(String key, String value) { + builder.appendParameter(key, value); + return this; + } + + public ApplicationSettings appendParameters(Map appendParameters) { + builder.appendParameters(appendParameters); + return this; + } + + ApplicationConfig build() { + return builder.build(); + } +} diff --git a/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java index 8b3dac232ff..c94febe7e60 100644 --- a/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java +++ b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java @@ -16,17 +16,58 @@ */ package org.apache.dubbo.bootstrap; +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.config.AbstractConfig; +import org.apache.dubbo.config.AbstractInterfaceConfig; import org.apache.dubbo.config.ApplicationConfig; +import org.apache.dubbo.config.DubboShutdownHook; +import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ReferenceConfig; +import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.ServiceConfig; +import org.apache.dubbo.config.builders.AbstractBuilder; +import org.apache.dubbo.config.builders.ApplicationBuilder; +import org.apache.dubbo.config.builders.ProtocolBuilder; +import org.apache.dubbo.config.builders.ReferenceBuilder; +import org.apache.dubbo.config.builders.RegistryBuilder; +import org.apache.dubbo.config.builders.ServiceBuilder; +import org.apache.dubbo.config.context.ConfigManager; +import org.apache.dubbo.config.event.DubboServiceDestroyedEvent; +import org.apache.dubbo.config.event.ServiceConfigExportedEvent; +import org.apache.dubbo.config.metadata.ConfigurableMetadataServiceExporter; +import org.apache.dubbo.event.EventDispatcher; +import org.apache.dubbo.event.EventListener; import org.apache.dubbo.metadata.MetadataServiceExporter; +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.ServiceDiscoveryStartedEvent; +import org.apache.dubbo.registry.client.event.ServiceDiscoveryStoppedEvent; +import org.apache.dubbo.registry.client.event.ServiceInstanceRegisteredEvent; +import org.apache.dubbo.registry.support.ServiceOrientedRegistry; +import java.util.HashMap; import java.util.LinkedList; import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Consumer; +import java.util.stream.Collectors; -import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; +import static java.util.Collections.emptyMap; +import static java.util.concurrent.Executors.newSingleThreadExecutor; +import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; +import static org.apache.dubbo.common.utils.StringUtils.isBlank; +import static org.apache.dubbo.common.utils.StringUtils.split; +import static org.apache.dubbo.common.utils.StringUtils.trim; +import static org.apache.dubbo.registry.support.AbstractRegistryFactory.getRegistries; /** * The bootstrap class of Dubbo @@ -35,47 +76,620 @@ */ public class DubboBootstrap { - private final List> serviceConfigs = new LinkedList<>(); + public static final String DEFAULT_REGISTRY_ID = "REGISTRY#DEFAULT"; - private final List> referenceConfigs = new LinkedList<>(); + public static final String DEFAULT_PROTOCOL_ID = "PROTOCOL#DEFAULT"; - private final MetadataServiceExporter metadataServiceExporter = - getExtensionLoader(MetadataServiceExporter.class).getExtension("default"); + public static final String DEFAULT_SERVICE_ID = "SERVICE#DEFAULT"; + + public static final String DEFAULT_REFERENCE_ID = "REFERENCE#DEFAULT"; + + private static final String NAME = DubboBootstrap.class.getSimpleName(); + + private final Logger logger = LoggerFactory.getLogger(getClass()); + + private final MetadataServiceExporter metadataServiceExporter = new ConfigurableMetadataServiceExporter(); + + private final AtomicBoolean awaited = new AtomicBoolean(false); + + private final Lock lock = new ReentrantLock(); + + private final Condition condition = lock.newCondition(); + + private final ExecutorService executorService = newSingleThreadExecutor(); + + private final EventDispatcher eventDispatcher = EventDispatcher.getDefaultExtension(); + + /** + * Is provider or not + */ + private boolean isProvider; + + private boolean initialized = false; + + private boolean started = false; + + /** + * Only Provider Register + */ + private boolean onlyRegisterProvider = false; private ServiceInstance serviceInstance; + private ApplicationBuilder applicationBuilder; + + private Map registryBuilders = new HashMap<>(); + + private Map protocolBuilders = new HashMap<>(); + + private Map> serviceBuilders = new HashMap<>(); + + private Map> referenceBuilders = new HashMap<>(); + + /** + * The global {@link ApplicationConfig} + */ private ApplicationConfig applicationConfig; - private String serviceDiscoveryType; + /** + * the global {@link RegistryConfig registries} + */ + private Map registryConfigs = emptyMap(); - private ServiceDiscovery serviceDiscovery; + /** + * the global {@link RegistryConfig registries} + */ + private Map protocolConfigs = emptyMap(); + /** + * the global {@link ServiceConfig services} + */ + private Map> serviceConfigs = emptyMap(); + + /** + * the global {@link ReferenceConfig references} + */ + private Map> referenceConfigs = new HashMap<>(); + + public ApplicationSettings application(String name) { + return new ApplicationSettings(initApplicationBuilder(name), this); + } + + public RegistrySettings registry() { + return registry(DEFAULT_REGISTRY_ID); + } + + public RegistrySettings registry(String id) { + return new RegistrySettings(initRegistryBuilder(id), this); + } + + public ProtocolSettings protocol() { + return protocol(DEFAULT_PROTOCOL_ID); + } + + public ProtocolSettings protocol(String id) { + return new ProtocolSettings(initProtocolBuilder(id), this); + } + + public ServiceSettings service(String id) { + return new ServiceSettings(initServiceBuilder(id), this); + } + + public ReferenceSettings reference(String id) { + return new ReferenceSettings<>(initReferenceBuilder(id), this); + } + + /** + * Set only register provider or not + * + * @param onlyRegisterProvider if true, only register the provider and reduce the registries' load. + * @return {@link DubboBootstrap} + */ + public DubboBootstrap onlyRegisterProvider(boolean onlyRegisterProvider) { + this.onlyRegisterProvider = onlyRegisterProvider; + return this; + } + + public DubboBootstrap application(String name, Consumer builder) { + initApplicationBuilder(name); + builder.accept(applicationBuilder); + return this; + } + + public DubboBootstrap registry(String id, Consumer builder) { + builder.accept(initRegistryBuilder(id)); + return this; + } + + public DubboBootstrap protocol(String id, Consumer builder) { + builder.accept(initProtocolBuilder(id)); + return this; + } - public DubboBootstrap applicationConfig(ApplicationConfig applicationConfig) { - this.applicationConfig = applicationConfig; + public DubboBootstrap service(String id, Consumer> builder) { + builder.accept(initServiceBuilder(id)); return this; } - public DubboBootstrap serviceDiscoveryType(String serviceDiscoveryType) { - this.serviceDiscoveryType = serviceDiscoveryType; + public DubboBootstrap reference(String id, Consumer> builder) { + builder.accept(initReferenceBuilder(id)); return this; } - public void start() { + /** + * Initialize + */ + public void init() { + if (isInitialized()) { + return; + } - registerSelfInstance(); + initApplicationConfig(); + initRegistryConfigs(); - metadataServiceExporter.export(); + initProtocolConfigs(); + + initServiceConfigs(); + + initReferenceConfigs(); + + initEventListeners(); + + clearBuilders(); + + initialized = true; + + if (logger.isInfoEnabled()) { + logger.info(NAME + " has been initialized!"); + } + } + + /** + * Get the {@link ServiceConfig} by specified id + * + * @param id The {@link ServiceConfig#getId() id} of {@link ServiceConfig} + * @param the type of service interface + * @return null if not found + */ + public ServiceConfig serviceConfig(String id) { + return (ServiceConfig) serviceConfigs.get(id); + } + + /** + * Get the {@link ReferenceConfig} by specified id + * + * @param id The {@link ReferenceConfig#getId() id} of {@link ReferenceConfig} + * @param the type of service interface + * @return null if not found + */ + public ReferenceConfig referenceConfig(String id) { + return (ReferenceConfig) referenceConfigs.get(id); + } + + private List getServiceDiscoveries() { + return getRegistries() + .stream() + .filter(registry -> ServiceOrientedRegistry.class.isInstance(registry)) + .map(registry -> ServiceOrientedRegistry.class.cast(registry)) + .map(ServiceOrientedRegistry::getServiceDiscovery) + .collect(Collectors.toList()); } - private void registerSelfInstance() { -// serviceInstance = new + /** + * Start the bootstrap + */ + public DubboBootstrap start() { + + if (!isStarted()) { + if (!isInitialized()) { + init(); + } + + exportServices(); + + // Not only provider register and some services are exported + if (!onlyRegisterProvider && !serviceConfigs.isEmpty()) { + /** + * export {@link MetadataService} + */ + List exportedURLs = exportMetadataService(applicationConfig, registryConfigs, protocolConfigs); + + /** + * Register the local {@link ServiceInstance} + */ + registerServiceInstance(exportedURLs); + } + + started = true; + + if (logger.isInfoEnabled()) { + logger.info(NAME + " is starting..."); + } + } + return this; } + /** + * Block current thread to be await. + * + * @return {@link DubboBootstrap} + */ + public DubboBootstrap await() { + // has been waited, return immediately + if (!awaited.get()) { + if (!executorService.isShutdown()) { + executorService.execute(() -> executeMutually(() -> { + while (!awaited.get()) { + if (logger.isInfoEnabled()) { + logger.info(NAME + " is awaiting..."); + } + try { + condition.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + })); + } + } + return this; + } + /** + * Stop the bootstrap + */ public void stop() { + if (!isInitialized() || !isStarted()) { + return; + } + + unregisterServiceInstance(); + + destroy(); + + clear(); + + release(); + + shutdown(); + } + + public boolean isInitialized() { + return initialized; + } + + public boolean isStarted() { + return started; + } + + private ApplicationBuilder initApplicationBuilder(String name) { + applicationBuilder = new ApplicationBuilder().name(name); + return applicationBuilder; + } + + private RegistryBuilder createRegistryBuilder(String id) { + return new RegistryBuilder().id(id); + } + + private ProtocolBuilder createProtocolBuilder(String id) { + return new ProtocolBuilder().id(id); + } + + private ServiceBuilder createServiceBuilder(String id) { + return new ServiceBuilder().id(id); + } + + private ReferenceBuilder createReferenceBuilder(String id) { + return new ReferenceBuilder().id(id); + } + + private RegistryBuilder initRegistryBuilder(String id) { + return registryBuilders.computeIfAbsent(id, this::createRegistryBuilder); + } + + private ProtocolBuilder initProtocolBuilder(String id) { + return protocolBuilders.computeIfAbsent(id, this::createProtocolBuilder); + } + + private ServiceBuilder initServiceBuilder(String id) { + return serviceBuilders.computeIfAbsent(id, this::createServiceBuilder); + } + + private ReferenceBuilder initReferenceBuilder(String id) { + return referenceBuilders.computeIfAbsent(id, this::createReferenceBuilder); + } + + private void initApplicationConfig() { + this.applicationConfig = buildApplicationConfig(); + } + + private void initRegistryConfigs() { + this.registryConfigs = buildRegistryConfigs(); + } + + private void initProtocolConfigs() { + this.protocolConfigs = buildProtocolConfigs(); + } + + private void initReferenceConfigs() { + this.referenceConfigs = buildReferenceConfigs(); + this.referenceConfigs.values().forEach(this::initReferenceConfig); + } + + private void initEventListeners() { + addEventListener(new EventListener() { + @Override + public void onEvent(ServiceInstanceRegisteredEvent event) { + if (logger.isInfoEnabled()) { + logger.info(event.getServiceInstance() + " has been registered."); + } + + } + }).addEventListener(new EventListener() { + @Override + public void onEvent(ServiceDiscoveryStartedEvent event) { + if (logger.isInfoEnabled()) { + logger.info(event.getServiceDiscovery() + " has been started."); + } + } + }).addEventListener(new EventListener() { + @Override + public void onEvent(ServiceConfigExportedEvent event) { + if (logger.isInfoEnabled()) { + logger.info(event.getServiceConfig().toString() + " has been exported."); + } + } + }).addEventListener(new EventListener() { + @Override + public void onEvent(ServiceDiscoveryStoppedEvent event) { + if (logger.isInfoEnabled()) { + logger.info(event.getServiceDiscovery() + " has been stopped."); + } + } + }).addEventListener(new EventListener() { + @Override + public void onEvent(DubboServiceDestroyedEvent event) { + release(); + if (logger.isInfoEnabled()) { + logger.info(NAME + " has been shutdown."); + } + } + }); + + } + + /** + * Add an instance of {@link EventListener} + * + * @param listener {@link EventListener} + * @return {@link DubboBootstrap} + */ + public DubboBootstrap addEventListener(EventListener listener) { + eventDispatcher.addEventListener(listener); + return this; + } + + private void initServiceConfigs() { + this.serviceConfigs = buildServiceConfigs(); + this.serviceConfigs.values().forEach(this::initServiceConfig); + } + + private List exportMetadataService(ApplicationConfig applicationConfig, + Map globalRegistryConfigs, + Map globalProtocolConfigs) { + ConfigurableMetadataServiceExporter exporter = new ConfigurableMetadataServiceExporter(); + exporter.setApplicationConfig(applicationConfig); + exporter.setRegistries(globalRegistryConfigs.values()); + exporter.setProtocols(globalProtocolConfigs.values()); + return exporter.export(); + } + + private ApplicationConfig buildApplicationConfig() { + return applicationBuilder.build(); + } + + private Map buildProtocolConfigs() { + return buildConfigs(protocolBuilders); + } + + private Map buildRegistryConfigs() { + return buildConfigs(registryBuilders); + } + + private Map> buildServiceConfigs() { + return buildConfigs(serviceBuilders); + } + + private Map> buildReferenceConfigs() { + return buildConfigs(referenceBuilders); + } + + private void exportServices() { + serviceConfigs.values().forEach(this::exportServiceConfig); + } + + private void initServiceConfig(ServiceConfig serviceConfig) { + initConfig(serviceConfig); + initProtocols(serviceConfig); + } + + private void initReferenceConfig(ReferenceConfig referenceConfig) { + initConfig(referenceConfig); + } + + private void initConfig(AbstractInterfaceConfig config) { + initApplication(config); + initRegistries(config); + } + + private void initApplication(AbstractInterfaceConfig config) { + if (config.getApplication() == null) { + config.setApplication(applicationConfig); + } + } + + private void initRegistries(AbstractInterfaceConfig config) { + List registries = config.getRegistries(); + if (CollectionUtils.isEmpty(registries)) { // If no registry present + registries = new LinkedList<>(); + String registerIds = config.getRegistryIds(); + if (!isBlank(registerIds)) { + for (String id : split(registerIds, ',')) { + RegistryConfig registryConfig = registryConfigs.get(trim(id)); + registries.add(registryConfig); + } + } + if (registries.isEmpty()) { // If empty, add all global registries + registries.addAll(registryConfigs.values()); + } + + config.setRegistries(registries); + } + } + + private void initProtocols(ServiceConfig serviceConfig) { + List protocols = serviceConfig.getProtocols(); + if (CollectionUtils.isEmpty(protocols)) { // If no protocols present + protocols = new LinkedList<>(); + String protocolIds = serviceConfig.getProtocolIds(); + if (!isBlank(protocolIds)) { + for (String id : split(protocolIds, ',')) { + ProtocolConfig protocol = protocolConfigs.get(trim(id)); + protocols.add(protocol); + } + } + if (protocols.isEmpty()) { // If empty, add all global protocols + protocols.addAll(protocolConfigs.values()); + } + serviceConfig.setProtocols(protocols); + } + } + + private void exportServiceConfig(ServiceConfig serviceConfig) { + serviceConfig.export(); + } + + private void registerServiceInstance(List exportedURLs) { + + exportedURLs + .stream() + .findFirst() + .ifPresent(url -> { + String serviceName = url.getParameter(APPLICATION_KEY); + String host = url.getHost(); + int port = url.getPort(); + + ServiceInstance serviceInstance = initServiceInstance(serviceName, host, port); + + getServiceDiscoveries().forEach(serviceDiscovery -> serviceDiscovery.register(serviceInstance)); + + }); + } + + private void unregisterServiceInstance() { + + if (serviceInstance != null) { + getServiceDiscoveries().forEach(serviceDiscovery -> { + serviceDiscovery.unregister(serviceInstance); + }); + } + + } + + private ServiceInstance initServiceInstance(String serviceName, String host, int port) { + this.serviceInstance = new DefaultServiceInstance(serviceName, host, port); + return this.serviceInstance; + } + + private void destroy() { + + destroyProtocolConfigs(); + + destroyReferenceConfigs(); + + DubboShutdownHook.getDubboShutdownHook().doDestroy(); + } + + private void destroyProtocolConfigs() { + protocolConfigs.values().forEach(ProtocolConfig::destroy); + if (logger.isDebugEnabled()) { + logger.debug(NAME + "'s all ProtocolConfigs have been destroyed."); + } + } + + private void destroyReferenceConfigs() { + referenceConfigs.values().forEach(ReferenceConfig::destroy); + if (logger.isDebugEnabled()) { + logger.debug(NAME + "'s all ReferenceConfigs have been destroyed."); + } + } + + private void clear() { + + clearBuilders(); + + clearConfigs(); + + ConfigManager.getInstance().clear(); + } + + private void clearConfigs() { + this.applicationConfig = null; + this.registryConfigs.clear(); + this.protocolConfigs.clear(); + this.serviceConfigs.clear(); + this.referenceConfigs.clear(); + if (logger.isDebugEnabled()) { + logger.debug(NAME + "'s configs have been clear."); + } + } + + private void clearBuilders() { + this.applicationBuilder = null; + this.registryBuilders.clear(); + this.protocolBuilders.clear(); + this.serviceBuilders.clear(); + this.referenceBuilders.clear(); + if (logger.isDebugEnabled()) { + logger.debug(NAME + "'s builders have been clear."); + } + } + + private void release() { + executeMutually(() -> { + while (awaited.compareAndSet(false, true)) { + if (logger.isInfoEnabled()) { + logger.info(NAME + " is about to shutdown..."); + } + condition.signalAll(); + } + }); + } + + private void shutdown() { + if (!executorService.isShutdown()) { + // Shutdown executorService + executorService.shutdown(); + } + } + + private void executeMutually(Runnable runnable) { + try { + lock.lock(); + runnable.run(); + } finally { + lock.unlock(); + } + } + + private static Map buildConfigs(Map map) { + Map configs = new HashMap<>(); + map.entrySet().forEach(entry -> { + configs.put(entry.getKey(), (C) entry.getValue().build()); + }); + return configs; } } diff --git a/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/ProtocolSettings.java b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/ProtocolSettings.java new file mode 100644 index 00000000000..dc0169b4e2a --- /dev/null +++ b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/ProtocolSettings.java @@ -0,0 +1,215 @@ +/* + * 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.bootstrap; + +import org.apache.dubbo.config.ProtocolConfig; +import org.apache.dubbo.config.builders.ProtocolBuilder; + +import java.util.Map; + +/** + * The settings of {@link ProtocolConfig protcol} + * + * @see ProtocolBuilder + * @since 2.7.3 + */ +public class ProtocolSettings extends AbstractSettings { + + private final ProtocolBuilder builder; + + public ProtocolSettings(ProtocolBuilder builder, DubboBootstrap dubboBootstrap) { + super(dubboBootstrap); + this.builder = builder; + } + + public ProtocolSettings name(String name) { + builder.name(name); + return this; + } + + public ProtocolSettings host(String host) { + builder.host(host); + return this; + } + + public ProtocolSettings port(Integer port) { + builder.port(port); + return this; + } + + public ProtocolSettings contextpath(String contextpath) { + builder.contextpath(contextpath); + return this; + } + + @Deprecated + public ProtocolSettings path(String path) { + builder.path(path); + return this; + } + + public ProtocolSettings threadpool(String threadpool) { + builder.threadpool(threadpool); + return this; + } + + public ProtocolSettings corethreads(Integer corethreads) { + builder.corethreads(corethreads); + return this; + } + + public ProtocolSettings threads(Integer threads) { + builder.threads(threads); + return this; + } + + public ProtocolSettings iothreads(Integer iothreads) { + builder.iothreads(iothreads); + return this; + } + + public ProtocolSettings queues(Integer queues) { + builder.queues(queues); + return this; + } + + public ProtocolSettings accepts(Integer accepts) { + builder.accepts(accepts); + return this; + } + + public ProtocolSettings codec(String codec) { + builder.codec(codec); + return this; + } + + public ProtocolSettings serialization(String serialization) { + builder.serialization(serialization); + return this; + } + + public ProtocolSettings charset(String charset) { + builder.charset(charset); + return this; + } + + public ProtocolSettings payload(Integer payload) { + builder.payload(payload); + return this; + } + + public ProtocolSettings buffer(Integer buffer) { + builder.buffer(buffer); + return this; + } + + public ProtocolSettings heartbeat(Integer heartbeat) { + builder.heartbeat(heartbeat); + return this; + } + + public ProtocolSettings accesslog(String accesslog) { + builder.accesslog(accesslog); + return this; + } + + public ProtocolSettings transporter(String transporter) { + builder.transporter(transporter); + return this; + } + + public ProtocolSettings exchanger(String exchanger) { + builder.exchanger(exchanger); + return this; + } + + public ProtocolSettings dispatcher(String dispatcher) { + builder.dispatcher(dispatcher); + return this; + } + + @Deprecated + public ProtocolSettings dispather(String dispather) { + builder.dispather(dispather); + return this; + } + + public ProtocolSettings networker(String networker) { + builder.networker(networker); + return this; + } + + public ProtocolSettings server(String server) { + builder.server(server); + return this; + } + + public ProtocolSettings client(String client) { + builder.client(client); + return this; + } + + public ProtocolSettings telnet(String telnet) { + builder.telnet(telnet); + return this; + } + + public ProtocolSettings prompt(String prompt) { + builder.prompt(prompt); + return this; + } + + public ProtocolSettings status(String status) { + builder.status(status); + return this; + } + + public ProtocolSettings register(Boolean register) { + builder.register(register); + return this; + } + + public ProtocolSettings keepAlive(Boolean keepAlive) { + builder.keepAlive(keepAlive); + return this; + } + + public ProtocolSettings optimizer(String optimizer) { + builder.optimizer(optimizer); + return this; + } + + public ProtocolSettings extension(String extension) { + builder.extension(extension); + return this; + } + + public ProtocolSettings appendParameter(String key, String value) { + builder.appendParameter(key, value); + return this; + } + + public ProtocolSettings appendParameters(Map appendParameters) { + builder.appendParameters(appendParameters); + return this; + } + + public ProtocolSettings isDefault(Boolean isDefault) { + builder.isDefault(isDefault); + return this; + } +} diff --git a/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/ReferenceSettings.java b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/ReferenceSettings.java new file mode 100644 index 00000000000..b38ae053554 --- /dev/null +++ b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/ReferenceSettings.java @@ -0,0 +1,334 @@ +/* + * 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.bootstrap; + +import org.apache.dubbo.config.ApplicationConfig; +import org.apache.dubbo.config.ConfigCenterConfig; +import org.apache.dubbo.config.ConsumerConfig; +import org.apache.dubbo.config.MetadataReportConfig; +import org.apache.dubbo.config.MethodConfig; +import org.apache.dubbo.config.ModuleConfig; +import org.apache.dubbo.config.MonitorConfig; +import org.apache.dubbo.config.ReferenceConfig; +import org.apache.dubbo.config.RegistryConfig; +import org.apache.dubbo.config.builders.ReferenceBuilder; + +import java.util.List; +import java.util.Map; + +/** + * The settings of {@link ReferenceConfig} + * + * @since 2.7.3 + */ +public class ReferenceSettings extends AbstractSettings { + + private final ReferenceBuilder builder; + + public ReferenceSettings(ReferenceBuilder builder, DubboBootstrap dubboBootstrap) { + super(dubboBootstrap); + this.builder = builder; + } + + public ReferenceSettings interfaceName(String interfaceName) { + builder.interfaceName(interfaceName); + return this; + } + + public ReferenceSettings interfaceClass(Class interfaceClass) { + builder.interfaceClass(interfaceClass); + return this; + } + + public ReferenceSettings client(String client) { + builder.client(client); + return this; + } + + public ReferenceSettings url(String url) { + builder.url(url); + return this; + } + + public ReferenceSettings addMethods(List methods) { + builder.addMethods(methods); + return this; + } + + public ReferenceSettings addMethod(MethodConfig method) { + builder.addMethod(method); + return this; + } + + public ReferenceSettings consumer(ConsumerConfig consumer) { + builder.consumer(consumer); + return this; + } + + public ReferenceSettings protocol(String protocol) { + builder.protocol(protocol); + return this; + } + + public ReferenceSettings check(Boolean check) { + builder.check(check); + return this; + } + + public ReferenceSettings init(Boolean init) { + builder.init(init); + return this; + } + + public ReferenceSettings generic(String generic) { + builder.generic(generic); + return this; + } + + public ReferenceSettings generic(Boolean generic) { + builder.generic(generic); + return this; + } + + @Deprecated + public ReferenceSettings injvm(Boolean injvm) { + builder.injvm(injvm); + return this; + } + + public ReferenceSettings lazy(Boolean lazy) { + builder.lazy(lazy); + return this; + } + + public ReferenceSettings reconnect(String reconnect) { + builder.reconnect(reconnect); + return this; + } + + public ReferenceSettings sticky(Boolean sticky) { + builder.sticky(sticky); + return this; + } + + public ReferenceSettings version(String version) { + builder.version(version); + return this; + } + + public ReferenceSettings group(String group) { + builder.group(group); + return this; + } + + @Deprecated + public ReferenceSettings local(String local) { + builder.local(local); + return this; + } + + @Deprecated + public ReferenceSettings local(Boolean local) { + builder.local(local); + return this; + } + + public ReferenceSettings stub(String stub) { + builder.stub(stub); + return this; + } + + public ReferenceSettings stub(Boolean stub) { + builder.stub(stub); + return this; + } + + public ReferenceSettings monitor(MonitorConfig monitor) { + builder.monitor(monitor); + return this; + } + + public ReferenceSettings monitor(String monitor) { + builder.monitor(monitor); + return this; + } + + public ReferenceSettings proxy(String proxy) { + builder.proxy(proxy); + return this; + } + + public ReferenceSettings cluster(String cluster) { + builder.cluster(cluster); + return this; + } + + public ReferenceSettings filter(String filter) { + builder.filter(filter); + return this; + } + + public ReferenceSettings listener(String listener) { + builder.listener(listener); + return this; + } + + public ReferenceSettings owner(String owner) { + builder.owner(owner); + return this; + } + + public ReferenceSettings connections(Integer connections) { + builder.connections(connections); + return this; + } + + public ReferenceSettings layer(String layer) { + builder.layer(layer); + return this; + } + + public ReferenceSettings application(ApplicationConfig application) { + builder.application(application); + return this; + } + + public ReferenceSettings module(ModuleConfig module) { + builder.module(module); + return this; + } + + public ReferenceSettings addRegistries(List registries) { + builder.addRegistries(registries); + return this; + } + + public ReferenceSettings addRegistry(RegistryConfig registry) { + builder.addRegistry(registry); + return this; + } + + public ReferenceSettings registryIds(String registryIds) { + builder.registryIds(registryIds); + return this; + } + + public ReferenceSettings onconnect(String onconnect) { + builder.onconnect(onconnect); + return this; + } + + public ReferenceSettings ondisconnect(String ondisconnect) { + builder.ondisconnect(ondisconnect); + return this; + } + + public ReferenceSettings metadataReportConfig(MetadataReportConfig metadataReportConfig) { + builder.metadataReportConfig(metadataReportConfig); + return this; + } + + public ReferenceSettings configCenter(ConfigCenterConfig configCenter) { + builder.configCenter(configCenter); + return this; + } + + public ReferenceSettings callbacks(Integer callbacks) { + builder.callbacks(callbacks); + return this; + } + + public ReferenceSettings scope(String scope) { + builder.scope(scope); + return this; + } + + public ReferenceSettings tag(String tag) { + builder.tag(tag); + return this; + } + + public ReferenceSettings timeout(Integer timeout) { + builder.timeout(timeout); + return this; + } + + public ReferenceSettings retries(Integer retries) { + builder.retries(retries); + return this; + } + + public ReferenceSettings actives(Integer actives) { + builder.actives(actives); + return this; + } + + public ReferenceSettings loadbalance(String loadbalance) { + builder.loadbalance(loadbalance); + return this; + } + + public ReferenceSettings async(Boolean async) { + builder.async(async); + return this; + } + + public ReferenceSettings sent(Boolean sent) { + builder.sent(sent); + return this; + } + + public ReferenceSettings mock(String mock) { + builder.mock(mock); + return this; + } + + public ReferenceSettings mock(Boolean mock) { + builder.mock(mock); + return this; + } + + public ReferenceSettings merger(String merger) { + builder.merger(merger); + return this; + } + + public ReferenceSettings cache(String cache) { + builder.cache(cache); + return this; + } + + public ReferenceSettings validation(String validation) { + builder.validation(validation); + return this; + } + + public ReferenceSettings appendParameters(Map appendParameters) { + builder.appendParameters(appendParameters); + return this; + } + + public ReferenceSettings appendParameter(String key, String value) { + builder.appendParameter(key, value); + return this; + } + + public ReferenceSettings forks(Integer forks) { + builder.forks(forks); + return this; + } +} diff --git a/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/RegistrySettings.java b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/RegistrySettings.java new file mode 100644 index 00000000000..40331ae4dbc --- /dev/null +++ b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/RegistrySettings.java @@ -0,0 +1,164 @@ +/* + * 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.bootstrap; + +import org.apache.dubbo.config.RegistryConfig; +import org.apache.dubbo.config.builders.RegistryBuilder; + +import java.util.Map; + +/** + * The settings of {@link RegistryConfig} + * + * @since 2.7.3 + */ +public class RegistrySettings extends AbstractSettings { + + private final RegistryBuilder builder; + + public RegistrySettings(RegistryBuilder builder, DubboBootstrap dubboBootstrap) { + super(dubboBootstrap); + this.builder = builder; + } + + public RegistrySettings address(String address) { + builder.address(address); + return this; + } + + public RegistrySettings username(String username) { + builder.username(username); + return this; + } + + public RegistrySettings password(String password) { + builder.password(password); + return this; + } + + public RegistrySettings port(Integer port) { + builder.port(port); + return this; + } + + public RegistrySettings protocol(String protocol) { + builder.protocol(protocol); + return this; + } + + public RegistrySettings transporter(String transporter) { + builder.transporter(transporter); + return this; + } + + @Deprecated + public RegistrySettings transport(String transport) { + builder.transport(transport); + return this; + } + + public RegistrySettings server(String server) { + builder.server(server); + return this; + } + + public RegistrySettings client(String client) { + builder.client(client); + return this; + } + + public RegistrySettings cluster(String cluster) { + builder.cluster(cluster); + return this; + } + + public RegistrySettings group(String group) { + builder.group(group); + return this; + } + + public RegistrySettings version(String version) { + builder.version(version); + return this; + } + + public RegistrySettings timeout(Integer timeout) { + builder.timeout(timeout); + return this; + } + + public RegistrySettings session(Integer session) { + builder.session(session); + return this; + } + + public RegistrySettings file(String file) { + builder.file(file); + return this; + } + + @Deprecated + public RegistrySettings wait(Integer wait) { + builder.wait(wait); + return this; + } + + public RegistrySettings isCheck(Boolean check) { + builder.isCheck(check); + return this; + } + + public RegistrySettings isDynamic(Boolean dynamic) { + builder.isDynamic(dynamic); + return this; + } + + public RegistrySettings register(Boolean register) { + builder.register(register); + return this; + } + + public RegistrySettings subscribe(Boolean subscribe) { + builder.subscribe(subscribe); + return this; + } + + public RegistrySettings appendParameter(String key, String value) { + builder.appendParameter(key, value); + return this; + } + + public RegistrySettings appendParameters(Map appendParameters) { + builder.appendParameters(appendParameters); + return this; + } + + public RegistrySettings isDefault(Boolean isDefault) { + builder.isDefault(isDefault); + return this; + } + + public RegistrySettings simplified(Boolean simplified) { + builder.simplified(simplified); + return this; + } + + public RegistrySettings extraKeys(String extraKeys) { + builder.extraKeys(extraKeys); + return this; + } +} diff --git a/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/ServiceSettings.java b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/ServiceSettings.java new file mode 100644 index 00000000000..314482e0e2a --- /dev/null +++ b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/ServiceSettings.java @@ -0,0 +1,384 @@ +/* + * 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.bootstrap; + +import org.apache.dubbo.config.ApplicationConfig; +import org.apache.dubbo.config.ConfigCenterConfig; +import org.apache.dubbo.config.MetadataReportConfig; +import org.apache.dubbo.config.MethodConfig; +import org.apache.dubbo.config.ModuleConfig; +import org.apache.dubbo.config.MonitorConfig; +import org.apache.dubbo.config.ProtocolConfig; +import org.apache.dubbo.config.ProviderConfig; +import org.apache.dubbo.config.RegistryConfig; +import org.apache.dubbo.config.ServiceConfig; +import org.apache.dubbo.config.builders.ServiceBuilder; + +import java.util.List; +import java.util.Map; + +/** + * The settings of {@link ServiceConfig Dubbo service} + * + * @since 2.7.3 + */ +public class ServiceSettings extends AbstractSettings { + + private final ServiceBuilder builder; + + public ServiceSettings(ServiceBuilder builder, DubboBootstrap dubboBootstrap) { + super(dubboBootstrap); + this.builder = builder; + } + + public ServiceSettings interfaceName(String interfaceName) { + builder.interfaceName(interfaceName); + return this; + } + + public ServiceSettings interfaceClass(Class interfaceClass) { + builder.interfaceClass(interfaceClass); + return this; + } + + public ServiceSettings ref(S ref) { + builder.ref(ref); + return this; + } + + public ServiceSettings path(String path) { + builder.path(path); + return this; + } + + public ServiceSettings addMethod(MethodConfig method) { + builder.addMethod(method); + return this; + } + + public ServiceSettings addMethods(List methods) { + builder.addMethods(methods); + return this; + } + + public ServiceSettings provider(ProviderConfig provider) { + builder.provider(provider); + return this; + } + + public ServiceSettings providerIds(String providerIds) { + builder.providerIds(providerIds); + return this; + } + + public ServiceSettings generic(String generic) { + builder.generic(generic); + return this; + } + + public ServiceSettings mock(String mock) { + builder.mock(mock); + return this; + } + + public ServiceSettings mock(Boolean mock) { + builder.mock(mock); + return this; + } + + public ServiceSettings version(String version) { + builder.version(version); + return this; + } + + public ServiceSettings group(String group) { + builder.group(group); + return this; + } + + public ServiceSettings deprecated(Boolean deprecated) { + builder.deprecated(deprecated); + return this; + } + + public ServiceSettings delay(Integer delay) { + builder.delay(delay); + return this; + } + + public ServiceSettings export(Boolean export) { + builder.export(export); + return this; + } + + public ServiceSettings weight(Integer weight) { + builder.weight(weight); + return this; + } + + public ServiceSettings document(String document) { + builder.document(document); + return this; + } + + public ServiceSettings dynamic(Boolean dynamic) { + builder.dynamic(dynamic); + return this; + } + + public ServiceSettings token(String token) { + builder.token(token); + return this; + } + + public ServiceSettings token(Boolean token) { + builder.token(token); + return this; + } + + public ServiceSettings accesslog(String accesslog) { + builder.accesslog(accesslog); + return this; + } + + public ServiceSettings accesslog(Boolean accesslog) { + builder.accesslog(accesslog); + return this; + } + + public ServiceSettings addProtocols(List protocols) { + builder.addProtocols(protocols); + return this; + } + + public ServiceSettings addProtocol(ProtocolConfig protocol) { + builder.addProtocol(protocol); + return this; + } + + public ServiceSettings protocolIds(String protocolIds) { + builder.protocolIds(protocolIds); + return this; + } + + public ServiceSettings executes(Integer executes) { + builder.executes(executes); + return this; + } + + public ServiceSettings register(Boolean register) { + builder.register(register); + return this; + } + + public ServiceSettings warmup(Integer warmup) { + builder.warmup(warmup); + return this; + } + + public ServiceSettings serialization(String serialization) { + builder.serialization(serialization); + return this; + } + + @Deprecated + public ServiceSettings local(String local) { + builder.local(local); + return this; + } + + @Deprecated + public ServiceSettings local(Boolean local) { + builder.local(local); + return this; + } + + public ServiceSettings stub(String stub) { + builder.stub(stub); + return this; + } + + public ServiceSettings stub(Boolean stub) { + builder.stub(stub); + return this; + } + + public ServiceSettings monitor(MonitorConfig monitor) { + builder.monitor(monitor); + return this; + } + + public ServiceSettings monitor(String monitor) { + builder.monitor(monitor); + return this; + } + + public ServiceSettings proxy(String proxy) { + builder.proxy(proxy); + return this; + } + + public ServiceSettings cluster(String cluster) { + builder.cluster(cluster); + return this; + } + + public ServiceSettings filter(String filter) { + builder.filter(filter); + return this; + } + + public ServiceSettings listener(String listener) { + builder.listener(listener); + return this; + } + + public ServiceSettings owner(String owner) { + builder.owner(owner); + return this; + } + + public ServiceSettings connections(Integer connections) { + builder.connections(connections); + return this; + } + + public ServiceSettings layer(String layer) { + builder.layer(layer); + return this; + } + + public ServiceSettings application(ApplicationConfig application) { + builder.application(application); + return this; + } + + public ServiceSettings module(ModuleConfig module) { + builder.module(module); + return this; + } + + public ServiceSettings addRegistries(List registries) { + builder.addRegistries(registries); + return this; + } + + public ServiceSettings addRegistry(RegistryConfig registry) { + builder.addRegistry(registry); + return this; + } + + public ServiceSettings registryIds(String registryIds) { + builder.registryIds(registryIds); + return this; + } + + public ServiceSettings onconnect(String onconnect) { + builder.onconnect(onconnect); + return this; + } + + public ServiceSettings ondisconnect(String ondisconnect) { + builder.ondisconnect(ondisconnect); + return this; + } + + public ServiceSettings metadataReportConfig(MetadataReportConfig metadataReportConfig) { + builder.metadataReportConfig(metadataReportConfig); + return this; + } + + public ServiceSettings configCenter(ConfigCenterConfig configCenter) { + builder.configCenter(configCenter); + return this; + } + + public ServiceSettings callbacks(Integer callbacks) { + builder.callbacks(callbacks); + return this; + } + + public ServiceSettings scope(String scope) { + builder.scope(scope); + return this; + } + + public ServiceSettings tag(String tag) { + builder.tag(tag); + return this; + } + + public ServiceSettings timeout(Integer timeout) { + builder.timeout(timeout); + return this; + } + + public ServiceSettings retries(Integer retries) { + builder.retries(retries); + return this; + } + + public ServiceSettings actives(Integer actives) { + builder.actives(actives); + return this; + } + + public ServiceSettings loadbalance(String loadbalance) { + builder.loadbalance(loadbalance); + return this; + } + + public ServiceSettings async(Boolean async) { + builder.async(async); + return this; + } + + public ServiceSettings sent(Boolean sent) { + builder.sent(sent); + return this; + } + + public ServiceSettings merger(String merger) { + builder.merger(merger); + return this; + } + + public ServiceSettings cache(String cache) { + builder.cache(cache); + return this; + } + + public ServiceSettings validation(String validation) { + builder.validation(validation); + return this; + } + + public ServiceSettings appendParameters(Map appendParameters) { + builder.appendParameters(appendParameters); + return this; + } + + public ServiceSettings appendParameter(String key, String value) { + builder.appendParameter(key, value); + return this; + } + + public ServiceSettings forks(Integer forks) { + builder.forks(forks); + return this; + } +} diff --git a/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/Settings.java b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/Settings.java new file mode 100644 index 00000000000..abf814184b8 --- /dev/null +++ b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/Settings.java @@ -0,0 +1,32 @@ +/* + * 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.bootstrap; + +/** + * The Dubbo settings + * + * @since 2.7.3 + */ +public interface Settings { + + /** + * Go next settings + * + * @return {@link DubboBootstrap} + */ + DubboBootstrap next(); +} diff --git a/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboBootstrapTest.java b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboBootstrapTest.java new file mode 100644 index 00000000000..33344e2e102 --- /dev/null +++ b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboBootstrapTest.java @@ -0,0 +1,54 @@ +/* + * 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.bootstrap; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +/** + * {@link DubboBootstrap} Test + * + * @since 2.7.3 + */ +public class DubboBootstrapTest { + + @Test + public void test() throws IOException { + + DubboBootstrap bootstrap = new DubboBootstrap() + .application("dubbo-provider-demo") + .next() + .registry() + .address("zookeeper://127.0.0.1:2181?registry-type=service") + .next() + .protocol() + .name("dubbo") + .port(-1) + .next() + .service("test") + .interfaceClass(EchoService.class) + .ref(new EchoServiceImpl()) + .group("DEFAULT") + .version("1.0.0") + .next(); + + bootstrap.start(); + + System.in.read(); + } +} diff --git a/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceConsumerBootstrap.java b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceConsumerBootstrap.java new file mode 100644 index 00000000000..b9f677ea380 --- /dev/null +++ b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceConsumerBootstrap.java @@ -0,0 +1,58 @@ +/* + * 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.bootstrap; + +import org.apache.dubbo.config.ReferenceConfig; + +import static org.apache.dubbo.bootstrap.EchoService.GROUP; +import static org.apache.dubbo.bootstrap.EchoService.VERSION; + +/** + * Dubbo Provider Bootstrap + * + * @since 2.7.3 + */ +public class DubboServiceConsumerBootstrap { + + public static void main(String[] args) throws Exception { + + DubboBootstrap bootstrap = new DubboBootstrap() + .application("dubbo-consumer-demo") + .next() + .registry() + .address("zookeeper://127.0.0.1:2181?registry-type=service") + .next() + .reference("ref") + .interfaceClass(EchoService.class) + .group(GROUP) + .version(VERSION) + .next() + .onlyRegisterProvider(true) + .start() + .await(); + + ReferenceConfig referenceConfig = bootstrap.referenceConfig("ref"); + + EchoService echoService = referenceConfig.get(); + + for (int i = 0; i < 500; i++) { + Thread.sleep(2000L); + System.out.println(echoService.echo("Hello,World")); + } + + } +} diff --git a/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceProviderBootstrap.java b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceProviderBootstrap.java new file mode 100644 index 00000000000..049cae84a39 --- /dev/null +++ b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceProviderBootstrap.java @@ -0,0 +1,52 @@ +/* + * 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.bootstrap; + +import java.io.IOException; + +import static org.apache.dubbo.bootstrap.EchoService.GROUP; +import static org.apache.dubbo.bootstrap.EchoService.VERSION; + +/** + * Dubbo Provider Bootstrap + * + * @since 2.7.3 + */ +public class DubboServiceProviderBootstrap { + + public static void main(String[] args) throws IOException { + + new DubboBootstrap() + .application("dubbo-provider-demo") + .next() + .registry() + .address("zookeeper://127.0.0.1:2181?registry-type=service") + .next() + .protocol() + .name("dubbo") + .port(-1) + .next() + .service("test") + .interfaceClass(EchoService.class) + .ref(new EchoServiceImpl()) + .group(GROUP) + .version(VERSION) + .next() + .start() + .await(); + } +} diff --git a/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/EchoService.java b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/EchoService.java new file mode 100644 index 00000000000..7ad86984526 --- /dev/null +++ b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/EchoService.java @@ -0,0 +1,31 @@ +/* + * 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.bootstrap; + +/** + * Echo Service + * + * @since 2.7.3 + */ +public interface EchoService { + + String GROUP = "DEFAULT"; + + String VERSION = "1.0.0"; + + String echo(String message); +} diff --git a/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/EchoServiceImpl.java b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/EchoServiceImpl.java new file mode 100644 index 00000000000..e0218b1e22b --- /dev/null +++ b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/EchoServiceImpl.java @@ -0,0 +1,36 @@ +/* + * 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.bootstrap; + +import org.apache.dubbo.rpc.RpcContext; + +import static java.lang.String.format; + +/** + * The implementation of {@link EchoService} + * + * @see EchoService + * @since 2.7.3 + */ +public class EchoServiceImpl implements EchoService { + + @Override + public String echo(String message) { + RpcContext rpcContext = RpcContext.getContext(); + return format("[%s:%s] ECHO - %s", rpcContext.getLocalHost(), rpcContext.getLocalPort(), message); + } +} diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/AbstractBuilder.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/AbstractBuilder.java index d1e33c607ba..12d09bf05cf 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/AbstractBuilder.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/AbstractBuilder.java @@ -25,9 +25,11 @@ /** * AbstractBuilder * + * @param The type of {@link AbstractConfig Config} + * @param The type of {@link AbstractBuilder Builder} * @since 2.7 */ -public abstract class AbstractBuilder { +public abstract class AbstractBuilder { /** * The config id */ @@ -62,7 +64,7 @@ protected static Map appendParameters(Map parame return parameters; } - protected void build(T instance) { + protected void build(C instance) { if (!StringUtils.isEmpty(id)) { instance.setId(id); } @@ -70,4 +72,11 @@ protected void build(T instance) { instance.setPrefix(prefix); } } + + /** + * Build an instance of {@link AbstractConfig config} + * + * @return an instance of {@link AbstractConfig config} + */ + public abstract C build(); } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ProtocolBuilder.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ProtocolBuilder.java index 42e55503ea7..4ddd943e903 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ProtocolBuilder.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ProtocolBuilder.java @@ -185,6 +185,10 @@ public class ProtocolBuilder extends AbstractBuilder extends AbstractReferenceBuilder id(String id) { + return super.id(id); + } + public ReferenceBuilder interfaceName(String interfaceName) { this.interfaceName = interfaceName; return getThis(); diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/RegistryBuilder.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/RegistryBuilder.java index f64e595f37d..616e6af09a5 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/RegistryBuilder.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/RegistryBuilder.java @@ -16,10 +16,10 @@ */ package org.apache.dubbo.config.builders; -import java.util.Map; - import org.apache.dubbo.config.RegistryConfig; +import java.util.Map; + /** * This is a builder for build {@link RegistryConfig}. * @@ -134,6 +134,10 @@ public class RegistryBuilder extends AbstractBuilder extends AbstractServiceBuilder interfaceName(String interfaceName) { this.interfaceName = interfaceName; return getThis(); diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java index b91be42a73b..ac36f9e477d 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java @@ -29,9 +29,11 @@ import org.apache.dubbo.metadata.MetadataService; import org.apache.dubbo.metadata.MetadataServiceExporter; -import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedList; import java.util.List; -import java.util.Map; + +import static java.util.Collections.unmodifiableList; /** * {@link MetadataServiceExporter} implementation based on {@link AbstractConfig Dubbo configurations}, the clients @@ -50,13 +52,28 @@ public class ConfigurableMetadataServiceExporter implements MetadataServiceExpor private final Logger logger = LoggerFactory.getLogger(getClass()); - /** - * {@link ConfigManager} stores {@link AbstractConfig the Dubbo *Config instances} - */ - private final ConfigManager configManager = ConfigManager.getInstance(); - private volatile ServiceConfig serviceConfig; + private ApplicationConfig applicationConfig; + + private List registries = new LinkedList<>(); + + private List protocols = new LinkedList<>(); + + public void setApplicationConfig(ApplicationConfig applicationConfig) { + this.applicationConfig = applicationConfig; + } + + public void setRegistries(Collection registries) { + this.registries.clear(); + this.registries.addAll(registries); + } + + public void setProtocols(Collection protocols) { + this.protocols.clear(); + this.protocols.addAll(protocols); + } + @Override public List export() { @@ -65,9 +82,9 @@ public List export() { LocalMetadataService metadataService = LocalMetadataService.getDefaultExtension(); ServiceConfig serviceConfig = new ServiceConfig<>(); - serviceConfig.setApplication(getApplicationConfig()); - serviceConfig.setRegistries(getRegistries()); - serviceConfig.setProtocols(getProtocols()); + serviceConfig.setApplication(applicationConfig); + serviceConfig.setRegistries(registries); + serviceConfig.setProtocols(protocols); serviceConfig.setInterface(MetadataService.class); serviceConfig.setRef(metadataService); serviceConfig.setGroup(getApplicationConfig().getName()); @@ -96,20 +113,16 @@ public void unexport() { } } - private List list(Map map) { - return new ArrayList<>(map.values()); - } - - private List getProtocols() { - return list(configManager.getProtocols()); + private List getProtocols() { + return unmodifiableList(protocols); } - private List getRegistries() { - return list(configManager.getRegistries()); + private List getRegistries() { + return unmodifiableList(registries); } private ApplicationConfig getApplicationConfig() { - return configManager.getApplication().get(); + return applicationConfig; } private boolean isExported() { diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ServiceInstancePortCustomizer.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ServiceInstancePortCustomizer.java index 61653ff7a8e..c9ef9b9f1c9 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ServiceInstancePortCustomizer.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ServiceInstancePortCustomizer.java @@ -31,7 +31,7 @@ public class ServiceInstancePortCustomizer implements ServiceInstanceCustomizer @Override public void customize(ServiceInstance serviceInstance) { - if (serviceInstance.getPort() == null + if (serviceInstance.getPort() != null || serviceInstance.getPort().intValue() < 1) { return; } @@ -44,7 +44,9 @@ public void customize(ServiceInstance serviceInstance) { .ifPresent(protocolConfig -> { if (serviceInstance instanceof DefaultServiceInstance) { DefaultServiceInstance instance = (DefaultServiceInstance) serviceInstance; - instance.setPort(protocolConfig.getPort()); + if (protocolConfig.getPort() != null) { + instance.setPort(protocolConfig.getPort()); + } } }); } diff --git a/dubbo-config/dubbo-config-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.MetadataServiceExporter b/dubbo-config/dubbo-config-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.MetadataServiceExporter deleted file mode 100644 index 30626fd41fc..00000000000 --- a/dubbo-config/dubbo-config-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.MetadataServiceExporter +++ /dev/null @@ -1 +0,0 @@ -default=org.apache.dubbo.config.metadata.ConfigurableMetadataServiceExporter \ No newline at end of file diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMapping.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMapping.java index 4c171bf224a..f535a517dad 100644 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMapping.java +++ b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMapping.java @@ -23,8 +23,10 @@ import java.util.Collections; import java.util.LinkedHashSet; +import java.util.List; import java.util.Set; +import static java.util.Arrays.asList; import static org.apache.dubbo.common.utils.StringUtils.isBlank; /** @@ -32,6 +34,8 @@ */ public class DynamicConfigurationServiceNameMapping implements ServiceNameMapping { + private static final List IGNORED_SERVICE_INTERFACES = asList(MetadataService.class.getName()); + private static final String SEPARATOR = ":"; private static final String EMPTY = ""; @@ -41,6 +45,10 @@ public class DynamicConfigurationServiceNameMapping implements ServiceNameMappin @Override public void map(String serviceInterface, String group, String version, String protocol) { + if (IGNORED_SERVICE_INTERFACES.contains(serviceInterface)) { + return; + } + DynamicConfiguration dynamicConfiguration = DynamicConfiguration.getDynamicConfiguration(); // the Dubbo Service Key as group diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java index 535864f7b26..a636d2b4c64 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java @@ -459,4 +459,13 @@ public static ServiceOrientedRegistry create(URL registryURL) { public static boolean supports(URL registryURL) { return SERVICE_REGISTRY_TYPE.equalsIgnoreCase(registryURL.getParameter(REGISTRY_TYPE_KEY)); } + + /** + * Get the instance of {@link ServiceDiscovery} + * + * @return non-null + */ + public ServiceDiscovery getServiceDiscovery() { + return serviceDiscovery; + } } From 7c0eb3d47bd58231842d39a1d52e583d22c3c645 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Fri, 7 Jun 2019 00:54:35 +0800 Subject: [PATCH 32/46] Polish apache/incubator-dubbo#4265 : [Feature] Dubbo Cloud Native - Add Bootstrap --- .../java/org/apache/dubbo/bootstrap/DubboBootstrap.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java index c94febe7e60..47bad6d9fa9 100644 --- a/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java +++ b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java @@ -23,7 +23,6 @@ import org.apache.dubbo.config.AbstractConfig; import org.apache.dubbo.config.AbstractInterfaceConfig; import org.apache.dubbo.config.ApplicationConfig; -import org.apache.dubbo.config.DubboShutdownHook; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.RegistryConfig; @@ -452,9 +451,9 @@ public void onEvent(ServiceDiscoveryStoppedEvent event) { }).addEventListener(new EventListener() { @Override public void onEvent(DubboServiceDestroyedEvent event) { - release(); + stop(); if (logger.isInfoEnabled()) { - logger.info(NAME + " has been shutdown."); + logger.info(NAME + " has been destroyed."); } } }); @@ -610,7 +609,6 @@ private void destroy() { destroyReferenceConfigs(); - DubboShutdownHook.getDubboShutdownHook().doDestroy(); } private void destroyProtocolConfigs() { From 3ac778c8c7351654b1f43be1d7c5094357bb5835 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E9=A9=AC=E5=93=A5?= Date: Fri, 7 Jun 2019 09:02:59 +0800 Subject: [PATCH 33/46] Polish apache/dubbo#4265 : Add test dependencies --- dubbo-bootstrap/pom.xml | 36 +++++++++++++++++++ .../dubbo/config/DubboConsumerBootstrap.java | 8 +++-- .../config/provider/impl/DemoServiceImpl.java | 17 ++++++++- pom.xml | 1 + 4 files changed, 59 insertions(+), 3 deletions(-) diff --git a/dubbo-bootstrap/pom.xml b/dubbo-bootstrap/pom.xml index f30963b8e4b..686ef7d0606 100644 --- a/dubbo-bootstrap/pom.xml +++ b/dubbo-bootstrap/pom.xml @@ -24,6 +24,42 @@ ${project.parent.version} + + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.parent.version} + test + + + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.parent.version} + test + + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.parent.version} + test + + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.parent.version} + test + + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.parent.version} + test + + \ No newline at end of file diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/DubboConsumerBootstrap.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/DubboConsumerBootstrap.java index ff0fa2dfe95..b8239368127 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/DubboConsumerBootstrap.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/DubboConsumerBootstrap.java @@ -27,7 +27,7 @@ */ public class DubboConsumerBootstrap { - public static void main(String[] args) throws IOException { + public static void main(String[] args) throws IOException, InterruptedException { ApplicationConfig application = new ApplicationConfig(); application.setName("dubbo-consumer-demo"); @@ -47,11 +47,15 @@ public static void main(String[] args) throws IOException { reference.setInterface(DemoService.class); reference.setVersion("1.0.0"); reference.setProtocol("dubbo"); + reference.setCheck(false); // 和本地bean一样使用xxxService DemoService demoService1 = reference.get(); - System.out.println(demoService1.sayName("Hello,World")); + for (int i = 0; i < 1000; i++) { + System.out.println(demoService1.sayName("Hello,World")); + Thread.sleep(1000); + } System.in.read(); } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/provider/impl/DemoServiceImpl.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/provider/impl/DemoServiceImpl.java index d81269e963d..1b213281b20 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/provider/impl/DemoServiceImpl.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/provider/impl/DemoServiceImpl.java @@ -16,20 +16,27 @@ */ package org.apache.dubbo.config.provider.impl; +import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.config.api.Box; import org.apache.dubbo.config.api.DemoException; import org.apache.dubbo.config.api.DemoService; import org.apache.dubbo.config.api.User; +import org.apache.dubbo.rpc.RpcContext; import java.util.List; +import static java.lang.String.format; + /** * DemoServiceImpl */ public class DemoServiceImpl implements DemoService { + private final Logger logger = LoggerFactory.getLogger(getClass()); + public String sayName(String name) { - return "say:" + name; + return log("say:" + name); } public Box getBox() { @@ -48,4 +55,12 @@ public int echo(int i) { return i; } + private T log(T object) { + RpcContext rpcContext = RpcContext.getContext(); + logger.info(format("RPC Invocation [ client - %s:%s , provider - %s:%s] : %s", + rpcContext.getRemoteHost(), rpcContext.getRemotePort(), + rpcContext.getLocalHost(), rpcContext.getLocalPort(), + object)); + return object; + } } \ No newline at end of file diff --git a/pom.xml b/pom.xml index e9c11a9f312..084674489c5 100644 --- a/pom.xml +++ b/pom.xml @@ -151,6 +151,7 @@ dubbo-dependencies dubbo-event dubbo-metadata + dubbo-bootstrap From a8526da64892a8bc88bead209d4323f0680d9b5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E9=A9=AC=E5=93=A5?= Date: Fri, 7 Jun 2019 17:33:25 +0800 Subject: [PATCH 34/46] Polish /apache/dubbo#3942 : Refactor implementation --- .../DefaultServiceDiscoveryFactory.java | 74 ------------------- ...ventPublishingServiceDiscoveryFactory.java | 47 ++++++++++++ .../client/ServiceDiscoveryFactory.java | 38 +--------- ...bo.registry.client.ServiceDiscoveryFactory | 2 +- .../InMemoryServiceDiscoveryFactory.java | 5 -- .../client/ServiceDiscoveryFactoryTest.java | 15 +--- ...bo.registry.client.ServiceDiscoveryFactory | 2 +- .../ZookeeperServiceDiscoveryFactory.java | 5 -- ...bo.registry.client.ServiceDiscoveryFactory | 1 + 9 files changed, 55 insertions(+), 134 deletions(-) delete mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceDiscoveryFactory.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceDiscoveryFactory.java create mode 100644 dubbo-registry/dubbo-registry-zookeeper/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscoveryFactory diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceDiscoveryFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceDiscoveryFactory.java deleted file mode 100644 index 2cc6dafdde0..00000000000 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceDiscoveryFactory.java +++ /dev/null @@ -1,74 +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.client; - -import org.apache.dubbo.common.URL; - -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.ServiceLoader; - -import static org.apache.dubbo.common.utils.CollectionUtils.sort; - -/** - * The default implementation of {@link ServiceDiscoveryFactory} as the default extension of - * {@link ServiceDiscoveryFactory}, default elements are loaded by @link ServiceLoader Java SPI} from in different - * artifacts(jars) in the class path. - * - * @see ServiceDiscoveryFactory - * @see ServiceLoader#load(Class) - * @since 2.7.3 - */ -public class DefaultServiceDiscoveryFactory implements ServiceDiscoveryFactory { - - private final List serviceDiscoveryFactories = new LinkedList<>(); - - public DefaultServiceDiscoveryFactory() { - initServiceDiscoveryFactories(); - } - - private void initServiceDiscoveryFactories() { - ServiceLoader serviceLoader = - ServiceLoader.load(ServiceDiscoveryFactory.class, getClass().getClassLoader()); - Iterator iterator = serviceLoader.iterator(); - iterator.forEachRemaining(serviceDiscoveryFactories::add); - sort(serviceDiscoveryFactories); - } - - @Override - public boolean supports(URL connectionURL) { - return serviceDiscoveryFactories - .stream() - .filter(factory -> factory.supports(connectionURL)) - .count() > 0; - } - - @Override - public ServiceDiscovery create(URL connectionURL) { - return serviceDiscoveryFactories - .stream() - .filter(factory -> factory.supports(connectionURL)) - .findFirst() // find the highest priority one - .map(factory -> factory.create(connectionURL)) // create the original instance - .map(serviceDiscovery -> new EventPublishingServiceDiscovery(serviceDiscovery)) // wrap the event-based - .orElseThrow(() -> - new IllegalStateException("The ServiceDiscovery can't be created by the connection URL[" - + connectionURL.toFullString() + "]") // If not found - ); - } -} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceDiscoveryFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceDiscoveryFactory.java new file mode 100644 index 00000000000..dc5a614c7fd --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceDiscoveryFactory.java @@ -0,0 +1,47 @@ +package org.apache.dubbo.registry.client;/* + * 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. + */ + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.extension.SPI; + +import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; + +/** + * The factory class to create an instance of {@link ServiceDiscoveryFactory} based on Event-Publishing as the default + * {@link SPI} implementation + * + * @see ServiceDiscoveryFactory + * @see EventPublishingServiceDiscovery + * @see ServiceDiscovery + * @since 2.7.3 + */ +public class EventPublishingServiceDiscoveryFactory implements ServiceDiscoveryFactory { + + private static final Class FACTORY_CLASS = ServiceDiscoveryFactory.class; + + @Override + public ServiceDiscovery create(URL connectionURL) { + String protocol = connectionURL.getProtocol(); + ServiceDiscoveryFactory serviceDiscoveryFactory = loadFactoryByProtocol(protocol); + ServiceDiscovery originalServiceDiscovery = serviceDiscoveryFactory.create(connectionURL); + return new EventPublishingServiceDiscovery(originalServiceDiscovery); + } + + protected ServiceDiscoveryFactory loadFactoryByProtocol(String protocol) { + return getExtensionLoader(FACTORY_CLASS).getExtension(protocol); + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryFactory.java index 913a3ce6c28..f7e7cefbc1f 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryFactory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryFactory.java @@ -19,7 +19,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.SPI; -import static java.lang.Integer.compare; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; /** @@ -28,46 +27,17 @@ * @see ServiceDiscovery * @since 2.7.3 */ -@SPI("default") -public interface ServiceDiscoveryFactory extends Comparable { +@SPI("event-publishing") +public interface ServiceDiscoveryFactory { /** - * It indicates the current implementation supports or not in the specified {@link URL connnection url}. + * Creates an instance of {@link ServiceDiscovery}. * * @param connectionURL the {@link URL connection url} - * @return if supports, return true, or false - */ - boolean supports(URL connectionURL); - - /** - * Creates an instance of {@link ServiceDiscovery} if {@link #supports(URL)} returns true, - * - * @param connectionURL the {@link URL connection url} - * @return an instance of {@link ServiceDiscovery} if supported, or null + * @return an instance of {@link ServiceDiscovery} */ ServiceDiscovery create(URL connectionURL); - /** - * The priority of current {@link ServiceDiscoveryFactory} - * - * @return The {@link Integer#MIN_VALUE minimum integer} indicates the highest priority, in contrast, - * the lowest priority is {@link Integer#MAX_VALUE the maximum integer} - */ - default int getPriority() { - return Integer.MAX_VALUE; - } - - /** - * Compares its priority - * - * @param that {@link ServiceDiscovery} - * @return - */ - @Override - default int compareTo(ServiceDiscoveryFactory that) { - return compare(this.getPriority(), that.getPriority()); - } - /** * Get the default extension of {@link ServiceDiscoveryFactory} * diff --git a/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscoveryFactory b/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscoveryFactory index d30ea0c1866..20b8e667392 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscoveryFactory +++ b/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscoveryFactory @@ -1 +1 @@ -default=org.apache.dubbo.registry.client.DefaultServiceDiscoveryFactory \ No newline at end of file +event-publishing=org.apache.dubbo.registry.client.EventPublishingServiceDiscoveryFactory \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InMemoryServiceDiscoveryFactory.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InMemoryServiceDiscoveryFactory.java index afab3e6b646..4a4104d38f0 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InMemoryServiceDiscoveryFactory.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InMemoryServiceDiscoveryFactory.java @@ -26,11 +26,6 @@ */ public class InMemoryServiceDiscoveryFactory implements ServiceDiscoveryFactory { - @Override - public boolean supports(URL connectionURL) { - return "in-memory".equalsIgnoreCase(connectionURL.getProtocol()); - } - @Override public ServiceDiscovery create(URL connectionURL) { return new InMemoryServiceDiscovery(); diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryFactoryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryFactoryTest.java index 3030bcb0214..bf9f1db1304 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryFactoryTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryFactoryTest.java @@ -23,8 +23,6 @@ import static org.apache.dubbo.common.URL.valueOf; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link ServiceDiscoveryFactory} Test @@ -46,13 +44,7 @@ public void init() { @Test public void testClass() { - assertEquals(DefaultServiceDiscoveryFactory.class, serviceDiscoveryFactory.getClass()); - } - - @Test - public void testSupports() { - assertFalse(serviceDiscoveryFactory.supports(dubboURL)); - assertTrue(serviceDiscoveryFactory.supports(inMemoryURL)); + assertEquals(EventPublishingServiceDiscoveryFactory.class, serviceDiscoveryFactory.getClass()); } @Test @@ -60,9 +52,4 @@ public void testCreate() { ServiceDiscovery serviceDiscovery = serviceDiscoveryFactory.create(inMemoryURL); assertEquals(EventPublishingServiceDiscovery.class, serviceDiscovery.getClass()); } - - @Test - public void testPriority() { - assertEquals(Integer.MAX_VALUE, serviceDiscoveryFactory.getPriority()); - } } diff --git a/dubbo-registry/dubbo-registry-api/src/test/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceDiscoveryFactory b/dubbo-registry/dubbo-registry-api/src/test/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceDiscoveryFactory index 5dc3c97161d..2a280741612 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceDiscoveryFactory +++ b/dubbo-registry/dubbo-registry-api/src/test/resources/META-INF/services/org.apache.dubbo.registry.client.ServiceDiscoveryFactory @@ -1 +1 @@ -org.apache.dubbo.registry.client.InMemoryServiceDiscoveryFactory \ No newline at end of file +in-memory=org.apache.dubbo.registry.client.InMemoryServiceDiscoveryFactory \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryFactory.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryFactory.java index 6cca1aa87bf..6572e281373 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryFactory.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryFactory.java @@ -28,11 +28,6 @@ */ public class ZookeeperServiceDiscoveryFactory implements ServiceDiscoveryFactory { - @Override - public boolean supports(URL connectionURL) { - return "zookeeper".equalsIgnoreCase(connectionURL.getProtocol()); - } - @Override public ServiceDiscovery create(URL connectionURL) { try { diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscoveryFactory b/dubbo-registry/dubbo-registry-zookeeper/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscoveryFactory new file mode 100644 index 00000000000..12262adad29 --- /dev/null +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscoveryFactory @@ -0,0 +1 @@ +zookeeper=org.apache.dubbo.registry.zookeeper.ZookeeperServiceDiscoveryFactory \ No newline at end of file From 1a3ee8f170dc234fe2cc98037082211c8e9ed5f5 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Sat, 8 Jun 2019 02:44:00 +0800 Subject: [PATCH 35/46] Polish apache/incubator-dubbo#3984 : Refactor --- .../dubbo/common/utils/DefaultPage.java | 35 ++++-- .../org/apache/dubbo/common/utils/Page.java | 22 +++- .../EventPublishingServiceDiscovery.java | 13 +-- .../registry/client/ServiceDiscovery.java | 110 +++++++----------- .../client/InMemoryServiceDiscovery.java | 26 ++++- .../registry/client/ServiceDiscoveryTest.java | 64 +++++----- .../ZookeeperServiceDiscoveryTest.java | 24 ++-- 7 files changed, 158 insertions(+), 136 deletions(-) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DefaultPage.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DefaultPage.java index a1c6d97387b..fd408b57ddc 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DefaultPage.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DefaultPage.java @@ -30,25 +30,34 @@ public class DefaultPage implements Page, Serializable { private final int requestOffset; - private final int requestSize; + private final int pageSize; - private int totalSize; + private final int totalSize; - private List data; + private final List data; - public DefaultPage(int requestOffset, int requestSize) { + private final int totalPages; + + private final boolean hasNext; + + public DefaultPage(int requestOffset, int pageSize, List data, int totalSize) { this.requestOffset = requestOffset; - this.requestSize = requestSize; + this.pageSize = pageSize; + this.data = data; + this.totalSize = totalSize; + int remain = totalSize % pageSize; + this.totalPages = remain > 0 ? (totalSize / pageSize) + 1 : totalSize / pageSize; + this.hasNext = totalSize - requestOffset - pageSize > 0; } @Override - public int getRequestOffset() { + public int getOffset() { return requestOffset; } @Override - public int getRequestSize() { - return requestSize; + public int getPageSize() { + return pageSize; } @Override @@ -56,8 +65,9 @@ public int getTotalSize() { return totalSize; } - public void setTotalSize(int totalSize) { - this.totalSize = totalSize; + @Override + public int getTotalPages() { + return totalPages; } @Override @@ -65,7 +75,8 @@ public List getData() { return data; } - public void setData(List data) { - this.data = data; + @Override + public boolean hasNext() { + return hasNext; } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Page.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Page.java index f899b696834..c15cfb84fdb 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Page.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Page.java @@ -30,22 +30,29 @@ public interface Page { * * @return positive integer */ - int getRequestOffset(); + int getOffset(); /** - * Gets the size of request for query + * Gets the size of request for pagination query * * @return positive integer */ - int getRequestSize(); + int getPageSize(); /** - * Returns the total amount of elements. + * Gets the total amount of elements. * * @return the total amount of elements */ int getTotalSize(); + /** + * Get the number of total pages. + * + * @return the number of total pages. + */ + int getTotalPages(); + /** * The data of current page * @@ -62,6 +69,13 @@ default int getDataSize() { return getData().size(); } + /** + * It indicates has next page or not + * + * @return if has , return true, or false + */ + boolean hasNext(); + /** * Returns whether the page has data at all. * diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceDiscovery.java index 057ae0b42e9..8caaae435db 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceDiscovery.java @@ -193,18 +193,13 @@ public List getInstances(String serviceName) throws NullPointer } @Override - public int getTotalSizeInstances(String serviceName) throws NullPointerException { - return serviceDiscovery.getTotalSizeInstances(serviceName); + public Page getInstances(String serviceName, int offset, int pageSize) throws NullPointerException, IllegalArgumentException { + return serviceDiscovery.getInstances(serviceName, offset, pageSize); } @Override - public Page getInstances(String serviceName, int offset, int requestSize) throws NullPointerException, IllegalArgumentException { - return serviceDiscovery.getInstances(serviceName, offset, requestSize); - } - - @Override - public Page getInstances(String serviceName, int offset, int requestSize, boolean healthyOnly) throws NullPointerException, IllegalArgumentException { - return serviceDiscovery.getInstances(serviceName, offset, requestSize, healthyOnly); + public Page getInstances(String serviceName, int offset, int pageSize, boolean healthyOnly) throws NullPointerException, IllegalArgumentException { + return serviceDiscovery.getInstances(serviceName, offset, pageSize, healthyOnly); } @Override diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscovery.java index d5755640e92..947dd56cd72 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscovery.java @@ -16,19 +16,16 @@ */ package org.apache.dubbo.registry.client; -import org.apache.dubbo.common.extension.SPI; -import org.apache.dubbo.common.utils.DefaultPage; import org.apache.dubbo.common.utils.Page; import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; -import java.util.ArrayList; -import java.util.Iterator; import java.util.LinkedHashMap; +import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; -import static java.util.Collections.emptyList; +import static java.util.Collections.unmodifiableList; import static java.util.Collections.unmodifiableMap; /** @@ -36,7 +33,6 @@ * * @since 2.7.3 */ -@SPI("composite") public interface ServiceDiscovery { // ==================================== Lifecycle ==================================== // @@ -83,6 +79,15 @@ public interface ServiceDiscovery { // ==================================== Discovery ===================================== // + /** + * Get the default size of pagination query + * + * @return the default value is 100 + */ + default int getDefaultPageSize() { + return 100; + } + /** * Gets all service names * @@ -97,17 +102,25 @@ public interface ServiceDiscovery { * @return non-null {@link List} * @throws NullPointerException if serviceName is null is null */ - List getInstances(String serviceName) throws NullPointerException; + default List getInstances(String serviceName) throws NullPointerException { - /** - * Gets the total size of {@link #getInstances(String)} instances} - * - * @param serviceName the service name - * @return - * @throws NullPointerException if serviceName is null is null - */ - default int getTotalSizeInstances(String serviceName) throws NullPointerException { - return getInstances(serviceName).size(); + List allInstances = new LinkedList<>(); + + int offset = 0; + + int pageSize = getDefaultPageSize(); + + Page page = getInstances(serviceName, offset, pageSize); + + allInstances.addAll(page.getData()); + + while (page.hasNext()) { + offset += page.getDataSize(); + page = getInstances(serviceName, offset, pageSize); + allInstances.addAll(page.getData()); + } + + return unmodifiableList(allInstances); } /** @@ -116,14 +129,15 @@ default int getTotalSizeInstances(String serviceName) throws NullPointerExceptio * * @param serviceName the service name * @param offset the offset of request , the number "0" indicates first page - * @param requestSize the number of request, the {@link Integer#MAX_VALUE max value} indicates the range is unlimited + * @param pageSize the number of request, the {@link Integer#MAX_VALUE max value} indicates the range is unlimited * @return non-null {@link Page} object - * @throws NullPointerException if serviceName is null is null - * @throws IllegalArgumentException if offset or requestSize is negative number + * @throws NullPointerException if serviceName is null is null + * @throws IllegalArgumentException if offset or pageSize is negative number + * @throws UnsupportedOperationException if not supported */ - default Page getInstances(String serviceName, int offset, int requestSize) throws NullPointerException, + default Page getInstances(String serviceName, int offset, int pageSize) throws NullPointerException, IllegalArgumentException { - return getInstances(serviceName, offset, requestSize, false); + return getInstances(serviceName, offset, pageSize, false); } /** @@ -132,51 +146,16 @@ default Page getInstances(String serviceName, int offset, int r * * @param serviceName the service name * @param offset the offset of request , the number "0" indicates first page - * @param requestSize the number of request, the {@link Integer#MAX_VALUE max value} indicates the range is unlimited + * @param pageSize the number of request, the {@link Integer#MAX_VALUE max value} indicates the range is unlimited * @param healthyOnly if true , filter healthy instances only * @return non-null {@link Page} object - * @throws NullPointerException if serviceName is null is null - * @throws IllegalArgumentException if offset or requestSize is negative number + * @throws NullPointerException if serviceName is null is null + * @throws IllegalArgumentException if offset or pageSize is negative number + * @throws UnsupportedOperationException if not supported */ - default Page getInstances(String serviceName, int offset, int requestSize, boolean healthyOnly) throws - NullPointerException, IllegalArgumentException { - - List serviceInstances = getInstances(serviceName); - - DefaultPage page = new DefaultPage(offset, requestSize); - - int totalElements = getTotalSizeInstances(serviceName); - - boolean hasMore = totalElements > offset + requestSize; - - int fromIndex = offset < totalElements ? offset : -1; - - int endIndex = hasMore ? offset + requestSize : totalElements; - - List data = fromIndex < 0 ? emptyList() : - new ArrayList<>(serviceInstances.subList(fromIndex, endIndex)); - - Iterator iterator = data.iterator(); - - while (iterator.hasNext()) { - ServiceInstance serviceInstance = iterator.next(); - if (!serviceInstance.isEnabled()) { // remove disabled instance - iterator.remove(); - continue; - } - - if (healthyOnly) { - if (!serviceInstance.isHealthy()) { // remove unhealthy instance - iterator.remove(); - continue; - } - } - } - - page.setData(data); - page.setTotalSize(totalElements); - - return page; + default Page getInstances(String serviceName, int offset, int pageSize, boolean healthyOnly) throws + NullPointerException, IllegalArgumentException, UnsupportedOperationException { + throw new UnsupportedOperationException("Current implementation does not support pagination query method."); } /** @@ -187,8 +166,9 @@ default Page getInstances(String serviceName, int offset, int r * @param requestSize the number of request, the {@link Integer#MAX_VALUE max value} indicates the range is unlimited * @return non-null read-only {@link Map} whose key is the service name and value is * the {@link Page pagination} of {@link ServiceInstance service instances} - * @throws NullPointerException if serviceName is null is null - * @throws IllegalArgumentException if offset or requestSize is negative number + * @throws NullPointerException if serviceName is null is null + * @throws IllegalArgumentException if offset or requestSize is negative number + * @throws UnsupportedOperationException if not supported */ default Map> getInstances(Iterable serviceNames, int offset, int requestSize) throws NullPointerException, IllegalArgumentException { diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InMemoryServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InMemoryServiceDiscovery.java index 051b75fcd67..3556cd23881 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InMemoryServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InMemoryServiceDiscovery.java @@ -16,15 +16,21 @@ */ package org.apache.dubbo.registry.client; +import org.apache.dubbo.common.utils.DefaultPage; +import org.apache.dubbo.common.utils.Page; import org.apache.dubbo.event.EventDispatcher; import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; +import java.util.ArrayList; import java.util.HashMap; +import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; +import static java.util.Collections.emptyList; + /** * In-Memory {@link ServiceDiscovery} implementation * @@ -42,8 +48,24 @@ public Set getServices() { } @Override - public List getInstances(String serviceName) throws NullPointerException { - return repository.computeIfAbsent(serviceName, s -> new LinkedList<>()); + public Page getInstances(String serviceName, int offset, int pageSize, boolean healthyOnly) { + List instances = new ArrayList<>(repository.computeIfAbsent(serviceName, s -> new LinkedList<>())); + int totalSize = instances.size(); + List data = emptyList(); + if (offset < totalSize) { + int toIndex = offset + pageSize > totalSize - 1 ? totalSize : offset + pageSize; + data = instances.subList(offset, toIndex); + } + if (healthyOnly) { + Iterator iterator = data.iterator(); + while (iterator.hasNext()) { + ServiceInstance instance = iterator.next(); + if (!instance.isHealthy()) { + iterator.remove(); + } + } + } + return new DefaultPage<>(offset, pageSize, data, totalSize); } public String toString() { diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryTest.java index a716d802cc6..ff38f2eeddd 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryTest.java @@ -118,12 +118,12 @@ public void testGetInstances() { // offset starts 0 int offset = 0; - // requestSize > total elements - int requestSize = 5; + // pageSize > total elements + int pageSize = 5; - Page page = serviceDiscovery.getInstances("A", offset, requestSize); - assertEquals(0, page.getRequestOffset()); - assertEquals(5, page.getRequestSize()); + Page page = serviceDiscovery.getInstances("A", offset, pageSize); + assertEquals(0, page.getOffset()); + assertEquals(5, page.getPageSize()); assertEquals(3, page.getTotalSize()); assertEquals(3, page.getData().size()); assertTrue(page.hasData()); @@ -132,12 +132,12 @@ public void testGetInstances() { assertTrue(instances.contains(instance)); } - // requestSize < total elements - requestSize = 2; + // pageSize < total elements + pageSize = 2; - page = serviceDiscovery.getInstances("A", offset, requestSize); - assertEquals(0, page.getRequestOffset()); - assertEquals(2, page.getRequestSize()); + page = serviceDiscovery.getInstances("A", offset, pageSize); + assertEquals(0, page.getOffset()); + assertEquals(2, page.getPageSize()); assertEquals(3, page.getTotalSize()); assertEquals(2, page.getData().size()); assertTrue(page.hasData()); @@ -147,9 +147,9 @@ public void testGetInstances() { } offset = 1; - page = serviceDiscovery.getInstances("A", offset, requestSize); - assertEquals(1, page.getRequestOffset()); - assertEquals(2, page.getRequestSize()); + page = serviceDiscovery.getInstances("A", offset, pageSize); + assertEquals(1, page.getOffset()); + assertEquals(2, page.getPageSize()); assertEquals(3, page.getTotalSize()); assertEquals(2, page.getData().size()); assertTrue(page.hasData()); @@ -159,25 +159,25 @@ public void testGetInstances() { } offset = 2; - page = serviceDiscovery.getInstances("A", offset, requestSize); - assertEquals(2, page.getRequestOffset()); - assertEquals(2, page.getRequestSize()); + page = serviceDiscovery.getInstances("A", offset, pageSize); + assertEquals(2, page.getOffset()); + assertEquals(2, page.getPageSize()); assertEquals(3, page.getTotalSize()); assertEquals(1, page.getData().size()); assertTrue(page.hasData()); offset = 3; - page = serviceDiscovery.getInstances("A", offset, requestSize); - assertEquals(3, page.getRequestOffset()); - assertEquals(2, page.getRequestSize()); + page = serviceDiscovery.getInstances("A", offset, pageSize); + assertEquals(3, page.getOffset()); + assertEquals(2, page.getPageSize()); assertEquals(3, page.getTotalSize()); assertEquals(0, page.getData().size()); assertFalse(page.hasData()); offset = 5; - page = serviceDiscovery.getInstances("A", offset, requestSize); - assertEquals(5, page.getRequestOffset()); - assertEquals(2, page.getRequestSize()); + page = serviceDiscovery.getInstances("A", offset, pageSize); + assertEquals(5, page.getOffset()); + assertEquals(2, page.getPageSize()); assertEquals(3, page.getTotalSize()); assertEquals(0, page.getData().size()); assertFalse(page.hasData()); @@ -204,8 +204,8 @@ public void testGetInstancesWithHealthy() { int requestSize = 5; Page page = serviceDiscovery.getInstances("A", offset, requestSize, true); - assertEquals(0, page.getRequestOffset()); - assertEquals(5, page.getRequestSize()); + assertEquals(0, page.getOffset()); + assertEquals(5, page.getPageSize()); assertEquals(3, page.getTotalSize()); assertEquals(2, page.getData().size()); assertTrue(page.hasData()); @@ -219,8 +219,8 @@ public void testGetInstancesWithHealthy() { offset = 1; page = serviceDiscovery.getInstances("A", offset, requestSize, true); - assertEquals(1, page.getRequestOffset()); - assertEquals(2, page.getRequestSize()); + assertEquals(1, page.getOffset()); + assertEquals(2, page.getPageSize()); assertEquals(3, page.getTotalSize()); assertEquals(1, page.getData().size()); assertTrue(page.hasData()); @@ -231,24 +231,24 @@ public void testGetInstancesWithHealthy() { offset = 2; page = serviceDiscovery.getInstances("A", offset, requestSize, true); - assertEquals(2, page.getRequestOffset()); - assertEquals(2, page.getRequestSize()); + assertEquals(2, page.getOffset()); + assertEquals(2, page.getPageSize()); assertEquals(3, page.getTotalSize()); assertEquals(0, page.getData().size()); assertFalse(page.hasData()); offset = 3; page = serviceDiscovery.getInstances("A", offset, requestSize, true); - assertEquals(3, page.getRequestOffset()); - assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getOffset()); + assertEquals(2, page.getPageSize()); assertEquals(3, page.getTotalSize()); assertEquals(0, page.getData().size()); assertFalse(page.hasData()); offset = 5; page = serviceDiscovery.getInstances("A", offset, requestSize, true); - assertEquals(5, page.getRequestOffset()); - assertEquals(2, page.getRequestSize()); + assertEquals(5, page.getOffset()); + assertEquals(2, page.getPageSize()); assertEquals(3, page.getTotalSize()); assertEquals(0, page.getData().size()); assertFalse(page.hasData()); diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryTest.java b/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryTest.java index 88a3106c66e..6af604b2bbb 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryTest.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryTest.java @@ -142,8 +142,8 @@ public void testGetInstances() throws InterruptedException { int requestSize = 5; Page page = discovery.getInstances(SERVICE_NAME, offset, requestSize); - assertEquals(0, page.getRequestOffset()); - assertEquals(5, page.getRequestSize()); + assertEquals(0, page.getOffset()); + assertEquals(5, page.getPageSize()); assertEquals(3, page.getTotalSize()); assertEquals(3, page.getData().size()); assertTrue(page.hasData()); @@ -156,8 +156,8 @@ public void testGetInstances() throws InterruptedException { requestSize = 2; page = discovery.getInstances(SERVICE_NAME, offset, requestSize); - assertEquals(0, page.getRequestOffset()); - assertEquals(2, page.getRequestSize()); + assertEquals(0, page.getOffset()); + assertEquals(2, page.getPageSize()); assertEquals(3, page.getTotalSize()); assertEquals(2, page.getData().size()); assertTrue(page.hasData()); @@ -168,8 +168,8 @@ public void testGetInstances() throws InterruptedException { offset = 1; page = discovery.getInstances(SERVICE_NAME, offset, requestSize); - assertEquals(1, page.getRequestOffset()); - assertEquals(2, page.getRequestSize()); + assertEquals(1, page.getOffset()); + assertEquals(2, page.getPageSize()); assertEquals(3, page.getTotalSize()); assertEquals(2, page.getData().size()); assertTrue(page.hasData()); @@ -180,24 +180,24 @@ public void testGetInstances() throws InterruptedException { offset = 2; page = discovery.getInstances(SERVICE_NAME, offset, requestSize); - assertEquals(2, page.getRequestOffset()); - assertEquals(2, page.getRequestSize()); + assertEquals(2, page.getOffset()); + assertEquals(2, page.getPageSize()); assertEquals(3, page.getTotalSize()); assertEquals(1, page.getData().size()); assertTrue(page.hasData()); offset = 3; page = discovery.getInstances(SERVICE_NAME, offset, requestSize); - assertEquals(3, page.getRequestOffset()); - assertEquals(2, page.getRequestSize()); + assertEquals(3, page.getOffset()); + assertEquals(2, page.getPageSize()); assertEquals(3, page.getTotalSize()); assertEquals(0, page.getData().size()); assertFalse(page.hasData()); offset = 5; page = discovery.getInstances(SERVICE_NAME, offset, requestSize); - assertEquals(5, page.getRequestOffset()); - assertEquals(2, page.getRequestSize()); + assertEquals(5, page.getOffset()); + assertEquals(2, page.getPageSize()); assertEquals(3, page.getTotalSize()); assertEquals(0, page.getData().size()); assertFalse(page.hasData()); From f39906a34fbcdbdad8b21f77961499022e178a71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E9=A9=AC=E5=93=A5?= Date: Sat, 8 Jun 2019 02:48:54 +0800 Subject: [PATCH 36/46] Add Nacos implementation --- .../common/constants/RegistryConstants.java | 14 +- .../registry/nacos/NacosRegistryFactory.java | 70 +-------- .../registry/nacos/NacosServiceDiscovery.java | 111 ++++++++++++++ .../nacos/NacosServiceDiscoveryFactory.java | 39 +++++ .../nacos/util/NacosNamingServiceUtils.java | 138 ++++++++++++++++++ ...bo.registry.client.ServiceDiscoveryFactory | 1 + 6 files changed, 304 insertions(+), 69 deletions(-) create mode 100644 dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscovery.java create mode 100644 dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryFactory.java create mode 100644 dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtils.java create mode 100644 dubbo-registry/dubbo-registry-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscoveryFactory diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java index fdf742a618e..b28fe39ce09 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java @@ -72,6 +72,18 @@ public interface RegistryConstants { * * @since 2.7.3 */ - public static final String SUBSCRIBED_SERVICE_NAMES_KEY = "subscribed-services"; + String SUBSCRIBED_SERVICE_NAMES_KEY = "subscribed-services"; + + /** + * The request size of service instances + * + * @since 2.7.3 + */ + String INSTANCES_REQUEST_SIZE_KEY = "instances-request-size"; + + /** + * The default request size of service instances + */ + int DEFAULT_INSTANCES_REQUEST_SIZE = 100; } diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistryFactory.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistryFactory.java index 2b66fb1e95b..d1630ed0d8c 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistryFactory.java @@ -21,23 +21,10 @@ import org.apache.dubbo.registry.RegistryFactory; import org.apache.dubbo.registry.support.AbstractRegistryFactory; -import com.alibaba.nacos.api.NacosFactory; -import com.alibaba.nacos.api.exception.NacosException; -import com.alibaba.nacos.api.naming.NamingService; -import com.alibaba.nacos.client.naming.utils.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Properties; - -import static com.alibaba.nacos.api.PropertyKeyConst.ACCESS_KEY; -import static com.alibaba.nacos.api.PropertyKeyConst.CLUSTER_NAME; -import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT; -import static com.alibaba.nacos.api.PropertyKeyConst.NAMESPACE; -import static com.alibaba.nacos.api.PropertyKeyConst.SECRET_KEY; -import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; -import static com.alibaba.nacos.client.naming.utils.UtilAndComs.NACOS_NAMING_LOG_NAME; -import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; +import static org.apache.dubbo.registry.nacos.util.NacosNamingServiceUtils.createNamingService; /** * Nacos {@link RegistryFactory} @@ -50,59 +37,6 @@ public class NacosRegistryFactory extends AbstractRegistryFactory { @Override protected Registry createRegistry(URL url) { - return new NacosRegistry(url, buildNamingService(url)); - } - - private NamingService buildNamingService(URL url) { - Properties nacosProperties = buildNacosProperties(url); - NamingService namingService; - try { - namingService = NacosFactory.createNamingService(nacosProperties); - } catch (NacosException e) { - if (logger.isErrorEnabled()) { - logger.error(e.getErrMsg(), e); - } - throw new IllegalStateException(e); - } - return namingService; - } - - private Properties buildNacosProperties(URL url) { - Properties properties = new Properties(); - setServerAddr(url, properties); - setProperties(url, properties); - return properties; - } - - private void setServerAddr(URL url, Properties properties) { - StringBuilder serverAddrBuilder = - new StringBuilder(url.getHost()) // Host - .append(":") - .append(url.getPort()); // Port - - // Append backup parameter as other servers - String backup = url.getParameter(BACKUP_KEY); - if (backup != null) { - serverAddrBuilder.append(",").append(backup); - } - - String serverAddr = serverAddrBuilder.toString(); - properties.put(SERVER_ADDR, serverAddr); - } - - private void setProperties(URL url, Properties properties) { - putPropertyIfAbsent(url, properties, NAMESPACE); - putPropertyIfAbsent(url, properties, NACOS_NAMING_LOG_NAME); - putPropertyIfAbsent(url, properties, ENDPOINT); - putPropertyIfAbsent(url, properties, ACCESS_KEY); - putPropertyIfAbsent(url, properties, SECRET_KEY); - putPropertyIfAbsent(url, properties, CLUSTER_NAME); - } - - private void putPropertyIfAbsent(URL url, Properties properties, String propertyName) { - String propertyValue = url.getParameter(propertyName); - if (StringUtils.isNotEmpty(propertyValue)) { - properties.setProperty(propertyName, propertyValue); - } + return new NacosRegistry(url, createNamingService(url)); } } diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscovery.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscovery.java new file mode 100644 index 00000000000..274b7ccb815 --- /dev/null +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscovery.java @@ -0,0 +1,111 @@ +package org.apache.dubbo.registry.nacos;/* + * 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. + */ + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.function.ThrowableFunction; +import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.registry.client.ServiceDiscovery; +import org.apache.dubbo.registry.client.ServiceInstance; +import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; + +import com.alibaba.nacos.api.naming.NamingService; +import com.alibaba.nacos.api.naming.pojo.Instance; +import com.alibaba.nacos.api.naming.pojo.ListView; + +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +import static org.apache.dubbo.common.function.ThrowableConsumer.execute; +import static org.apache.dubbo.registry.nacos.util.NacosNamingServiceUtils.createNamingService; +import static org.apache.dubbo.registry.nacos.util.NacosNamingServiceUtils.getGroup; +import static org.apache.dubbo.registry.nacos.util.NacosNamingServiceUtils.toInstance; + +/** + * Nacos {@link ServiceDiscovery} implementation + * + * @see ServiceDiscovery + * @since 2.7.3 + */ +public class NacosServiceDiscovery implements ServiceDiscovery { + + private final Logger logger = LoggerFactory.getLogger(getClass()); + + private final NamingService namingService; + + private final String group; + + public NacosServiceDiscovery(URL connectionURL) { + this.namingService = createNamingService(connectionURL); + this.group = getGroup(connectionURL); + } + + @Override + public void start() { + // DO NOTHING + } + + @Override + public void stop() { + // DO NOTHING + } + + @Override + public void register(ServiceInstance serviceInstance) throws RuntimeException { + execute(namingService, service -> { + Instance instance = toInstance(serviceInstance); + service.registerInstance(instance.getServiceName(), group, instance); + }); + } + + @Override + public void update(ServiceInstance serviceInstance) throws RuntimeException { + // TODO: Nacos should support + unregister(serviceInstance); + register(serviceInstance); + } + + @Override + public void unregister(ServiceInstance serviceInstance) throws RuntimeException { + execute(namingService, service -> { + Instance instance = toInstance(serviceInstance); + service.deregisterInstance(instance.getServiceName(), group, instance); + }); + } + + @Override + public Set getServices() { + return ThrowableFunction.execute(namingService, service -> { + ListView view = service.getServicesOfServer(0, Integer.MAX_VALUE, group); + return new LinkedHashSet<>(view.getData()); + }); + } + + @Override + public List getInstances(String serviceName) throws NullPointerException { + return Collections.emptyList(); + } + + @Override + public void addServiceInstancesChangedListener(String serviceName, ServiceInstancesChangedListener listener) + throws NullPointerException, IllegalArgumentException { + + } +} diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryFactory.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryFactory.java new file mode 100644 index 00000000000..65ba64fc029 --- /dev/null +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryFactory.java @@ -0,0 +1,39 @@ +package org.apache.dubbo.registry.nacos;/* + * 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. + */ + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.registry.client.ServiceDiscovery; +import org.apache.dubbo.registry.client.ServiceDiscoveryFactory; + +import com.alibaba.nacos.api.naming.NamingService; + +import static org.apache.dubbo.registry.nacos.util.NacosNamingServiceUtils.createNamingService; + +/** + * Nacos {@link ServiceDiscoveryFactory} + * + * @see ServiceDiscoveryFactory + * @see ServiceDiscovery + * @since 2.7.3 + */ +public class NacosServiceDiscoveryFactory implements ServiceDiscoveryFactory { + + @Override + public ServiceDiscovery create(URL connectionURL) { + return new NacosServiceDiscovery(connectionURL); + } +} diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtils.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtils.java new file mode 100644 index 00000000000..a1f474d6de4 --- /dev/null +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtils.java @@ -0,0 +1,138 @@ +package org.apache.dubbo.registry.nacos.util;/* + * 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. + */ + +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.client.ServiceInstance; + +import com.alibaba.nacos.api.NacosFactory; +import com.alibaba.nacos.api.exception.NacosException; +import com.alibaba.nacos.api.naming.NamingService; +import com.alibaba.nacos.api.naming.pojo.Instance; +import com.alibaba.nacos.client.naming.utils.StringUtils; + +import java.util.Properties; + +import static com.alibaba.nacos.api.PropertyKeyConst.ACCESS_KEY; +import static com.alibaba.nacos.api.PropertyKeyConst.CLUSTER_NAME; +import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT; +import static com.alibaba.nacos.api.PropertyKeyConst.NAMESPACE; +import static com.alibaba.nacos.api.PropertyKeyConst.SECRET_KEY; +import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; +import static com.alibaba.nacos.client.naming.utils.UtilAndComs.NACOS_NAMING_LOG_NAME; +import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; + +/** + * The utilities class for {@link NamingService} + * + * @since 2.7.3 + */ +public class NacosNamingServiceUtils { + + private static final Logger logger = LoggerFactory.getLogger(NacosNamingServiceUtils.class); + + /** + * Convert the {@link ServiceInstance} to {@link Instance} + * + * @param serviceInstance {@link ServiceInstance} + * @return non-null + * @since 2.7.3 + */ + public static Instance toInstance(ServiceInstance serviceInstance) { + Instance instance = new Instance(); + instance.setInstanceId(serviceInstance.getId()); + instance.setServiceName(serviceInstance.getServiceName()); + instance.setIp(serviceInstance.getHost()); + instance.setPort(serviceInstance.getPort()); + instance.setMetadata(serviceInstance.getMetadata()); + instance.setEnabled(serviceInstance.isEnabled()); + instance.setHealthy(serviceInstance.isHealthy()); + return instance; + } + + /** + * The group of {@link NamingService} to register + * + * @param connectionURL {@link URL connection url} + * @return non-null, "default" as default + * @since 2.7.3 + */ + public static String getGroup(URL connectionURL) { + return connectionURL.getParameter("nacos.group", "default"); + } + + /** + * Create an instance of {@link NamingService} from specified {@link URL connection url} + * + * @param connectionURL {@link URL connection url} + * @return {@link NamingService} + * @since 2.7.3 + */ + public static NamingService createNamingService(URL connectionURL) { + Properties nacosProperties = buildNacosProperties(connectionURL); + NamingService namingService; + try { + namingService = NacosFactory.createNamingService(nacosProperties); + } catch (NacosException e) { + if (logger.isErrorEnabled()) { + logger.error(e.getErrMsg(), e); + } + throw new IllegalStateException(e); + } + return namingService; + } + + private static Properties buildNacosProperties(URL url) { + Properties properties = new Properties(); + setServerAddr(url, properties); + setProperties(url, properties); + return properties; + } + + private static void setServerAddr(URL url, Properties properties) { + StringBuilder serverAddrBuilder = + new StringBuilder(url.getHost()) // Host + .append(":") + .append(url.getPort()); // Port + + // Append backup parameter as other servers + String backup = url.getParameter(BACKUP_KEY); + if (backup != null) { + serverAddrBuilder.append(",").append(backup); + } + + String serverAddr = serverAddrBuilder.toString(); + properties.put(SERVER_ADDR, serverAddr); + } + + private static void setProperties(URL url, Properties properties) { + putPropertyIfAbsent(url, properties, NAMESPACE); + putPropertyIfAbsent(url, properties, NACOS_NAMING_LOG_NAME); + putPropertyIfAbsent(url, properties, ENDPOINT); + putPropertyIfAbsent(url, properties, ACCESS_KEY); + putPropertyIfAbsent(url, properties, SECRET_KEY); + putPropertyIfAbsent(url, properties, CLUSTER_NAME); + } + + private static void putPropertyIfAbsent(URL url, Properties properties, String propertyName) { + String propertyValue = url.getParameter(propertyName); + if (StringUtils.isNotEmpty(propertyValue)) { + properties.setProperty(propertyName, propertyValue); + } + } +} diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscoveryFactory b/dubbo-registry/dubbo-registry-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscoveryFactory new file mode 100644 index 00000000000..4fc3f4a4dd2 --- /dev/null +++ b/dubbo-registry/dubbo-registry-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscoveryFactory @@ -0,0 +1 @@ +nacos=org.apache.dubbo.registry.nacos.NacosServiceDiscoveryFactory \ No newline at end of file From 41c25bbd4d6ac2403ff1e99268e1cf0409b3bea8 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Sat, 8 Jun 2019 03:49:36 +0800 Subject: [PATCH 37/46] Polish apache/incubator-dubbo#3984 : Add Nacos implementation --- dubbo-bootstrap/pom.xml | 23 +++++++++++ .../DubboServiceConsumerBootstrap.java | 2 +- .../DubboServiceProviderBootstrap.java | 2 +- .../dubbo/common/utils/DefaultPageTest.java | 37 +++++++++++++++++ .../support/ServiceOrientedRegistry.java | 9 ++-- .../registry/nacos/NacosServiceDiscovery.java | 41 +++++++++++++++---- .../nacos/util/NacosNamingServiceUtils.java | 17 ++++++++ 7 files changed, 117 insertions(+), 14 deletions(-) create mode 100644 dubbo-common/src/test/java/org/apache/dubbo/common/utils/DefaultPageTest.java diff --git a/dubbo-bootstrap/pom.xml b/dubbo-bootstrap/pom.xml index 686ef7d0606..f7ec2641730 100644 --- a/dubbo-bootstrap/pom.xml +++ b/dubbo-bootstrap/pom.xml @@ -25,6 +25,8 @@ + + org.apache.dubbo dubbo-registry-zookeeper @@ -39,6 +41,27 @@ test + + + org.apache.dubbo + dubbo-registry-nacos + ${project.parent.version} + test + + + + org.apache.dubbo + dubbo-configcenter-nacos + ${project.parent.version} + test + + + + com.alibaba.nacos + nacos-client + test + + org.apache.dubbo dubbo-rpc-dubbo diff --git a/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceConsumerBootstrap.java b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceConsumerBootstrap.java index b9f677ea380..800f29de6e8 100644 --- a/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceConsumerBootstrap.java +++ b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceConsumerBootstrap.java @@ -34,7 +34,7 @@ public static void main(String[] args) throws Exception { .application("dubbo-consumer-demo") .next() .registry() - .address("zookeeper://127.0.0.1:2181?registry-type=service") + .address("nacos://127.0.0.1:8848?registry-type=service&subscribed-services=dubbo-provider-demo") .next() .reference("ref") .interfaceClass(EchoService.class) diff --git a/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceProviderBootstrap.java b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceProviderBootstrap.java index 049cae84a39..bb149ad7a5e 100644 --- a/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceProviderBootstrap.java +++ b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceProviderBootstrap.java @@ -34,7 +34,7 @@ public static void main(String[] args) throws IOException { .application("dubbo-provider-demo") .next() .registry() - .address("zookeeper://127.0.0.1:2181?registry-type=service") + .address("nacos://127.0.0.1:8848?registry-type=service") .next() .protocol() .name("dubbo") diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/DefaultPageTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/DefaultPageTest.java new file mode 100644 index 00000000000..3e6296ba3dd --- /dev/null +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/DefaultPageTest.java @@ -0,0 +1,37 @@ +/* + * 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.common.utils; + +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static java.util.Arrays.asList; + +/** + * {@link DefaultPage} + * + * @since 2.7.3 + */ +public class DefaultPageTest { + + @Test + public void test() { + List data = asList(1, 2, 3, 4, 5); + DefaultPage page = new DefaultPage(0, 1, data.subList(0, 1), data.size()); + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java index a636d2b4c64..945df0d680a 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java @@ -61,7 +61,6 @@ import static org.apache.dubbo.common.utils.CollectionUtils.isEmpty; import static org.apache.dubbo.common.utils.CollectionUtils.isNotEmpty; import static org.apache.dubbo.common.utils.StringUtils.isBlank; -import static org.apache.dubbo.common.utils.StringUtils.split; import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getExportedServicesRevision; import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getMetadataServiceURLsParams; import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getProviderHost; @@ -105,7 +104,7 @@ public ServiceOrientedRegistry(URL registryURL) { private Set buildSubscribedServices(URL url) { String subscribedServiceNames = url.getParameter(SUBSCRIBED_SERVICE_NAMES_KEY); return isBlank(subscribedServiceNames) ? emptySet() : - unmodifiableSet(of(split(subscribedServiceNames, ',')) + unmodifiableSet(of(subscribedServiceNames.split(",")) .map(String::trim) .filter(StringUtils::isNotEmpty) .collect(toSet())); @@ -228,13 +227,15 @@ protected void subscribeURLs(URL subscribedURL, NotifyListener listener, String listener.notify(subscribedURLs); } - private List getSubscribedURLs(URL subscribedURL, Collection instances) { List subscribedURLs = new LinkedList<>(); // local service instances could be mutable - List serviceInstances = new ArrayList<>(instances); + List serviceInstances = instances.stream() + .filter(ServiceInstance::isEnabled) + .filter(ServiceInstance::isHealthy) + .collect(Collectors.toList()); /** * A caches all revisions of exported services in different {@link ServiceInstance}s diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscovery.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscovery.java index 274b7ccb815..c7a248eccd9 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscovery.java @@ -21,17 +21,20 @@ import org.apache.dubbo.common.logger.LoggerFactory; 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 org.apache.dubbo.registry.nacos.util.NacosNamingServiceUtils; import com.alibaba.nacos.api.naming.NamingService; +import com.alibaba.nacos.api.naming.listener.NamingEvent; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; -import java.util.Collections; -import java.util.HashSet; +import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; +import java.util.stream.Collectors; import static org.apache.dubbo.common.function.ThrowableConsumer.execute; import static org.apache.dubbo.registry.nacos.util.NacosNamingServiceUtils.createNamingService; @@ -48,23 +51,25 @@ public class NacosServiceDiscovery implements ServiceDiscovery { private final Logger logger = LoggerFactory.getLogger(getClass()); - private final NamingService namingService; + private final URL connectionURL; private final String group; + private NamingService namingService; + public NacosServiceDiscovery(URL connectionURL) { - this.namingService = createNamingService(connectionURL); + this.connectionURL = connectionURL; this.group = getGroup(connectionURL); } @Override public void start() { - // DO NOTHING + this.namingService = createNamingService(connectionURL); } @Override public void stop() { - // DO NOTHING + this.namingService = null; } @Override @@ -99,13 +104,33 @@ public Set getServices() { } @Override - public List getInstances(String serviceName) throws NullPointerException { - return Collections.emptyList(); + public List getInstances(String serviceName) throws NullPointerException { + return ThrowableFunction.execute(namingService, service -> + service.selectInstances(serviceName, true) + .stream().map(NacosNamingServiceUtils::toServiceInstance) + .collect(Collectors.toList()) + ); } @Override public void addServiceInstancesChangedListener(String serviceName, ServiceInstancesChangedListener listener) throws NullPointerException, IllegalArgumentException { + execute(namingService, service -> { + service.subscribe(serviceName, e -> { // Register Nacos EventListener + if (e instanceof NamingEvent) { + NamingEvent event = (NamingEvent) e; + handleEvent(event, listener); + } + }); + }); + } + private void handleEvent(NamingEvent event, ServiceInstancesChangedListener listener) { + String serviceName = event.getServiceName(); + Collection serviceInstances = event.getInstances() + .stream() + .map(NacosNamingServiceUtils::toServiceInstance) + .collect(Collectors.toList()); + listener.onEvent(new ServiceInstancesChangedEvent(serviceName, serviceInstances)); } } diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtils.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtils.java index a1f474d6de4..2b1d6a898f4 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtils.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtils.java @@ -18,6 +18,7 @@ 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.client.DefaultServiceInstance; import org.apache.dubbo.registry.client.ServiceInstance; import com.alibaba.nacos.api.NacosFactory; @@ -65,6 +66,22 @@ public static Instance toInstance(ServiceInstance serviceInstance) { return instance; } + /** + * Convert the {@link Instance} to {@link ServiceInstance} + * + * @param instance {@link Instance} + * @return non-null + * @since 2.7.3 + */ + public static ServiceInstance toServiceInstance(Instance instance) { + DefaultServiceInstance serviceInstance = new DefaultServiceInstance(instance.getInstanceId(), + instance.getServiceName(), instance.getIp(), instance.getPort()); + serviceInstance.setMetadata(instance.getMetadata()); + serviceInstance.setEnabled(instance.isEnabled()); + serviceInstance.setHealthy(instance.isHealthy()); + return serviceInstance; + } + /** * The group of {@link NamingService} to register * From de63bdb79e4677580480c8c9744cf541c6829503 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Sat, 8 Jun 2019 23:27:02 +0800 Subject: [PATCH 38/46] Polish apache/incubator-dubbo#4268 : Dubbo Event - To support Generic event type handle --- .../dubbo/event/GenericEventListener.java | 121 ++++++++++++++++++ .../dubbo/event/GenericEventListenerTest.java | 77 +++++++++++ 2 files changed, 198 insertions(+) create mode 100644 dubbo-event/src/main/java/org/apache/dubbo/event/GenericEventListener.java create mode 100644 dubbo-event/src/test/java/org/apache/dubbo/event/GenericEventListenerTest.java diff --git a/dubbo-event/src/main/java/org/apache/dubbo/event/GenericEventListener.java b/dubbo-event/src/main/java/org/apache/dubbo/event/GenericEventListener.java new file mode 100644 index 00000000000..3e37ddd5620 --- /dev/null +++ b/dubbo-event/src/main/java/org/apache/dubbo/event/GenericEventListener.java @@ -0,0 +1,121 @@ +/* + * 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.event; + +import org.apache.dubbo.common.function.ThrowableConsumer; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import static java.util.Collections.emptySet; +import static java.util.stream.Stream.of; +import static org.apache.dubbo.common.function.ThrowableFunction.execute; + +/** + * An abstract class of {@link EventListener} for Generic events + * + * @see Event + * @see EventListener + * @since 2.7.3 + */ +public abstract class GenericEventListener implements EventListener { + + private final Method onEventMethod; + + private final Map, Set> handleEventMethods; + + protected GenericEventListener() { + this.onEventMethod = findOnEventMethod(); + this.handleEventMethods = findHandleEventMethods(); + } + + private Method findOnEventMethod() { + return execute(getClass(), listenerClass -> listenerClass.getMethod("onEvent", Event.class)); + } + + private Map, Set> findHandleEventMethods() { + // Event class for key, the eventMethods' Set as value + Map, Set> eventMethods = new HashMap<>(); + + of(getClass().getMethods()) + .filter(this::isHandleEventMethod) + .forEach(method -> { + Class paramType = method.getParameterTypes()[0]; + Set methods = eventMethods.computeIfAbsent(paramType, key -> new LinkedHashSet<>()); + methods.add(method); + }); + return eventMethods; + } + + public final void onEvent(Event event) { + Class eventClass = event.getClass(); + handleEventMethods.getOrDefault(eventClass, emptySet()).forEach(method -> { + ThrowableConsumer.execute(method, m -> { + m.invoke(this, event); + }); + }); + } + + /** + * Method must meet these conditions: + *

    + *
  • not {@link #onEvent(Event)} method
  • + *
  • public accessibility
  • + *
  • void return type
  • + *
  • no {@link Exception exception} declaration
  • + *
  • only one {@link Event} type argument
  • + *
+ * + * @param method + * @return + */ + private boolean isHandleEventMethod(Method method) { + + if (onEventMethod.equals(method)) { // not {@link #onEvent(Event)} method + return false; + } + + if (!Modifier.isPublic(method.getModifiers())) { // not public + return false; + } + + if (!void.class.equals(method.getReturnType())) { // void return type + return false; + } + + Class[] exceptionTypes = method.getExceptionTypes(); + + if (exceptionTypes.length > 0) { // no exception declaration + return false; + } + + Class[] paramTypes = method.getParameterTypes(); + if (paramTypes.length != 1) { // not only one argument + return false; + } + + if (!Event.class.isAssignableFrom(paramTypes[0])) { // not Event type argument + return false; + } + + return true; + } +} diff --git a/dubbo-event/src/test/java/org/apache/dubbo/event/GenericEventListenerTest.java b/dubbo-event/src/test/java/org/apache/dubbo/event/GenericEventListenerTest.java new file mode 100644 index 00000000000..c0ff9a1d41d --- /dev/null +++ b/dubbo-event/src/test/java/org/apache/dubbo/event/GenericEventListenerTest.java @@ -0,0 +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.event; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * {@link GenericEventListener} Test + * + * @since 2.7.3 + */ +public class GenericEventListenerTest { + + private EventDispatcher eventDispatcher; + + private MyGenericEventListener listener; + + @BeforeEach + public void init() { + this.listener = new MyGenericEventListener(); + this.eventDispatcher = EventDispatcher.getDefaultExtension(); + this.eventDispatcher.addEventListener(listener); + } + + @AfterEach + public void destroy() { + this.eventDispatcher.removeAllEventListeners(); + } + + @Test + public void testOnEvent() { + String value = "Hello,World"; + EchoEvent echoEvent = new EchoEvent(value); + eventDispatcher.dispatch(echoEvent); + assertEquals(echoEvent, listener.getEchoEvent()); + assertEquals(value, listener.getEchoEvent().getSource()); + } + + class MyGenericEventListener extends GenericEventListener { + + private EchoEvent echoEvent; + + public void onEvent(EchoEvent echoEvent) { + this.echoEvent = echoEvent; + } + + public void event(EchoEvent echoEvent) { + assertEquals("Hello,World", echoEvent.getSource()); + } + + public void event(EchoEvent echoEvent, Object arg) { + this.echoEvent = echoEvent; + } + + public EchoEvent getEchoEvent() { + return echoEvent; + } + } +} From 4673c3b201b8050e615088dd271fdbd3d7d67598 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Sun, 9 Jun 2019 00:28:12 +0800 Subject: [PATCH 39/46] Polish apache/incubator-dubbo#4268 : Update JavaDoc --- .../apache/dubbo/event/GenericEventListener.java | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/dubbo-event/src/main/java/org/apache/dubbo/event/GenericEventListener.java b/dubbo-event/src/main/java/org/apache/dubbo/event/GenericEventListener.java index 3e37ddd5620..065be3c553e 100644 --- a/dubbo-event/src/main/java/org/apache/dubbo/event/GenericEventListener.java +++ b/dubbo-event/src/main/java/org/apache/dubbo/event/GenericEventListener.java @@ -30,7 +30,17 @@ import static org.apache.dubbo.common.function.ThrowableFunction.execute; /** - * An abstract class of {@link EventListener} for Generic events + * An abstract class of {@link EventListener} for Generic events, the sub class could add more {@link Event event} + * handle methods, rather than only binds the {@link EventListener#onEvent(Event)} method that is declared to be + * final the implementation can't override. It's notable that all {@link Event event} handle methods must + * meet following conditions: + *
    + *
  • not {@link #onEvent(Event)} method
  • + *
  • public accessibility
  • + *
  • void return type
  • + *
  • no {@link Exception exception} declaration
  • + *
  • only one {@link Event} type argument
  • + *
* * @see Event * @see EventListener @@ -54,7 +64,6 @@ private Method findOnEventMethod() { private Map, Set> findHandleEventMethods() { // Event class for key, the eventMethods' Set as value Map, Set> eventMethods = new HashMap<>(); - of(getClass().getMethods()) .filter(this::isHandleEventMethod) .forEach(method -> { @@ -75,7 +84,7 @@ public final void onEvent(Event event) { } /** - * Method must meet these conditions: + * The {@link Event event} handle methods must meet following conditions: *
    *
  • not {@link #onEvent(Event)} method
  • *
  • public accessibility
  • From f516ca4ec6e3d156cd132d6ef85d299844405553 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Sun, 9 Jun 2019 03:11:42 +0800 Subject: [PATCH 40/46] Polish apache/incubator-dubbo#4268 : Add GenericEventListener implementation --- .../dubbo/bootstrap/DubboBootstrap.java | 49 ----------- .../src/test/resources/log4j.properties | 7 ++ .../event/listener/LoggingEventListener.java | 51 +++++++++++ .../org.apache.dubbo.event.EventListener | 3 +- .../EventPublishingServiceDiscovery.java | 6 +- .../event/ServiceDiscoveryStartedEvent.java | 5 +- .../event/ServiceDiscoveryStartingEvent.java | 5 +- .../event/ServiceDiscoveryStoppedEvent.java | 5 +- .../event/ServiceDiscoveryStoppingEvent.java | 5 +- .../ServiceInstancePreRegisteredEvent.java | 3 +- .../ServiceInstancePreUnregisteredEvent.java | 34 ++++++++ .../event/ServiceInstanceRegisteredEvent.java | 3 +- .../ServiceInstanceUnregisteredEvent.java | 35 ++++++++ .../event/ServiceInstancesChangedEvent.java | 3 +- .../event/listener/LoggingEventListener.java | 85 +++++++++++++++++++ .../org.apache.dubbo.event.EventListener | 3 +- .../nacos/util/NacosNamingServiceUtils.java | 3 +- 17 files changed, 231 insertions(+), 74 deletions(-) create mode 100644 dubbo-bootstrap/src/test/resources/log4j.properties create mode 100644 dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/listener/LoggingEventListener.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancePreUnregisteredEvent.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstanceUnregisteredEvent.java create mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/LoggingEventListener.java diff --git a/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java index 47bad6d9fa9..c6c26062b64 100644 --- a/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java +++ b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java @@ -34,8 +34,6 @@ import org.apache.dubbo.config.builders.RegistryBuilder; import org.apache.dubbo.config.builders.ServiceBuilder; import org.apache.dubbo.config.context.ConfigManager; -import org.apache.dubbo.config.event.DubboServiceDestroyedEvent; -import org.apache.dubbo.config.event.ServiceConfigExportedEvent; import org.apache.dubbo.config.metadata.ConfigurableMetadataServiceExporter; import org.apache.dubbo.event.EventDispatcher; import org.apache.dubbo.event.EventListener; @@ -43,9 +41,6 @@ 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.ServiceDiscoveryStartedEvent; -import org.apache.dubbo.registry.client.event.ServiceDiscoveryStoppedEvent; -import org.apache.dubbo.registry.client.event.ServiceInstanceRegisteredEvent; import org.apache.dubbo.registry.support.ServiceOrientedRegistry; import java.util.HashMap; @@ -234,8 +229,6 @@ public void init() { initReferenceConfigs(); - initEventListeners(); - clearBuilders(); initialized = true; @@ -418,48 +411,6 @@ private void initReferenceConfigs() { this.referenceConfigs.values().forEach(this::initReferenceConfig); } - private void initEventListeners() { - addEventListener(new EventListener() { - @Override - public void onEvent(ServiceInstanceRegisteredEvent event) { - if (logger.isInfoEnabled()) { - logger.info(event.getServiceInstance() + " has been registered."); - } - - } - }).addEventListener(new EventListener() { - @Override - public void onEvent(ServiceDiscoveryStartedEvent event) { - if (logger.isInfoEnabled()) { - logger.info(event.getServiceDiscovery() + " has been started."); - } - } - }).addEventListener(new EventListener() { - @Override - public void onEvent(ServiceConfigExportedEvent event) { - if (logger.isInfoEnabled()) { - logger.info(event.getServiceConfig().toString() + " has been exported."); - } - } - }).addEventListener(new EventListener() { - @Override - public void onEvent(ServiceDiscoveryStoppedEvent event) { - if (logger.isInfoEnabled()) { - logger.info(event.getServiceDiscovery() + " has been stopped."); - } - } - }).addEventListener(new EventListener() { - @Override - public void onEvent(DubboServiceDestroyedEvent event) { - stop(); - if (logger.isInfoEnabled()) { - logger.info(NAME + " has been destroyed."); - } - } - }); - - } - /** * Add an instance of {@link EventListener} * diff --git a/dubbo-bootstrap/src/test/resources/log4j.properties b/dubbo-bootstrap/src/test/resources/log4j.properties new file mode 100644 index 00000000000..15a0900f0d2 --- /dev/null +++ b/dubbo-bootstrap/src/test/resources/log4j.properties @@ -0,0 +1,7 @@ +###set log levels### +log4j.rootLogger=info, stdout +###output to the console### +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d{dd/MM/yy HH:mm:ss:SSS z}] %t %5p %c{2}: %m%n \ No newline at end of file diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/listener/LoggingEventListener.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/listener/LoggingEventListener.java new file mode 100644 index 00000000000..661c3d7e25b --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/event/listener/LoggingEventListener.java @@ -0,0 +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.config.event.listener; + +import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.config.event.DubboServiceDestroyedEvent; +import org.apache.dubbo.config.event.ServiceConfigExportedEvent; +import org.apache.dubbo.event.Event; +import org.apache.dubbo.event.GenericEventListener; + +import static java.lang.String.format; + +/** + * A listener for logging the {@link Event Dubbo event} + * + * @see ServiceConfigExportedEvent + * @since 2.7.3 + */ +public class LoggingEventListener extends GenericEventListener { + + private static final String NAME = "Dubbo Service"; + + private final Logger logger = LoggerFactory.getLogger(getClass()); + + public void onEvent(DubboServiceDestroyedEvent event) { + if (logger.isInfoEnabled()) { + logger.info(NAME + " has been destroyed."); + } + } + + private void debug(String pattern, Object... args) { + if (logger.isDebugEnabled()) { + logger.debug(format(pattern, args)); + } + } +} diff --git a/dubbo-config/dubbo-config-api/src/main/resources/META-INF/services/org.apache.dubbo.event.EventListener b/dubbo-config/dubbo-config-api/src/main/resources/META-INF/services/org.apache.dubbo.event.EventListener index b30703bf233..d77cfb49ecd 100644 --- a/dubbo-config/dubbo-config-api/src/main/resources/META-INF/services/org.apache.dubbo.event.EventListener +++ b/dubbo-config/dubbo-config-api/src/main/resources/META-INF/services/org.apache.dubbo.event.EventListener @@ -1 +1,2 @@ -org.apache.dubbo.config.event.listener.ServiceNameMappingListener \ No newline at end of file +org.apache.dubbo.config.event.listener.ServiceNameMappingListener +org.apache.dubbo.config.event.listener.LoggingEventListener \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceDiscovery.java index 8caaae435db..d1fc7927d41 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/EventPublishingServiceDiscovery.java @@ -26,7 +26,9 @@ import org.apache.dubbo.registry.client.event.ServiceDiscoveryStoppedEvent; import org.apache.dubbo.registry.client.event.ServiceDiscoveryStoppingEvent; import org.apache.dubbo.registry.client.event.ServiceInstancePreRegisteredEvent; +import org.apache.dubbo.registry.client.event.ServiceInstancePreUnregisteredEvent; import org.apache.dubbo.registry.client.event.ServiceInstanceRegisteredEvent; +import org.apache.dubbo.registry.client.event.ServiceInstanceUnregisteredEvent; import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; import java.util.List; @@ -176,9 +178,9 @@ public final void unregister(ServiceInstance serviceInstance) throws RuntimeExce requireNotStopped(UNREGISTER_ACTION); executeWithEvents( - empty(), + of(new ServiceInstancePreUnregisteredEvent(this, serviceInstance)), () -> serviceDiscovery.unregister(serviceInstance), - empty() + of(new ServiceInstanceUnregisteredEvent(this, serviceInstance)) ); } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStartedEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStartedEvent.java index d94204427b8..f44c108c09e 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStartedEvent.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStartedEvent.java @@ -19,11 +19,8 @@ import org.apache.dubbo.event.Event; import org.apache.dubbo.registry.client.ServiceDiscovery; -import java.util.EventObject; - /** - * The {@link ServiceDiscovery Service Discovery} Started {@link EventObject Event} - * after {@link ServiceDiscovery#start()} execution + * An event raised after the {@link ServiceDiscovery Service Discovery} started * * @see ServiceDiscovery#start() * @since 2.7.3 diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStartingEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStartingEvent.java index 03fdf61cd9c..63fd88c76f4 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStartingEvent.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStartingEvent.java @@ -19,11 +19,8 @@ import org.apache.dubbo.event.Event; import org.apache.dubbo.registry.client.ServiceDiscovery; -import java.util.EventObject; - /** - * The {@link ServiceDiscovery Service Discovery} Starting {@link EventObject Event} - * before {@link ServiceDiscovery#start()} execution + * An event raised when the {@link ServiceDiscovery Service Discovery} is starting. * * @see ServiceDiscovery#start * @since 2.7.3 diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStoppedEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStoppedEvent.java index f9ce0634e20..97ff0a9a636 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStoppedEvent.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStoppedEvent.java @@ -19,11 +19,8 @@ import org.apache.dubbo.event.Event; import org.apache.dubbo.registry.client.ServiceDiscovery; -import java.util.EventObject; - /** - * The {@link ServiceDiscovery Service Discovery} Stopped {@link EventObject Event} - * after {@link ServiceDiscovery#stop()} execution + * An event raised after the {@link ServiceDiscovery Service Discovery} stopped. * * @see ServiceDiscovery#stop() * @since 2.7.3 diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStoppingEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStoppingEvent.java index d6e3e248fa2..8c827c26935 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStoppingEvent.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceDiscoveryStoppingEvent.java @@ -19,11 +19,8 @@ import org.apache.dubbo.event.Event; import org.apache.dubbo.registry.client.ServiceDiscovery; -import java.util.EventObject; - /** - * The {@link ServiceDiscovery Service Discovery} Stopping {@link EventObject Event} - * before {@link ServiceDiscovery#stop()} execution + * An event raised when the {@link ServiceDiscovery Service Discovery} is stopping. * * @see ServiceDiscovery#stop() * @since 2.7.3 diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancePreRegisteredEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancePreRegisteredEvent.java index 5bdc1edd08d..463d1970938 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancePreRegisteredEvent.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancePreRegisteredEvent.java @@ -21,7 +21,8 @@ /** - * The before-{@link ServiceDiscovery#register(ServiceInstance) register} event for {@link ServiceInstance} + * An event raised before a {@link ServiceInstance service instance} + * {@link ServiceDiscovery#register(ServiceInstance) registered} * * @since 2.7.3 */ diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancePreUnregisteredEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancePreUnregisteredEvent.java new file mode 100644 index 00000000000..dc7aa058ae5 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancePreUnregisteredEvent.java @@ -0,0 +1,34 @@ +/* + * 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.client.event; + +import org.apache.dubbo.registry.client.ServiceDiscovery; +import org.apache.dubbo.registry.client.ServiceInstance; + + +/** + * An event raised before a {@link ServiceInstance service instance} + * {@link ServiceDiscovery#unregister(ServiceInstance) unregistered} + * + * @since 2.7.3 + */ +public class ServiceInstancePreUnregisteredEvent extends ServiceInstanceEvent { + + public ServiceInstancePreUnregisteredEvent(Object source, ServiceInstance serviceInstance) { + super(source, serviceInstance); + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstanceRegisteredEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstanceRegisteredEvent.java index cb2f2181450..3617d0ef022 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstanceRegisteredEvent.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstanceRegisteredEvent.java @@ -21,7 +21,8 @@ /** - * The after-{@link ServiceDiscovery#register(ServiceInstance) register} event for {@link ServiceInstance} + * An event raised after a {@link ServiceInstance service instance} + * {@link ServiceDiscovery#register(ServiceInstance) registered} * * @since 2.7.3 */ diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstanceUnregisteredEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstanceUnregisteredEvent.java new file mode 100644 index 00000000000..f3afd06eea9 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstanceUnregisteredEvent.java @@ -0,0 +1,35 @@ +/* + * 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.client.event; + +import org.apache.dubbo.registry.client.ServiceDiscovery; +import org.apache.dubbo.registry.client.ServiceInstance; + + +/** + * An event raised after a {@link ServiceInstance service instance} + * {@link ServiceDiscovery#unregister(ServiceInstance) unregistered} + * + * @see ServiceInstanceEvent + * @since 2.7.3 + */ +public class ServiceInstanceUnregisteredEvent extends ServiceInstanceEvent { + + public ServiceInstanceUnregisteredEvent(Object source, ServiceInstance serviceInstance) { + super(source, serviceInstance); + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancesChangedEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancesChangedEvent.java index 03fe3f0d1fd..d93173f585a 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancesChangedEvent.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancesChangedEvent.java @@ -21,12 +21,11 @@ import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; import java.util.Collection; -import java.util.EventObject; import static java.util.Collections.unmodifiableCollection; /** - * The Service Instances Changed {@link EventObject Event} cause by service + * An event raised after the {@link ServiceInstance instances} of one service has been changed. * * @see ServiceInstancesChangedListener * @since 2.7.3 diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/LoggingEventListener.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/LoggingEventListener.java new file mode 100644 index 00000000000..6f68cb7dd31 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/LoggingEventListener.java @@ -0,0 +1,85 @@ +/* + * 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.client.event.listener; + +import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.event.Event; +import org.apache.dubbo.event.GenericEventListener; +import org.apache.dubbo.registry.client.event.ServiceDiscoveryStartedEvent; +import org.apache.dubbo.registry.client.event.ServiceDiscoveryStartingEvent; +import org.apache.dubbo.registry.client.event.ServiceDiscoveryStoppedEvent; +import org.apache.dubbo.registry.client.event.ServiceDiscoveryStoppingEvent; +import org.apache.dubbo.registry.client.event.ServiceInstancePreRegisteredEvent; +import org.apache.dubbo.registry.client.event.ServiceInstancePreUnregisteredEvent; +import org.apache.dubbo.registry.client.event.ServiceInstanceRegisteredEvent; +import org.apache.dubbo.registry.client.event.ServiceInstanceUnregisteredEvent; +import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent; + +import static java.lang.String.format; + +/** + * A listener for logging the {@link Event Dubbo event} + * + * @since 2.7.3 + */ +public class LoggingEventListener extends GenericEventListener { + + private final Logger logger = LoggerFactory.getLogger(getClass()); + + public void onEvent(ServiceDiscoveryStartingEvent event) { + info("%s is starting...", event.getServiceDiscovery()); + } + + public void onEvent(ServiceDiscoveryStartedEvent event) { + info("%s is started.", event.getServiceDiscovery()); + } + + public void onEvent(ServiceInstancePreRegisteredEvent event) { + info("%s is registering into %s...", event.getServiceInstance(), event.getSource()); + } + + public void onEvent(ServiceInstanceRegisteredEvent event) { + info("%s has been registered into %s.", event.getServiceInstance(), event.getSource()); + } + + public void onEvent(ServiceInstancesChangedEvent event) { + info("The services'[name : %s] instances[size : %s] has been changed.", event.getServiceName(), event.getServiceInstances().size()); + } + + public void onEvent(ServiceInstancePreUnregisteredEvent event) { + info("%s is registering from %s...", event.getServiceInstance(), event.getSource()); + } + + public void onEvent(ServiceInstanceUnregisteredEvent event) { + info("%s has been unregistered from %s.", event.getServiceInstance(), event.getSource()); + } + + public void onEvent(ServiceDiscoveryStoppingEvent event) { + info("%s is stopping...", event.getServiceDiscovery()); + } + + public void onEvent(ServiceDiscoveryStoppedEvent event) { + info("%s is stopped.", event.getServiceDiscovery()); + } + + private void info(String pattern, Object... args) { + if (logger.isInfoEnabled()) { + logger.info(format(pattern, args)); + } + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/services/org.apache.dubbo.event.EventListener b/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/services/org.apache.dubbo.event.EventListener index f2d0579d623..4bb27fbb760 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/services/org.apache.dubbo.event.EventListener +++ b/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/services/org.apache.dubbo.event.EventListener @@ -1 +1,2 @@ -org.apache.dubbo.registry.client.event.listener.CustomizableServiceInstanceListener \ No newline at end of file +org.apache.dubbo.registry.client.event.listener.CustomizableServiceInstanceListener +org.apache.dubbo.registry.client.event.listener.LoggingEventListener \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtils.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtils.java index 2b1d6a898f4..f0d803892b4 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtils.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtils.java @@ -35,6 +35,7 @@ import static com.alibaba.nacos.api.PropertyKeyConst.NAMESPACE; import static com.alibaba.nacos.api.PropertyKeyConst.SECRET_KEY; import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; +import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; import static com.alibaba.nacos.client.naming.utils.UtilAndComs.NACOS_NAMING_LOG_NAME; import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; @@ -90,7 +91,7 @@ public static ServiceInstance toServiceInstance(Instance instance) { * @since 2.7.3 */ public static String getGroup(URL connectionURL) { - return connectionURL.getParameter("nacos.group", "default"); + return connectionURL.getParameter("nacos.group", DEFAULT_GROUP); } /** From 0d746f21db175f4ecddf772266af825fb355ec86 Mon Sep 17 00:00:00 2001 From: "ken.lj" Date: Fri, 14 Jun 2019 12:39:58 +0800 Subject: [PATCH 41/46] add cache for MetadataServiceProxy --- .../DubboServiceConsumerBootstrap.java | 2 +- .../DubboServiceProviderBootstrap.java | 2 +- .../common/constants/CommonConstants.java | 2 + .../DefaultMetadataServiceProxyFactory.java | 72 +++++++++++ .../metadata/MetadataServiceProxyFactory.java | 50 ++++++++ .../registry/client/ServiceInstance.java | 44 +++++++ .../DefaultMetadataServiceProxyFactory.java | 35 +++++- .../client/metadata/MetadataServiceProxy.java | 114 ------------------ .../metadata/MetadataServiceProxyFactory.java | 2 +- .../metadata/MetadataServiceURLBuilder.java | 81 ------------- .../support/ServiceOrientedRegistry.java | 3 +- 11 files changed, 205 insertions(+), 202 deletions(-) create mode 100644 dubbo-metadata/src/main/java/org/apache/dubbo/metadata/DefaultMetadataServiceProxyFactory.java create mode 100644 dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceProxyFactory.java delete mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxy.java delete mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLBuilder.java diff --git a/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceConsumerBootstrap.java b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceConsumerBootstrap.java index 800f29de6e8..d525ee2b344 100644 --- a/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceConsumerBootstrap.java +++ b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceConsumerBootstrap.java @@ -34,7 +34,7 @@ public static void main(String[] args) throws Exception { .application("dubbo-consumer-demo") .next() .registry() - .address("nacos://127.0.0.1:8848?registry-type=service&subscribed-services=dubbo-provider-demo") + .address("zookeeper://127.0.0.1:2181?registry-type=service&subscribed-services=dubbo-provider-demo") .next() .reference("ref") .interfaceClass(EchoService.class) diff --git a/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceProviderBootstrap.java b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceProviderBootstrap.java index bb149ad7a5e..049cae84a39 100644 --- a/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceProviderBootstrap.java +++ b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceProviderBootstrap.java @@ -34,7 +34,7 @@ public static void main(String[] args) throws IOException { .application("dubbo-provider-demo") .next() .registry() - .address("nacos://127.0.0.1:8848?registry-type=service") + .address("zookeeper://127.0.0.1:2181?registry-type=service") .next() .protocol() .name("dubbo") diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java index d005ae931ae..5e2e55047f8 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java @@ -151,6 +151,8 @@ public interface CommonConstants { String REVISION_KEY = "revision"; + String METADATA_REVISION = "metadata.revision"; + /** * package version in the manifest */ diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/DefaultMetadataServiceProxyFactory.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/DefaultMetadataServiceProxyFactory.java new file mode 100644 index 00000000000..74c6c1d917c --- /dev/null +++ b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/DefaultMetadataServiceProxyFactory.java @@ -0,0 +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.metadata; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.extension.ExtensionLoader; +import org.apache.dubbo.registry.client.ServiceInstance; +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.directory.StaticDirectory; +import org.apache.dubbo.rpc.cluster.support.AvailableCluster; + +import java.lang.reflect.Proxy; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * The factory of {@link MetadataService}'s {@link Proxy} + * + * @since 2.7.3 + */ +public class DefaultMetadataServiceProxyFactory implements MetadataServiceProxyFactory { + + private final Map proxys = new HashMap<>(); + + private ProxyFactory proxyFactory; + + private Protocol protocol; + + private Cluster cluster = ExtensionLoader.getExtensionLoader(Cluster.class).getExtension(AvailableCluster.NAME); + + public void setProtocol(Protocol protocol) { + this.protocol = protocol; + } + + public void setProxyFactory(ProxyFactory proxyFactory) { + this.proxyFactory = proxyFactory; + } + + @Override + public MetadataService getProxy(ServiceInstance serviceInstance) { + return proxys.computeIfAbsent(serviceInstance.getId(), id -> createProxy(serviceInstance)); + } + + protected MetadataService createProxy(ServiceInstance serviceInstance) { + List urls = ServiceInstance.toUrls(serviceInstance); + List> invokers = urls.stream() + .map(url -> protocol.refer(MetadataService.class, url)) + .collect(Collectors.toList()); + + Invoker invoker = cluster.join(new StaticDirectory<>(invokers)); + return proxyFactory.getProxy(invoker); + } +} diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceProxyFactory.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceProxyFactory.java new file mode 100644 index 00000000000..eefa7556712 --- /dev/null +++ b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceProxyFactory.java @@ -0,0 +1,50 @@ +/* + * 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; + +import org.apache.dubbo.common.extension.SPI; +import org.apache.dubbo.registry.client.ServiceInstance; + +import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; + +/** + * A factory to create a {@link MetadataService} proxy + * + * @see ServiceInstance + * @see MetadataService + * @since 2.7.3 + */ +@SPI("default") +public interface MetadataServiceProxyFactory { + + /** + * Create a {@link MetadataService} proxy via the specified {@link ServiceInstance} + * + * @param serviceInstance the instance of {@link ServiceInstance} + * @return non-null + */ + MetadataService getProxy(ServiceInstance serviceInstance); + + /** + * Get the default extension of {@link MetadataServiceProxyFactory} + * + * @return non-null + */ + static MetadataServiceProxyFactory getDefaultExtension() { + return getExtensionLoader(MetadataServiceProxyFactory.class).getDefaultExtension(); + } +} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstance.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstance.java index bcdcfd29e66..cd501e6cee0 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstance.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstance.java @@ -16,8 +16,19 @@ */ package org.apache.dubbo.registry.client; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.URLBuilder; +import org.apache.dubbo.metadata.MetadataService; + +import java.util.ArrayList; +import java.util.List; import java.util.Map; +import static java.lang.String.valueOf; +import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getMetadataServiceURLsParams; +import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getProviderHost; +import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getProviderPort; + /** * The model class of an instance of a service, which is used for service registration and discovery. *

    @@ -91,4 +102,37 @@ default boolean isHealthy() { * @return if equals , return true, or false */ boolean equals(Object another); + + /** + * Build the {@link URL urls} from {@link ServiceInstance#getMetadata() the metadata} of {@link ServiceInstance} + * + * @param serviceInstance {@link ServiceInstance} + * @return the not-null {@link List} + */ + static List toUrls(ServiceInstance serviceInstance) { + + Map> paramsMap = getMetadataServiceURLsParams(serviceInstance); + + List urls = new ArrayList<>(paramsMap.size()); + + for (Map.Entry> entry : paramsMap.entrySet()) { + + URLBuilder urlBuilder = new URLBuilder(); + String protocol = entry.getKey(); + Map urlParams = entry.getValue(); + String host = getProviderHost(urlParams); + Integer port = getProviderPort(urlParams); + urlBuilder.setHost(host) + .setPort(port) + .setProtocol(protocol) + .setPath(MetadataService.class.getName()); + + // add parameters + entry.getValue().forEach((name, value) -> urlBuilder.addParameter(name, valueOf(value))); + + urls.add(urlBuilder.build()); + } + + return urls; + } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/DefaultMetadataServiceProxyFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/DefaultMetadataServiceProxyFactory.java index 65af122b097..b1b773b5519 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/DefaultMetadataServiceProxyFactory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/DefaultMetadataServiceProxyFactory.java @@ -16,11 +16,22 @@ */ package org.apache.dubbo.registry.client.metadata; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.metadata.MetadataService; import org.apache.dubbo.registry.client.ServiceInstance; +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.directory.StaticDirectory; +import org.apache.dubbo.rpc.cluster.support.AvailableCluster; import java.lang.reflect.Proxy; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; /** * The factory of {@link MetadataService}'s {@link Proxy} @@ -29,14 +40,34 @@ */ public class DefaultMetadataServiceProxyFactory implements MetadataServiceProxyFactory { + private final Map proxys = new HashMap<>(); + + private ProxyFactory proxyFactory; + private Protocol protocol; + private Cluster cluster = ExtensionLoader.getExtensionLoader(Cluster.class).getExtension(AvailableCluster.NAME); + public void setProtocol(Protocol protocol) { this.protocol = protocol; } + public void setProxyFactory(ProxyFactory proxyFactory) { + this.proxyFactory = proxyFactory; + } + @Override - public MetadataService createProxy(ServiceInstance serviceInstance) { - return new MetadataServiceProxy(serviceInstance, protocol); + public MetadataService getProxy(ServiceInstance serviceInstance) { + return proxys.computeIfAbsent(serviceInstance.getId(), id -> createProxy(serviceInstance)); + } + + protected MetadataService createProxy(ServiceInstance serviceInstance) { + List urls = ServiceInstance.toUrls(serviceInstance); + List> invokers = urls.stream() + .map(url -> protocol.refer(MetadataService.class, url)) + .collect(Collectors.toList()); + + Invoker invoker = cluster.join(new StaticDirectory<>(invokers)); + return proxyFactory.getProxy(invoker); } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxy.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxy.java deleted file mode 100644 index 538365f6b96..00000000000 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxy.java +++ /dev/null @@ -1,114 +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.client.metadata; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.metadata.MetadataService; -import org.apache.dubbo.registry.client.ServiceInstance; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Protocol; -import org.apache.dubbo.rpc.proxy.InvokerInvocationHandler; - -import java.util.Iterator; -import java.util.List; -import java.util.function.Function; - -import static java.lang.reflect.Proxy.newProxyInstance; -import static org.apache.dubbo.registry.client.metadata.MetadataServiceURLBuilder.INSTANCE; - -/** - * The Proxy object for the {@link MetadataService} whose {@link ServiceInstance} providers may export multiple - * {@link Protocol protocols} at the same time. - * - * @see ServiceInstance - * @see MetadataService - * @since 2.7.3 - */ -class MetadataServiceProxy implements MetadataService { - - private final Logger logger = LoggerFactory.getLogger(getClass()); - - private final List urls; - - private final Protocol protocol; - - public MetadataServiceProxy(ServiceInstance serviceInstance, Protocol protocol) { - this(INSTANCE.build(serviceInstance), protocol); - } - - public MetadataServiceProxy(List urls, Protocol protocol) { - this.urls = urls; - this.protocol = protocol; - } - - @Override - public String serviceName() { - return doInMetadataService(MetadataService::serviceName); - } - - @Override - public List getSubscribedURLs() { - return doInMetadataService(MetadataService::getSubscribedURLs); - } - - @Override - public List getExportedURLs(String serviceInterface, String group, String version, String protocol) { - return doInMetadataService(metadataService -> - metadataService.getExportedURLs(serviceInterface, group, version, protocol)); - } - - protected T doInMetadataService(Function callback) { - - T result = null; // execution result - - Throwable exception = null; // exception maybe present - - Iterator iterator = urls.iterator(); - - while (iterator.hasNext()) { // Executes MetadataService's method until success - URL url = iterator.next(); - Invoker invoker = null; - try { - invoker = this.protocol.refer(MetadataService.class, url); - MetadataService proxy = (MetadataService) newProxyInstance(getClass().getClassLoader(), - new Class[]{MetadataService.class}, new InvokerInvocationHandler(invoker)); - result = callback.apply(proxy); - exception = null; - } catch (Throwable e) { - exception = e; - // If met with some error, invoke next - if (logger.isErrorEnabled()) { - logger.error(e.getMessage(), e); - } - } finally { - if (invoker != null) { - // to destroy the Invoker finally - invoker.destroy(); - invoker = null; - } - } - } - - if (exception != null) { // If all executions were failed - throw new RuntimeException(exception.getMessage(), exception); - } - - return result; - } -} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxyFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxyFactory.java index 8cb803c0690..9a1e337b886 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxyFactory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxyFactory.java @@ -38,7 +38,7 @@ public interface MetadataServiceProxyFactory { * @param serviceInstance the instance of {@link ServiceInstance} * @return non-null */ - MetadataService createProxy(ServiceInstance serviceInstance); + MetadataService getProxy(ServiceInstance serviceInstance); /** * Get the default extension of {@link MetadataServiceProxyFactory} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLBuilder.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLBuilder.java deleted file mode 100644 index fa6416b6c9b..00000000000 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLBuilder.java +++ /dev/null @@ -1,81 +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.client.metadata; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.URLBuilder; -import org.apache.dubbo.metadata.MetadataService; -import org.apache.dubbo.registry.client.ServiceInstance; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import static java.lang.String.valueOf; -import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getMetadataServiceURLsParams; -import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getProviderHost; -import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getProviderPort; - -/** - * The {@link URL} builder for {@link MetadataService} - * - * @see MetadataService - * @since 2.7.3 - */ -class MetadataServiceURLBuilder { - - /** - * The singleton instance of {@link MetadataServiceURLBuilder} - */ - public static final MetadataServiceURLBuilder INSTANCE = new MetadataServiceURLBuilder(); - - private MetadataServiceURLBuilder() { - } - - /** - * Build the {@link URL urls} from {@link ServiceInstance#getMetadata() the metadata} of {@link ServiceInstance} - * - * @param serviceInstance {@link ServiceInstance} - * @return the not-null {@link List} - */ - public List build(ServiceInstance serviceInstance) { - - Map> paramsMap = getMetadataServiceURLsParams(serviceInstance); - - List urls = new ArrayList<>(paramsMap.size()); - - for (Map.Entry> entry : paramsMap.entrySet()) { - - URLBuilder urlBuilder = new URLBuilder(); - String protocol = entry.getKey(); - Map urlParams = entry.getValue(); - String host = getProviderHost(urlParams); - Integer port = getProviderPort(urlParams); - urlBuilder.setHost(host) - .setPort(port) - .setProtocol(protocol) - .setPath(MetadataService.class.getName()); - - // add parameters - entry.getValue().forEach((name, value) -> urlBuilder.addParameter(name, valueOf(value))); - - urls.add(urlBuilder.build()); - } - - return urls; - } -} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java index 945df0d680a..34e209e3418 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java @@ -91,7 +91,6 @@ public class ServiceOrientedRegistry extends FailbackRegistry { private final MetadataServiceProxyFactory metadataServiceProxyFactory; - public ServiceOrientedRegistry(URL registryURL) { super(registryURL); this.serviceDiscovery = buildServiceDiscovery(registryURL); @@ -397,7 +396,7 @@ protected List getProviderExportedURLs(URL subscribedURL, ServiceInstance p String protocol = subscribedURL.getParameter(PROTOCOL_KEY); try { - MetadataService metadataService = metadataServiceProxyFactory.createProxy(providerInstance); + MetadataService metadataService = metadataServiceProxyFactory.getProxy(providerInstance); List urls = metadataService.getExportedURLs(serviceInterface, group, version, protocol); exportedURLs = urls.stream().map(URL::valueOf).collect(Collectors.toList()); } catch (Throwable e) { From 6bfe8814244d34943d64dd39cc4f9cbd0439a77e Mon Sep 17 00:00:00 2001 From: "ken.lj" Date: Fri, 14 Jun 2019 13:56:35 +0800 Subject: [PATCH 42/46] support multiple metadata and configcenter --- dubbo-all/pom.xml | 26 +- dubbo-bom/pom.xml | 23 +- .../dubbo/bootstrap/DubboBootstrap.java | 420 +++++++++++------- .../dubbo/bootstrap/DubboBootstrapTest.java | 30 +- .../DubboServiceConsumerBootstrap.java | 37 +- .../DubboServiceProviderBootstrap.java | 27 +- dubbo-cluster/pom.xml | 5 - .../apache/dubbo/rpc/cluster/Directory.java | 2 + .../cluster/directory/StaticDirectory.java | 5 + .../rpc/cluster/router/AbstractRouter.java | 2 +- .../router/condition/config/AppRouter.java | 2 +- .../condition/config/AppRouterFactory.java | 2 +- .../condition/config/ListenableRouter.java | 8 +- .../condition/config/ServiceRouter.java | 2 +- .../config/ServiceRouterFactory.java | 2 +- .../rpc/cluster/router/tag/TagRouter.java | 10 +- .../cluster/router/tag/TagRouterFactory.java | 2 +- .../support/AbstractClusterInvoker.java | 4 + .../apache/dubbo/common/bytecode/Proxy.java | 2 +- .../AbstractDynamicConfigurationFactory.java | 19 +- .../configcenter/ConfigChangeEvent.java | 2 +- .../configcenter/ConfigChangeType.java | 2 +- .../configcenter/ConfigurationListener.java | 2 +- .../config}/configcenter/Constants.java | 2 +- .../configcenter/DynamicConfiguration.java | 2 +- .../DynamicConfigurationFactory.java | 2 +- .../nop/NopDynamicConfiguration.java | 6 +- .../nop/NopDynamicConfigurationFactory.java | 6 +- .../CompositeDynamicConfiguration.java | 98 ++++ .../common/constants/CommonConstants.java | 4 + .../apache/dubbo/common/utils/UrlUtils.java | 21 + ...g.configcenter.DynamicConfigurationFactory | 1 + .../com/alibaba/dubbo/common/Constants.java | 2 +- dubbo-config/dubbo-config-api/pom.xml | 6 - .../apache/dubbo/config/AbstractConfig.java | 3 - .../dubbo/config/AbstractInterfaceConfig.java | 121 +---- .../dubbo/config/AbstractServiceConfig.java | 4 +- .../dubbo/config/ConfigCenterConfig.java | 10 +- .../dubbo/config/MetadataReportConfig.java | 13 + .../apache/dubbo/config/ReferenceConfig.java | 12 +- .../apache/dubbo/config/RegistryConfig.java | 13 + .../apache/dubbo/config/ServiceConfig.java | 29 +- .../config/builders/ApplicationBuilder.java | 4 + .../config/builders/ProtocolBuilder.java | 4 + .../config/builders/ReferenceBuilder.java | 4 + .../config/builders/RegistryBuilder.java | 4 + .../dubbo/config/builders/ServiceBuilder.java | 4 + .../dubbo/config/context/ConfigManager.java | 165 +++++-- .../ConfigurableMetadataServiceExporter.java | 4 +- .../config}/telnet/ShutdownTelnetHandler.java | 2 +- ...apache.dubbo.remoting.telnet.TelnetHandler | 1 + ...nfigurableMetadataServiceExporterTest.java | 4 +- .../dubbo/config}/service/DemoException.java | 2 +- .../dubbo/config}/service/DemoService.java | 2 +- .../config}/service/DemoServiceImpl.java | 2 +- .../config}/service/GenericServiceTest.java | 6 +- .../apache/dubbo/config}/service/User.java | 2 +- .../telnet/ShutdownTelnetHandlerTest.java | 3 +- .../validation/ValidationParameter.java | 2 +- .../config}/validation/ValidationService.java | 2 +- .../validation/ValidationServiceImpl.java | 2 +- .../config}/validation/ValidationTest.java | 2 +- .../main/resources/META-INF/compat/dubbo.xsd | 5 + .../src/main/resources/META-INF/dubbo.xsd | 5 + .../dubbo-configcenter-api/pom.xml | 39 -- ...o.configcenter.DynamicConfigurationFactory | 1 - .../AbstractDynamicConfigurationTest.java | 47 -- .../mock/MockDynamicConfiguration.java | 54 --- .../nop/NopDynamicConfigurationTest.java | 70 --- ...o.configcenter.DynamicConfigurationFactory | 1 - .../dubbo-configcenter-apollo/pom.xml | 2 +- .../apollo/ApolloDynamicConfiguration.java | 14 +- .../ApolloDynamicConfigurationFactory.java | 4 +- ....configcenter.DynamicConfigurationFactory} | 0 .../dubbo-configcenter-consul/pom.xml | 2 +- .../consul/ConsulDynamicConfiguration.java | 12 +- .../ConsulDynamicConfigurationFactory.java | 4 +- ....configcenter.DynamicConfigurationFactory} | 0 .../dubbo-configcenter-etcd/pom.xml | 11 +- .../etcd/EtcdDynamicConfiguration.java | 10 +- .../etcd/EtcdDynamicConfigurationFactory.java | 4 +- ....configcenter.DynamicConfigurationFactory} | 0 .../etcd/EtcdDynamicConfigurationTest.java | 4 +- .../dubbo-configcenter-nacos/pom.xml | 2 +- .../nacos/NacosDynamicConfiguration.java | 10 +- .../NacosDynamicConfigurationFactory.java | 4 +- ....configcenter.DynamicConfigurationFactory} | 0 .../nacos/NacosDynamicConfigurationTest.java | 4 +- .../dubbo-configcenter-zookeeper/pom.xml | 2 +- .../support/zookeeper/CacheListener.java | 6 +- .../ZookeeperDynamicConfiguration.java | 6 +- .../ZookeeperDynamicConfigurationFactory.java | 4 +- ....configcenter.DynamicConfigurationFactory} | 0 .../ZookeeperDynamicConfigurationTest.java | 8 +- dubbo-configcenter/pom.xml | 1 - dubbo-container/dubbo-container-log4j/pom.xml | 5 - .../dubbo-demo-api-consumer/pom.xml | 5 + .../dubbo-demo-api-provider/pom.xml | 5 + .../dubbo-metadata-api}/pom.xml | 40 +- ...ynamicConfigurationServiceNameMapping.java | 2 +- .../dubbo/metadata/MetadataService.java | 13 +- .../metadata/MetadataServiceExporter.java | 0 .../dubbo/metadata/ServiceNameMapping.java | 0 .../metadata/WritableMetadataService.java} | 18 +- .../definition/ServiceDefinitionBuilder.java | 0 .../definition/TypeDefinitionBuilder.java | 0 .../definition/builder/ArrayTypeBuilder.java | 0 .../builder/CollectionTypeBuilder.java | 0 .../builder/DefaultTypeBuilder.java | 0 .../definition/builder/EnumTypeBuilder.java | 0 .../definition/builder/MapTypeBuilder.java | 0 .../definition/builder/TypeBuilder.java | 0 .../model/FullServiceDefinition.java | 0 .../definition/model/MethodDefinition.java | 3 +- .../definition/model/ServiceDefinition.java | 3 +- .../definition/model/TypeDefinition.java | 3 +- .../metadata/definition/util/ClassUtils.java | 0 .../util/JaketConfigurationUtils.java | 0 .../InMemoryWritableMetadataService.java} | 47 +- ...g.apache.dubbo.metadata.ServiceNameMapping | 0 ...che.dubbo.metadata.WritableMetadataService | 1 + ...bo.metadata.definition.builder.TypeBuilder | 0 ...icConfigurationServiceNameMappingTest.java | 4 +- .../InMemoryWritableMetadataServiceTest.java} | 7 +- .../metadata/LocalMetadataServiceTest.java | 6 +- .../metadata/definition/MetadataTest.java | 0 .../metadata/definition/MetadataUtils.java | 0 .../ServiceDefinitionBuildderTest.java | 0 .../definition/common/ClassExtendsMap.java | 0 .../metadata/definition/common/ColorEnum.java | 0 .../definition/common/OuterClass.java | 0 .../common/ResultWithRawCollections.java | 0 .../definition/common/TestService.java | 0 .../definition/service/ComplexObject.java | 0 .../definition/service/DemoService.java | 0 .../dubbo-metadata-report-api/pom.xml | 10 +- .../identifier/MetadataIdentifier.java | 14 +- .../RemoteWritableMetadataService.java | 109 ++++- .../dubbo/metadata/store/MetadataReport.java | 21 +- .../metadata/store/MetadataReportFactory.java | 0 .../support/AbstractMetadataReport.java | 40 +- .../AbstractMetadataReportFactory.java | 4 +- .../dubbo/metadata/support/Constants.java | 0 ...che.dubbo.metadata.WritableMetadataService | 1 + .../identifier/MetadataIdentifierTest.java | 0 .../integration/InterfaceNameTestService.java | 0 .../InterfaceNameTestService2.java | 0 .../MetadataReportServiceTest.java | 6 +- .../integration/RetryTestService.java | 0 .../store/test/JTestMetadataReport4Test.java | 21 + .../test/JTestMetadataReportFactory4Test.java | 0 .../AbstractMetadataReportFactoryTest.java | 25 +- .../support/AbstractMetadataReportTest.java | 41 ++ ...dubbo.metadata.store.MetadataReportFactory | 0 .../dubbo-metadata-report-consul/pom.xml | 0 .../store/consul/ConsulMetadataReport.java | 22 + .../consul/ConsulMetadataReportFactory.java | 0 ...dubbo.metadata.store.MetadataReportFactory | 0 .../dubbo-metadata-report-etcd/pom.xml | 0 .../store/etcd/EtcdMetadataReport.java | 22 + .../store/etcd/EtcdMetadataReportFactory.java | 0 ...dubbo.metadata.store.MetadataReportFactory | 0 .../store/etcd/EtcdMetadata4TstService.java | 0 .../store/etcd/EtcdMetadataReportTest.java | 0 .../dubbo-metadata-report-nacos/pom.xml | 0 .../store/nacos/NacosMetadataReport.java | 34 +- .../nacos/NacosMetadataReportFactory.java | 0 ...dubbo.metadata.store.MetadataReportFactory | 0 .../store/nacos/NacosMetadata4TstService.java | 0 .../store/nacos/NacosMetadataReportTest.java | 0 .../dubbo-metadata-report-redis/pom.xml | 0 .../store/redis/RedisMetadataReport.java | 20 + .../redis/RedisMetadataReportFactory.java | 0 ...dubbo.metadata.store.MetadataReportFactory | 0 .../store/redis/RedisMetadata4TstService.java | 0 .../store/redis/RedisMetadataReportTest.java | 0 .../dubbo-metadata-report-zookeeper/pom.xml | 0 .../zookeeper/ZookeeperMetadataReport.java | 22 + .../ZookeeperMetadataReportFactory.java | 0 ...dubbo.metadata.store.MetadataReportFactory | 0 .../ZookeeperMetadataReport4TstService.java | 0 .../ZookeeperMetadataReportTest.java | 0 .../dubbo-metadata-report}/pom.xml | 3 +- dubbo-metadata/pom.xml | 41 +- .../DefaultMetadataServiceProxyFactory.java | 72 --- .../metadata/MetadataServiceProxyFactory.java | 50 --- ...apache.dubbo.metadata.LocalMetadataService | 1 - .../org/apache/dubbo/qos/command/impl/Ls.java | 9 +- .../dubbo/qos/command/impl/Offline.java | 8 +- .../apache/dubbo/qos/command/impl/Online.java | 8 +- .../apache/dubbo/qos/command/impl/LsTest.java | 17 +- .../dubbo/qos/command/impl/OfflineTest.java | 15 +- .../dubbo/qos/command/impl/OnlineTest.java | 13 +- dubbo-registry/dubbo-registry-api/pom.xml | 11 +- ...tedServicesRevisionMetadataCustomizer.java | 6 +- ...ataServiceURLParamsMetadataCustomizer.java | 6 +- .../DefaultMetadataServiceProxyFactory.java | 2 +- .../MetadataServiceProxyFactory.java | 8 +- .../RemoteMetadataServiceProxyFactory.java | 15 +- .../AbstractConfiguratorListener.java | 8 +- .../integration/RegistryDirectory.java | 7 +- .../integration/RegistryProtocol.java | 13 +- .../support/ConsumerInvokerWrapper.java | 88 ---- .../support/ProviderConsumerRegTable.java | 112 ----- .../support/ServiceOrientedRegistry.java | 22 +- ...lient.metadata.MetadataServiceProxyFactory | 1 - ...metadata.proxy.MetadataServiceProxyFactory | 2 + .../support/ServiceOrientedRegistryTest.java | 6 +- .../nacos/NacosServiceDiscoveryFactory.java | 4 - .../dubbo/rpc/model/ApplicationModel.java | 50 ++- .../apache/dubbo/rpc/model/ConsumerModel.java | 32 +- .../apache/dubbo/rpc/model/ProviderModel.java | 33 +- .../invoker}/ProviderInvokerWrapper.java | 4 +- dubbo-rpc/dubbo-rpc-dubbo/pom.xml | 9 +- .../dubbo/telnet/InvokeTelnetHandler.java | 2 +- .../dubbo/telnet/ListTelnetHandler.java | 20 +- ...apache.dubbo.remoting.telnet.TelnetHandler | 3 +- .../rpc/protocol/dubbo/FutureFilterTest.java | 3 +- pom.xml | 1 - 219 files changed, 1477 insertions(+), 1350 deletions(-) rename {dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo => dubbo-common/src/main/java/org/apache/dubbo/common/config}/configcenter/AbstractDynamicConfigurationFactory.java (70%) rename {dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo => dubbo-common/src/main/java/org/apache/dubbo/common/config}/configcenter/ConfigChangeEvent.java (97%) rename {dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo => dubbo-common/src/main/java/org/apache/dubbo/common/config}/configcenter/ConfigChangeType.java (95%) rename {dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo => dubbo-common/src/main/java/org/apache/dubbo/common/config}/configcenter/ConfigurationListener.java (95%) rename {dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo => dubbo-common/src/main/java/org/apache/dubbo/common/config}/configcenter/Constants.java (95%) rename {dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo => dubbo-common/src/main/java/org/apache/dubbo/common/config}/configcenter/DynamicConfiguration.java (99%) rename {dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo => dubbo-common/src/main/java/org/apache/dubbo/common/config}/configcenter/DynamicConfigurationFactory.java (95%) rename {dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/support => dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter}/nop/NopDynamicConfiguration.java (91%) rename {dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/support => dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter}/nop/NopDynamicConfigurationFactory.java (83%) create mode 100644 dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/wrapper/CompositeDynamicConfiguration.java create mode 100644 dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory rename {dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo => dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config}/telnet/ShutdownTelnetHandler.java (98%) create mode 100644 dubbo-config/dubbo-config-api/src/main/resources/META-INF/services/org.apache.dubbo.remoting.telnet.TelnetHandler rename {dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc => dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config}/service/DemoException.java (96%) rename {dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc => dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config}/service/DemoService.java (96%) rename {dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc => dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config}/service/DemoServiceImpl.java (96%) rename {dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc => dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config}/service/GenericServiceTest.java (99%) rename {dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc => dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config}/service/User.java (97%) rename {dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo => dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config}/telnet/ShutdownTelnetHandlerTest.java (97%) rename {dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc => dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config}/validation/ValidationParameter.java (98%) rename {dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc => dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config}/validation/ValidationService.java (98%) rename {dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc => dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config}/validation/ValidationServiceImpl.java (96%) rename {dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc => dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config}/validation/ValidationTest.java (99%) delete mode 100644 dubbo-configcenter/dubbo-configcenter-api/pom.xml delete mode 100644 dubbo-configcenter/dubbo-configcenter-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.configcenter.DynamicConfigurationFactory delete mode 100644 dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/mock/AbstractDynamicConfigurationTest.java delete mode 100644 dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/mock/MockDynamicConfiguration.java delete mode 100644 dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfigurationTest.java delete mode 100644 dubbo-configcenter/dubbo-configcenter-api/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.configcenter.DynamicConfigurationFactory rename dubbo-configcenter/dubbo-configcenter-apollo/src/main/resources/META-INF/dubbo/internal/{org.apache.dubbo.configcenter.DynamicConfigurationFactory => org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory} (100%) rename dubbo-configcenter/dubbo-configcenter-consul/src/main/resources/META-INF/dubbo/internal/{org.apache.dubbo.configcenter.DynamicConfigurationFactory => org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory} (100%) rename dubbo-configcenter/dubbo-configcenter-etcd/src/main/resources/META-INF/dubbo/internal/{org.apache.dubbo.configcenter.DynamicConfigurationFactory => org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory} (100%) rename dubbo-configcenter/dubbo-configcenter-nacos/src/main/resources/META-INF/dubbo/internal/{org.apache.dubbo.configcenter.DynamicConfigurationFactory => org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory} (100%) rename dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/resources/META-INF/dubbo/internal/{org.apache.dubbo.configcenter.DynamicConfigurationFactory => org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory} (100%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/pom.xml (50%) rename dubbo-metadata/{ => dubbo-metadata-api}/src/main/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMapping.java (98%) rename dubbo-metadata/{ => dubbo-metadata-api}/src/main/java/org/apache/dubbo/metadata/MetadataService.java (95%) rename dubbo-metadata/{ => dubbo-metadata-api}/src/main/java/org/apache/dubbo/metadata/MetadataServiceExporter.java (100%) rename dubbo-metadata/{ => dubbo-metadata-api}/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java (100%) rename dubbo-metadata/{src/main/java/org/apache/dubbo/metadata/LocalMetadataService.java => dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/WritableMetadataService.java} (79%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/main/java/org/apache/dubbo/metadata/definition/ServiceDefinitionBuilder.java (100%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/main/java/org/apache/dubbo/metadata/definition/TypeDefinitionBuilder.java (100%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/main/java/org/apache/dubbo/metadata/definition/builder/ArrayTypeBuilder.java (100%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/main/java/org/apache/dubbo/metadata/definition/builder/CollectionTypeBuilder.java (100%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/main/java/org/apache/dubbo/metadata/definition/builder/DefaultTypeBuilder.java (100%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/main/java/org/apache/dubbo/metadata/definition/builder/EnumTypeBuilder.java (100%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/main/java/org/apache/dubbo/metadata/definition/builder/MapTypeBuilder.java (100%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/main/java/org/apache/dubbo/metadata/definition/builder/TypeBuilder.java (100%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/main/java/org/apache/dubbo/metadata/definition/model/FullServiceDefinition.java (100%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/main/java/org/apache/dubbo/metadata/definition/model/MethodDefinition.java (97%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/main/java/org/apache/dubbo/metadata/definition/model/ServiceDefinition.java (97%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/main/java/org/apache/dubbo/metadata/definition/model/TypeDefinition.java (97%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/main/java/org/apache/dubbo/metadata/definition/util/ClassUtils.java (100%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/main/java/org/apache/dubbo/metadata/definition/util/JaketConfigurationUtils.java (100%) rename dubbo-metadata/{src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java => dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/store/InMemoryWritableMetadataService.java} (76%) rename dubbo-metadata/{ => dubbo-metadata-api}/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.ServiceNameMapping (100%) create mode 100644 dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.WritableMetadataService rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.definition.builder.TypeBuilder (100%) rename dubbo-metadata/{ => dubbo-metadata-api}/src/test/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMappingTest.java (96%) rename dubbo-metadata/{src/test/java/org/apache/dubbo/metadata/InMemoryLocalMetadataServiceTest.java => dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/InMemoryWritableMetadataServiceTest.java} (95%) rename dubbo-metadata/{ => dubbo-metadata-api}/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java (82%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/test/java/org/apache/dubbo/metadata/definition/MetadataTest.java (100%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/test/java/org/apache/dubbo/metadata/definition/MetadataUtils.java (100%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/test/java/org/apache/dubbo/metadata/definition/ServiceDefinitionBuildderTest.java (100%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/test/java/org/apache/dubbo/metadata/definition/common/ClassExtendsMap.java (100%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/test/java/org/apache/dubbo/metadata/definition/common/ColorEnum.java (100%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/test/java/org/apache/dubbo/metadata/definition/common/OuterClass.java (100%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/test/java/org/apache/dubbo/metadata/definition/common/ResultWithRawCollections.java (100%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/test/java/org/apache/dubbo/metadata/definition/common/TestService.java (100%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/test/java/org/apache/dubbo/metadata/definition/service/ComplexObject.java (100%) rename {dubbo-metadata-report/dubbo-metadata-definition => dubbo-metadata/dubbo-metadata-api}/src/test/java/org/apache/dubbo/metadata/definition/service/DemoService.java (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-api/pom.xml (97%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java (86%) rename dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/MetadataReportService.java => dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/RemoteWritableMetadataService.java (56%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/store/MetadataReport.java (65%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/store/MetadataReportFactory.java (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java (94%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactory.java (93%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/Constants.java (100%) create mode 100644 dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.WritableMetadataService rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/identifier/MetadataIdentifierTest.java (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/InterfaceNameTestService.java (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/InterfaceNameTestService2.java (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/MetadataReportServiceTest.java (95%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/RetryTestService.java (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReport4Test.java (77%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReportFactory4Test.java (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactoryTest.java (88%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportTest.java (90%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-api/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-consul/pom.xml (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java (76%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReportFactory.java (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-etcd/pom.xml (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java (82%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportFactory.java (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadata4TstService.java (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-nacos/pom.xml (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java (87%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadata4TstService.java (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-redis/pom.xml (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java (93%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportFactory.java (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-redis/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadata4TstService.java (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-zookeeper/pom.xml (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java (88%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportFactory.java (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-zookeeper/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport4TstService.java (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportTest.java (100%) rename {dubbo-metadata-report => dubbo-metadata/dubbo-metadata-report}/pom.xml (94%) delete mode 100644 dubbo-metadata/src/main/java/org/apache/dubbo/metadata/DefaultMetadataServiceProxyFactory.java delete mode 100644 dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceProxyFactory.java delete mode 100644 dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.LocalMetadataService rename dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/{ => proxy}/DefaultMetadataServiceProxyFactory.java (97%) rename dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/{ => proxy}/MetadataServiceProxyFactory.java (88%) rename dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/mock/MockDynamicConfigurationFactory.java => dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/proxy/RemoteMetadataServiceProxyFactory.java (64%) delete mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ConsumerInvokerWrapper.java delete mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ProviderConsumerRegTable.java delete mode 100644 dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.metadata.MetadataServiceProxyFactory create mode 100644 dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.metadata.proxy.MetadataServiceProxyFactory rename {dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support => dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/invoker}/ProviderInvokerWrapper.java (95%) diff --git a/dubbo-all/pom.xml b/dubbo-all/pom.xml index eaf17722461..b47d580e0ab 100644 --- a/dubbo-all/pom.xml +++ b/dubbo-all/pom.xml @@ -408,13 +408,6 @@ compile true - - org.apache.dubbo - dubbo-configcenter-api - ${project.version} - compile - true - org.apache.dubbo dubbo-configcenter-zookeeper @@ -464,6 +457,13 @@ true + + org.apache.dubbo + dubbo-metadata-api + ${project.version} + compile + true + org.apache.dubbo dubbo-metadata-report-api @@ -516,14 +516,6 @@ true - - org.apache.dubbo - dubbo-metadata - ${project.version} - compile - true - - org.springframework @@ -640,13 +632,13 @@ org.apache.dubbo:dubbo-serialization-protostuff org.apache.dubbo:dubbo-serialization-gson org.apache.dubbo:dubbo-serialization-googlePb - 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-api org.apache.dubbo:dubbo-metadata-definition org.apache.dubbo:dubbo-metadata-report-redis @@ -778,7 +770,7 @@ - META-INF/dubbo/internal/org.apache.dubbo.configcenter.DynamicConfigurationFactory + META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory diff --git a/dubbo-bom/pom.xml b/dubbo-bom/pom.xml index 8b69673ec9f..202af02701f 100644 --- a/dubbo-bom/pom.xml +++ b/dubbo-bom/pom.xml @@ -362,11 +362,22 @@ dubbo-compatible ${project.version} + + + org.apache.dubbo + dubbo-metadata-api + ${project.version} + org.apache.dubbo dubbo-metadata-report-api ${project.version} + + org.apache.dubbo + dubbo-metadata-definition + ${project.version} + org.apache.dubbo dubbo-metadata-report-zookeeper @@ -392,11 +403,8 @@ dubbo-metadata-report-nacos ${project.version} - - org.apache.dubbo - dubbo-configcenter-api - ${project.version} - + + org.apache.dubbo dubbo-configcenter-zookeeper @@ -422,11 +430,6 @@ dubbo-configcenter-nacos ${project.version} - - org.apache.dubbo - dubbo-metadata-definition - ${project.version} - diff --git a/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java index c6c26062b64..76e520070cc 100644 --- a/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java +++ b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java @@ -17,19 +17,31 @@ package org.apache.dubbo.bootstrap; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.config.Environment; +import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; +import org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory; +import org.apache.dubbo.common.config.configcenter.wrapper.CompositeDynamicConfiguration; +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.common.utils.CollectionUtils; +import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.AbstractConfig; -import org.apache.dubbo.config.AbstractInterfaceConfig; import org.apache.dubbo.config.ApplicationConfig; +import org.apache.dubbo.config.ConfigCenterConfig; +import org.apache.dubbo.config.ConsumerConfig; +import org.apache.dubbo.config.DubboShutdownHook; +import org.apache.dubbo.config.MetadataReportConfig; import org.apache.dubbo.config.ProtocolConfig; +import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.builders.AbstractBuilder; import org.apache.dubbo.config.builders.ApplicationBuilder; +import org.apache.dubbo.config.builders.ConsumerBuilder; import org.apache.dubbo.config.builders.ProtocolBuilder; +import org.apache.dubbo.config.builders.ProviderBuilder; import org.apache.dubbo.config.builders.ReferenceBuilder; import org.apache.dubbo.config.builders.RegistryBuilder; import org.apache.dubbo.config.builders.ServiceBuilder; @@ -37,16 +49,18 @@ import org.apache.dubbo.config.metadata.ConfigurableMetadataServiceExporter; import org.apache.dubbo.event.EventDispatcher; import org.apache.dubbo.event.EventListener; -import org.apache.dubbo.metadata.MetadataServiceExporter; +import org.apache.dubbo.metadata.integration.RemoteWritableMetadataService; 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.support.ServiceOrientedRegistry; +import java.io.IOException; +import java.util.ArrayList; import java.util.HashMap; -import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Condition; @@ -55,12 +69,9 @@ import java.util.function.Consumer; import java.util.stream.Collectors; -import static java.util.Collections.emptyMap; import static java.util.concurrent.Executors.newSingleThreadExecutor; +import static org.apache.dubbo.common.config.ConfigurationUtils.parseProperties; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; -import static org.apache.dubbo.common.utils.StringUtils.isBlank; -import static org.apache.dubbo.common.utils.StringUtils.split; -import static org.apache.dubbo.common.utils.StringUtils.trim; import static org.apache.dubbo.registry.support.AbstractRegistryFactory.getRegistries; /** @@ -82,8 +93,6 @@ public class DubboBootstrap { private final Logger logger = LoggerFactory.getLogger(getClass()); - private final MetadataServiceExporter metadataServiceExporter = new ConfigurableMetadataServiceExporter(); - private final AtomicBoolean awaited = new AtomicBoolean(false); private final Lock lock = new ReentrantLock(); @@ -112,6 +121,10 @@ public class DubboBootstrap { private ApplicationBuilder applicationBuilder; + private ConsumerBuilder consumerBuilder; + + private ProviderBuilder providerBuilder; + private Map registryBuilders = new HashMap<>(); private Map protocolBuilders = new HashMap<>(); @@ -120,70 +133,88 @@ public class DubboBootstrap { private Map> referenceBuilders = new HashMap<>(); - /** - * The global {@link ApplicationConfig} - */ - private ApplicationConfig applicationConfig; + public DubboBootstrap() { + DubboShutdownHook.getDubboShutdownHook().register(); + } /** - * the global {@link RegistryConfig registries} + * Set only register provider or not + * + * @param onlyRegisterProvider if true, only register the provider and reduce the registries' load. + * @return {@link DubboBootstrap} */ - private Map registryConfigs = emptyMap(); + public DubboBootstrap onlyRegisterProvider(boolean onlyRegisterProvider) { + this.onlyRegisterProvider = onlyRegisterProvider; + return this; + } - /** - * the global {@link RegistryConfig registries} - */ - private Map protocolConfigs = emptyMap(); + /* accept Config instance */ + public DubboBootstrap application(ApplicationConfig applicationConfig) { + ConfigManager.getInstance().setApplication(applicationConfig); + return this; + } - /** - * the global {@link ServiceConfig services} - */ - private Map> serviceConfigs = emptyMap(); + public DubboBootstrap configCenter(ConfigCenterConfig configCenterConfig) { + ConfigManager.getInstance().addConfigCenter(configCenterConfig); + return this; + } - /** - * the global {@link ReferenceConfig references} - */ - private Map> referenceConfigs = new HashMap<>(); + public DubboBootstrap configCenter(List configCenterConfigs) { + ConfigManager.getInstance().addConfigCenter(configCenterConfigs); + return this; + } - public ApplicationSettings application(String name) { - return new ApplicationSettings(initApplicationBuilder(name), this); + public DubboBootstrap metadataReport(MetadataReportConfig metadataReportConfig) { + ConfigManager.getInstance().addMetadataReport(metadataReportConfig); + return this; } - public RegistrySettings registry() { - return registry(DEFAULT_REGISTRY_ID); + public DubboBootstrap metadataReport(List metadataReportConfigs) { + ConfigManager.getInstance().addMetadataReport(metadataReportConfigs); + return this; } - public RegistrySettings registry(String id) { - return new RegistrySettings(initRegistryBuilder(id), this); + public DubboBootstrap registry(RegistryConfig registryConfig) { + ConfigManager.getInstance().addRegistry(registryConfig, true); + return this; } - public ProtocolSettings protocol() { - return protocol(DEFAULT_PROTOCOL_ID); + public DubboBootstrap registry(List registryConfigs) { + ConfigManager.getInstance().addRegistries(registryConfigs, true); + return this; } - public ProtocolSettings protocol(String id) { - return new ProtocolSettings(initProtocolBuilder(id), this); + public DubboBootstrap protocol(ProtocolConfig protocolConfig) { + ConfigManager.getInstance().addProtocol(protocolConfig, true); + return this; } - public ServiceSettings service(String id) { - return new ServiceSettings(initServiceBuilder(id), this); + public DubboBootstrap protocols(List protocolConfigs) { + ConfigManager.getInstance().addProtocols(protocolConfigs, true); + return this; } - public ReferenceSettings reference(String id) { - return new ReferenceSettings<>(initReferenceBuilder(id), this); + public DubboBootstrap consumer(ConsumerConfig consumerConfig) { + ConfigManager.getInstance().addConsumer(consumerConfig); + return this; } - /** - * Set only register provider or not - * - * @param onlyRegisterProvider if true, only register the provider and reduce the registries' load. - * @return {@link DubboBootstrap} - */ - public DubboBootstrap onlyRegisterProvider(boolean onlyRegisterProvider) { - this.onlyRegisterProvider = onlyRegisterProvider; + public DubboBootstrap provider(ProviderConfig providerConfig) { + ConfigManager.getInstance().addProvider(providerConfig); + return this; + } + + public DubboBootstrap service(ServiceConfig serviceConfig) { + ConfigManager.getInstance().addService(serviceConfig); + return this; + } + + public DubboBootstrap reference(ReferenceConfig referenceConfig) { + ConfigManager.getInstance().addReference(referenceConfig); return this; } + /* accept builder functional interface */ public DubboBootstrap application(String name, Consumer builder) { initApplicationBuilder(name); builder.accept(applicationBuilder); @@ -219,18 +250,31 @@ public void init() { return; } - initApplicationConfig(); + buildApplicationConfig(); - initRegistryConfigs(); + buildRegistryConfigs(); - initProtocolConfigs(); + buildProtocolConfigs(); - initServiceConfigs(); + buildServiceConfigs(); - initReferenceConfigs(); + buildReferenceConfigs(); clearBuilders(); + startConfigCenter(); + startMetadataReport(); + + loadRemoteConfigs(); + useRegistryAsConfigCenterIfNecessary(); + +// checkApplication(); +// checkProvider(); +// chcckConsumer(); +// checkRegistry(); +// checkProtocol(); +// checkMonitor(); + initialized = true; if (logger.isInfoEnabled()) { @@ -238,26 +282,67 @@ public void init() { } } - /** - * Get the {@link ServiceConfig} by specified id - * - * @param id The {@link ServiceConfig#getId() id} of {@link ServiceConfig} - * @param the type of service interface - * @return null if not found - */ - public ServiceConfig serviceConfig(String id) { - return (ServiceConfig) serviceConfigs.get(id); + private void loadRemoteConfigs() { + ConfigManager configManager = ConfigManager.getInstance(); + + // registry ids to registry configs + List tmpRegistries = new ArrayList<>(); + Set registryIds = configManager.getRegistryIds(); + registryIds.forEach(id -> { + if (tmpRegistries.stream().noneMatch(reg -> reg.getId().equals(id))) { + tmpRegistries.add(configManager.getRegistry(id).orElseGet(() -> { + RegistryConfig registryConfig = new RegistryConfig(); + registryConfig.setId(id); + registryConfig.refresh(); + return registryConfig; + })); + } + }); + + configManager.addRegistries(tmpRegistries, true); + + // protocol ids to protocol configs + List tmpProtocols = new ArrayList<>(); + Set protocolIds = configManager.getProtocolIds(); + protocolIds.forEach(id -> { + if (tmpProtocols.stream().noneMatch(prot -> prot.getId().equals(id))) { + tmpProtocols.add(configManager.getProtocol(id).orElseGet(() -> { + ProtocolConfig protocolConfig = new ProtocolConfig(); + protocolConfig.setId(id); + protocolConfig.refresh(); + return protocolConfig; + })); + } + }); + + configManager.addProtocols(tmpProtocols, true); } /** - * Get the {@link ReferenceConfig} by specified id - * - * @param id The {@link ReferenceConfig#getId() id} of {@link ReferenceConfig} - * @param the type of service interface - * @return null if not found + * For compatibility purpose, use registry as the default config center when the registry protocol is zookeeper and + * there's no config center specified explicitly. */ - public ReferenceConfig referenceConfig(String id) { - return (ReferenceConfig) referenceConfigs.get(id); + private void useRegistryAsConfigCenterIfNecessary() { + ConfigManager configManager = ConfigManager.getInstance(); + configManager.getDefaultRegistries().ifPresent(registryConfigs -> { + for (RegistryConfig registryConfig : registryConfigs) { + if (registryConfig != null && registryConfig.isZookeeperProtocol()) { + // we use the loading status of DynamicConfiguration to decide whether ConfigCenter has been initiated. + Environment.getInstance().getDynamicConfiguration().orElseGet(() -> { + Set configCenters = configManager.getConfigCenters(); + if (CollectionUtils.isEmpty(configCenters)) { + ConfigCenterConfig cc = new ConfigCenterConfig(); + cc.setProtocol(registryConfig.getProtocol()); + cc.setAddress(registryConfig.getAddress()); + cc.setHighestPriority(false); + configManager.addConfigCenter(cc); + } + return null; + }); + } + } + startConfigCenter(); + }); } private List getServiceDiscoveries() { @@ -282,11 +367,17 @@ public DubboBootstrap start() { exportServices(); // Not only provider register and some services are exported - if (!onlyRegisterProvider && !serviceConfigs.isEmpty()) { + if (!onlyRegisterProvider && !ConfigManager.getInstance().getServiceConfigs().isEmpty()) { /** * export {@link MetadataService} */ - List exportedURLs = exportMetadataService(applicationConfig, registryConfigs, protocolConfigs); + ConfigManager configManager = ConfigManager.getInstance(); + // TODO, only export to default registry? + List exportedURLs = exportMetadataService ( + configManager.getApplication().orElseThrow(() -> new IllegalStateException("ApplicationConfig cannot be null")), + configManager.getDefaultRegistries().orElseThrow(() -> new IllegalStateException("No default RegistryConfig")), + configManager.getDefaultProtocols().orElseThrow(() -> new IllegalStateException("No default ProtocolConfig")) + ); /** * Register the local {@link ServiceInstance} @@ -357,6 +448,7 @@ public boolean isStarted() { return started; } + /* serve for builder apis, begin */ private ApplicationBuilder initApplicationBuilder(String name) { applicationBuilder = new ApplicationBuilder().name(name); return applicationBuilder; @@ -394,21 +486,69 @@ private ReferenceBuilder initReferenceBuilder(String id) { return referenceBuilders.computeIfAbsent(id, this::createReferenceBuilder); } - private void initApplicationConfig() { - this.applicationConfig = buildApplicationConfig(); + /* serve for builder apis, end */ + + private void startMetadataReport() { + // FIXME, multiple metadata config support. + Set metadataReportConfigs = ConfigManager.getInstance().getMetadataConfigs(); + if (CollectionUtils.isEmpty(metadataReportConfigs)) { + return; + } + MetadataReportConfig metadataReportConfig = metadataReportConfigs.iterator().next(); + if (!metadataReportConfig.isValid()) { + return; + } + + RemoteWritableMetadataService.instance(metadataReportConfig::toUrl); } - private void initRegistryConfigs() { - this.registryConfigs = buildRegistryConfigs(); + private void startConfigCenter() { + Set configCenters = ConfigManager.getInstance().getConfigCenters(); + + if (CollectionUtils.isNotEmpty(configCenters)) { + CompositeDynamicConfiguration compositeDynamicConfiguration = new CompositeDynamicConfiguration(); + for (ConfigCenterConfig configCenter : configCenters) { + configCenter.refresh(); + compositeDynamicConfiguration.addConfiguration(prepareEnvironment(configCenter)); + } + Environment.getInstance().setDynamicConfiguration(compositeDynamicConfiguration); + } + ConfigManager.getInstance().refreshAll(); } - private void initProtocolConfigs() { - this.protocolConfigs = buildProtocolConfigs(); + private DynamicConfiguration prepareEnvironment(ConfigCenterConfig configCenter) { + if (configCenter.isValid()) { + if (!configCenter.checkOrUpdateInited()) { + return null; + } + DynamicConfiguration dynamicConfiguration = getDynamicConfiguration(configCenter.toUrl()); + String configContent = dynamicConfiguration.getConfigs(configCenter.getConfigFile(), configCenter.getGroup()); + + String appGroup = ConfigManager.getInstance().getApplication().orElse(new ApplicationConfig()).getName(); + String appConfigContent = null; + if (StringUtils.isNotEmpty(appGroup)) { + appConfigContent = dynamicConfiguration.getConfigs + (StringUtils.isNotEmpty(configCenter.getAppConfigFile()) ? configCenter.getAppConfigFile() : configCenter.getConfigFile(), + appGroup + ); + } + try { + Environment.getInstance().setConfigCenterFirst(configCenter.isHighestPriority()); + Environment.getInstance().updateExternalConfigurationMap(parseProperties(configContent)); + Environment.getInstance().updateAppExternalConfigurationMap(parseProperties(appConfigContent)); + } catch (IOException e) { + throw new IllegalStateException("Failed to parse configurations from Config Center.", e); + } + return dynamicConfiguration; + } + return null; } - private void initReferenceConfigs() { - this.referenceConfigs = buildReferenceConfigs(); - this.referenceConfigs.values().forEach(this::initReferenceConfig); + private DynamicConfiguration getDynamicConfiguration(URL url) { + DynamicConfigurationFactory factory = ExtensionLoader + .getExtensionLoader(DynamicConfigurationFactory.class) + .getExtension(url.getProtocol()); + return factory.getDynamicConfiguration(url); } /** @@ -422,103 +562,49 @@ public DubboBootstrap addEventListener(EventListener listener) { return this; } - private void initServiceConfigs() { - this.serviceConfigs = buildServiceConfigs(); - this.serviceConfigs.values().forEach(this::initServiceConfig); - } - private List exportMetadataService(ApplicationConfig applicationConfig, - Map globalRegistryConfigs, - Map globalProtocolConfigs) { + List globalRegistryConfigs, + List globalProtocolConfigs) { ConfigurableMetadataServiceExporter exporter = new ConfigurableMetadataServiceExporter(); exporter.setApplicationConfig(applicationConfig); - exporter.setRegistries(globalRegistryConfigs.values()); - exporter.setProtocols(globalProtocolConfigs.values()); + exporter.setRegistries(globalRegistryConfigs); + exporter.setProtocols(globalProtocolConfigs); return exporter.export(); } - private ApplicationConfig buildApplicationConfig() { - return applicationBuilder.build(); + private void buildApplicationConfig() { + ApplicationConfig applicationConfig = null; + if (applicationBuilder != null) { + applicationConfig = applicationBuilder.build(); + } + ConfigManager.getInstance().setApplication(applicationConfig); } - private Map buildProtocolConfigs() { - return buildConfigs(protocolBuilders); + private void buildProtocolConfigs() { + List protocolConfigs = buildConfigs(protocolBuilders); + ConfigManager.getInstance().addProtocols(protocolConfigs, true); } - private Map buildRegistryConfigs() { - return buildConfigs(registryBuilders); + private void buildRegistryConfigs() { + List registryConfigs = buildConfigs(registryBuilders); + ConfigManager.getInstance().addRegistries(registryConfigs, true); } - private Map> buildServiceConfigs() { - return buildConfigs(serviceBuilders); + private void buildServiceConfigs() { + List> serviceConfigs = buildConfigs(serviceBuilders); + serviceConfigs.forEach(ConfigManager.getInstance()::addService); } - private Map> buildReferenceConfigs() { - return buildConfigs(referenceBuilders); + private void buildReferenceConfigs() { + List> referenceConfigs = buildConfigs(referenceBuilders); + referenceConfigs.forEach(ConfigManager.getInstance()::addReference); } private void exportServices() { - serviceConfigs.values().forEach(this::exportServiceConfig); - } - - private void initServiceConfig(ServiceConfig serviceConfig) { - initConfig(serviceConfig); - initProtocols(serviceConfig); - } - - private void initReferenceConfig(ReferenceConfig referenceConfig) { - initConfig(referenceConfig); - } - - private void initConfig(AbstractInterfaceConfig config) { - initApplication(config); - initRegistries(config); - } - - private void initApplication(AbstractInterfaceConfig config) { - if (config.getApplication() == null) { - config.setApplication(applicationConfig); - } - } - - private void initRegistries(AbstractInterfaceConfig config) { - List registries = config.getRegistries(); - if (CollectionUtils.isEmpty(registries)) { // If no registry present - registries = new LinkedList<>(); - String registerIds = config.getRegistryIds(); - if (!isBlank(registerIds)) { - for (String id : split(registerIds, ',')) { - RegistryConfig registryConfig = registryConfigs.get(trim(id)); - registries.add(registryConfig); - } - } - if (registries.isEmpty()) { // If empty, add all global registries - registries.addAll(registryConfigs.values()); - } - - config.setRegistries(registries); - } + ConfigManager.getInstance().getServiceConfigs().forEach(this::exportServiceConfig); } - private void initProtocols(ServiceConfig serviceConfig) { - List protocols = serviceConfig.getProtocols(); - if (CollectionUtils.isEmpty(protocols)) { // If no protocols present - protocols = new LinkedList<>(); - String protocolIds = serviceConfig.getProtocolIds(); - if (!isBlank(protocolIds)) { - for (String id : split(protocolIds, ',')) { - ProtocolConfig protocol = protocolConfigs.get(trim(id)); - protocols.add(protocol); - } - } - if (protocols.isEmpty()) { // If empty, add all global protocols - protocols.addAll(protocolConfigs.values()); - } - serviceConfig.setProtocols(protocols); - } - } - - private void exportServiceConfig(ServiceConfig serviceConfig) { + public void exportServiceConfig(ServiceConfig serviceConfig) { serviceConfig.export(); } @@ -563,14 +649,14 @@ private void destroy() { } private void destroyProtocolConfigs() { - protocolConfigs.values().forEach(ProtocolConfig::destroy); + ConfigManager.getInstance().getProtocols().values().forEach(ProtocolConfig::destroy); if (logger.isDebugEnabled()) { logger.debug(NAME + "'s all ProtocolConfigs have been destroyed."); } } private void destroyReferenceConfigs() { - referenceConfigs.values().forEach(ReferenceConfig::destroy); + ConfigManager.getInstance().getReferenceConfigs().forEach(ReferenceConfig::destroy); if (logger.isDebugEnabled()) { logger.debug(NAME + "'s all ReferenceConfigs have been destroyed."); } @@ -586,11 +672,7 @@ private void clear() { } private void clearConfigs() { - this.applicationConfig = null; - this.registryConfigs.clear(); - this.protocolConfigs.clear(); - this.serviceConfigs.clear(); - this.referenceConfigs.clear(); + ConfigManager.getInstance().clear(); if (logger.isDebugEnabled()) { logger.debug(NAME + "'s configs have been clear."); } @@ -634,10 +716,10 @@ private void executeMutually(Runnable runnable) { } } - private static Map buildConfigs(Map map) { - Map configs = new HashMap<>(); + private static List buildConfigs(Map map) { + List configs = new ArrayList<>(); map.entrySet().forEach(entry -> { - configs.put(entry.getKey(), (C) entry.getValue().build()); + configs.add((C) entry.getValue().build()); }); return configs; } diff --git a/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboBootstrapTest.java b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboBootstrapTest.java index 33344e2e102..302980a00fe 100644 --- a/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboBootstrapTest.java +++ b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboBootstrapTest.java @@ -16,6 +16,11 @@ */ package org.apache.dubbo.bootstrap; +import org.apache.dubbo.config.builders.ApplicationBuilder; +import org.apache.dubbo.config.builders.ProtocolBuilder; +import org.apache.dubbo.config.builders.RegistryBuilder; +import org.apache.dubbo.config.builders.ServiceBuilder; + import org.junit.jupiter.api.Test; import java.io.IOException; @@ -30,24 +35,13 @@ public class DubboBootstrapTest { @Test public void test() throws IOException { - DubboBootstrap bootstrap = new DubboBootstrap() - .application("dubbo-provider-demo") - .next() - .registry() - .address("zookeeper://127.0.0.1:2181?registry-type=service") - .next() - .protocol() - .name("dubbo") - .port(-1) - .next() - .service("test") - .interfaceClass(EchoService.class) - .ref(new EchoServiceImpl()) - .group("DEFAULT") - .version("1.0.0") - .next(); - - bootstrap.start(); + new DubboBootstrap() + .application(ApplicationBuilder.newBuilder().name("dubbo-provider-demo").build()) + .registry(RegistryBuilder.newBuilder().address("zookeeper://127.0.0.1:2181?registry-type=service&metadata=remote").build()) + .protocol(ProtocolBuilder.newBuilder().port(-1).name("dubbo").build()) + .service(ServiceBuilder.newBuilder().id("test").interfaceClass(EchoService.class).ref(new EchoServiceImpl()).build()) + .start() + .await(); System.in.read(); } diff --git a/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceConsumerBootstrap.java b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceConsumerBootstrap.java index d525ee2b344..ef1efd350d9 100644 --- a/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceConsumerBootstrap.java +++ b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceConsumerBootstrap.java @@ -16,10 +16,9 @@ */ package org.apache.dubbo.bootstrap; -import org.apache.dubbo.config.ReferenceConfig; - -import static org.apache.dubbo.bootstrap.EchoService.GROUP; -import static org.apache.dubbo.bootstrap.EchoService.VERSION; +import org.apache.dubbo.config.builders.ApplicationBuilder; +import org.apache.dubbo.config.builders.ReferenceBuilder; +import org.apache.dubbo.config.builders.RegistryBuilder; /** * Dubbo Provider Bootstrap @@ -31,28 +30,22 @@ public class DubboServiceConsumerBootstrap { public static void main(String[] args) throws Exception { DubboBootstrap bootstrap = new DubboBootstrap() - .application("dubbo-consumer-demo") - .next() - .registry() - .address("zookeeper://127.0.0.1:2181?registry-type=service&subscribed-services=dubbo-provider-demo") - .next() - .reference("ref") - .interfaceClass(EchoService.class) - .group(GROUP) - .version(VERSION) - .next() + .application(ApplicationBuilder.newBuilder().name("dubbo-consumer-demo").build()) + .registry(RegistryBuilder.newBuilder().address("zookeeper://127.0.0.1:2181?registry-type=service&subscribed-services=dubbo-provider-demo&metadata=remote").build()) + .reference(ReferenceBuilder.newBuilder().id("ref").interfaceClass(EchoService.class).build()) .onlyRegisterProvider(true) .start() .await(); - ReferenceConfig referenceConfig = bootstrap.referenceConfig("ref"); - - EchoService echoService = referenceConfig.get(); - - for (int i = 0; i < 500; i++) { - Thread.sleep(2000L); - System.out.println(echoService.echo("Hello,World")); - } + // TODO, +// ReferenceConfig referenceConfig = ReferenceConfigCache.getCache().get(EchoService.class.getName(), EchoService.class); +// +// EchoService echoService = referenceConfig.get(); +// +// for (int i = 0; i < 500; i++) { +// Thread.sleep(2000L); +// System.out.println(echoService.echo("Hello,World")); +// } } } diff --git a/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceProviderBootstrap.java b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceProviderBootstrap.java index 049cae84a39..e8499a20282 100644 --- a/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceProviderBootstrap.java +++ b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceProviderBootstrap.java @@ -16,10 +16,12 @@ */ package org.apache.dubbo.bootstrap; -import java.io.IOException; +import org.apache.dubbo.config.builders.ApplicationBuilder; +import org.apache.dubbo.config.builders.ProtocolBuilder; +import org.apache.dubbo.config.builders.RegistryBuilder; +import org.apache.dubbo.config.builders.ServiceBuilder; -import static org.apache.dubbo.bootstrap.EchoService.GROUP; -import static org.apache.dubbo.bootstrap.EchoService.VERSION; +import java.io.IOException; /** * Dubbo Provider Bootstrap @@ -31,21 +33,10 @@ public class DubboServiceProviderBootstrap { public static void main(String[] args) throws IOException { new DubboBootstrap() - .application("dubbo-provider-demo") - .next() - .registry() - .address("zookeeper://127.0.0.1:2181?registry-type=service") - .next() - .protocol() - .name("dubbo") - .port(-1) - .next() - .service("test") - .interfaceClass(EchoService.class) - .ref(new EchoServiceImpl()) - .group(GROUP) - .version(VERSION) - .next() + .application(ApplicationBuilder.newBuilder().name("dubbo-provider-demo").build()) + .registry(RegistryBuilder.newBuilder().address("zookeeper://127.0.0.1:2181?registry-type=service&metadata=remote").build()) + .protocol(ProtocolBuilder.newBuilder().port(-1).name("dubbo").build()) + .service(ServiceBuilder.newBuilder().id("test").interfaceClass(EchoService.class).ref(new EchoServiceImpl()).build()) .start() .await(); } diff --git a/dubbo-cluster/pom.xml b/dubbo-cluster/pom.xml index ff59682d847..864e7ccc77e 100644 --- a/dubbo-cluster/pom.xml +++ b/dubbo-cluster/pom.xml @@ -34,11 +34,6 @@ dubbo-rpc-api ${project.parent.version} - - org.apache.dubbo - dubbo-configcenter-api - ${project.parent.version} - org.yaml snakeyaml diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Directory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Directory.java index 67f021659e7..a03a78162b7 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Directory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Directory.java @@ -46,4 +46,6 @@ public interface Directory extends Node { */ List> list(Invocation invocation) throws RpcException; + List> getAllInvokers(); + } \ No newline at end of file diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectory.java index c5a26a3f7d3..0595c6366ef 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectory.java @@ -61,6 +61,11 @@ public Class getInterface() { return invokers.get(0).getInterface(); } + @Override + public List> getAllInvokers() { + return invokers; + } + @Override public boolean isAvailable() { if (isDestroyed()) { diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/AbstractRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/AbstractRouter.java index 657ad866c28..b848cb1edb5 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/AbstractRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/AbstractRouter.java @@ -17,7 +17,7 @@ package org.apache.dubbo.rpc.cluster.router; import org.apache.dubbo.common.URL; -import org.apache.dubbo.configcenter.DynamicConfiguration; +import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.rpc.cluster.Router; public abstract class AbstractRouter implements Router { diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppRouter.java index b334e377bb1..852da6be5de 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppRouter.java @@ -17,8 +17,8 @@ package org.apache.dubbo.rpc.cluster.router.condition.config; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.constants.CommonConstants; -import org.apache.dubbo.configcenter.DynamicConfiguration; /** * Application level router, "application.condition-router" diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppRouterFactory.java index 066f865b65f..067a5232086 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppRouterFactory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppRouterFactory.java @@ -17,8 +17,8 @@ package org.apache.dubbo.rpc.cluster.router.condition.config; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.configcenter.DynamicConfiguration; import org.apache.dubbo.rpc.cluster.Router; import org.apache.dubbo.rpc.cluster.RouterFactory; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ListenableRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ListenableRouter.java index 564f371eac0..5931e850f00 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ListenableRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ListenableRouter.java @@ -17,14 +17,14 @@ package org.apache.dubbo.rpc.cluster.router.condition.config; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.config.configcenter.ConfigChangeEvent; +import org.apache.dubbo.common.config.configcenter.ConfigChangeType; +import org.apache.dubbo.common.config.configcenter.ConfigurationListener; +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.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.configcenter.ConfigChangeEvent; -import org.apache.dubbo.configcenter.ConfigChangeType; -import org.apache.dubbo.configcenter.ConfigurationListener; -import org.apache.dubbo.configcenter.DynamicConfiguration; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceRouter.java index ed3748e0fd5..1bdf2612f95 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceRouter.java @@ -17,7 +17,7 @@ package org.apache.dubbo.rpc.cluster.router.condition.config; import org.apache.dubbo.common.URL; -import org.apache.dubbo.configcenter.DynamicConfiguration; +import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; /** * Service level router, "server-unique-name.condition-router" diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceRouterFactory.java index 18d4a1dd3e8..12911ac4406 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceRouterFactory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceRouterFactory.java @@ -17,8 +17,8 @@ package org.apache.dubbo.rpc.cluster.router.condition.config; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.configcenter.DynamicConfiguration; import org.apache.dubbo.rpc.cluster.CacheableRouterFactory; import org.apache.dubbo.rpc.cluster.Router; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java index c6387fe3fc5..d33d103d964 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouter.java @@ -17,16 +17,16 @@ package org.apache.dubbo.rpc.cluster.router.tag; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.config.configcenter.ConfigChangeEvent; +import org.apache.dubbo.common.config.configcenter.ConfigChangeType; +import org.apache.dubbo.common.config.configcenter.ConfigurationListener; +import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.constants.CommonConstants; 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.NetUtils; import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.configcenter.ConfigChangeEvent; -import org.apache.dubbo.configcenter.ConfigChangeType; -import org.apache.dubbo.configcenter.ConfigurationListener; -import org.apache.dubbo.configcenter.DynamicConfiguration; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; @@ -40,8 +40,8 @@ import java.util.function.Predicate; import java.util.stream.Collectors; -import static org.apache.dubbo.rpc.cluster.Constants.TAG_KEY; import static org.apache.dubbo.rpc.Constants.FORCE_USE_TAG; +import static org.apache.dubbo.rpc.cluster.Constants.TAG_KEY; /** * TagRouter, "application.tag-router" diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouterFactory.java index 7d3e013123f..0df085d6264 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouterFactory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagRouterFactory.java @@ -17,8 +17,8 @@ package org.apache.dubbo.rpc.cluster.router.tag; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.configcenter.DynamicConfiguration; import org.apache.dubbo.rpc.cluster.CacheableRouterFactory; import org.apache.dubbo.rpc.cluster.Router; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvoker.java index db2d401eba9..61ef95596ab 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvoker.java @@ -94,6 +94,10 @@ public boolean isAvailable() { return directory.isAvailable(); } + public Directory getDirectory() { + return directory; + } + @Override public void destroy() { if (destroyed.compareAndSet(false, true)) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Proxy.java b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Proxy.java index 2da28183504..cf335b49826 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Proxy.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Proxy.java @@ -155,7 +155,7 @@ public static Proxy getProxy(ClassLoader cl, Class... ics) { for (Method method : ics[i].getMethods()) { String desc = ReflectUtils.getDesc(method); - if (worked.contains(desc)) { + if (worked.contains(desc) || Modifier.isStatic(method.getModifiers())) { continue; } worked.add(desc); diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/AbstractDynamicConfigurationFactory.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfigurationFactory.java similarity index 70% rename from dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/AbstractDynamicConfigurationFactory.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfigurationFactory.java index 324f2cbef76..15b9145dfa3 100644 --- a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/AbstractDynamicConfigurationFactory.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfigurationFactory.java @@ -14,27 +14,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.configcenter; +package org.apache.dubbo.common.config.configcenter; import org.apache.dubbo.common.URL; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; + /** * */ public abstract class AbstractDynamicConfigurationFactory implements DynamicConfigurationFactory { - private volatile DynamicConfiguration dynamicConfiguration; + private volatile Map dynamicConfigurations = new ConcurrentHashMap<>(); @Override public DynamicConfiguration getDynamicConfiguration(URL url) { - if (dynamicConfiguration == null) { - synchronized (this) { - if (dynamicConfiguration == null) { - dynamicConfiguration = createDynamicConfiguration(url); - } - } - } - return dynamicConfiguration; + String key = url == null ? DEFAULT_KEY : url.getAddress(); + return dynamicConfigurations.computeIfAbsent(key, k -> createDynamicConfiguration(url)); } protected abstract DynamicConfiguration createDynamicConfiguration(URL url); diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/ConfigChangeEvent.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigChangeEvent.java similarity index 97% rename from dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/ConfigChangeEvent.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigChangeEvent.java index cdedd15e34e..751746f199d 100644 --- a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/ConfigChangeEvent.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigChangeEvent.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.configcenter; +package org.apache.dubbo.common.config.configcenter; /** * Config change event, immutable. diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/ConfigChangeType.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigChangeType.java similarity index 95% rename from dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/ConfigChangeType.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigChangeType.java index e810ddce600..fe43a2b1ab1 100644 --- a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/ConfigChangeType.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigChangeType.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.configcenter; +package org.apache.dubbo.common.config.configcenter; /** * Config change event type diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/ConfigurationListener.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigurationListener.java similarity index 95% rename from dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/ConfigurationListener.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigurationListener.java index 7c7a1310d46..09746c5bcee 100644 --- a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/ConfigurationListener.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigurationListener.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.configcenter; +package org.apache.dubbo.common.config.configcenter; /** * Config listener, will get notified when the config it listens on changes. diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/Constants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/Constants.java similarity index 95% rename from dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/Constants.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/Constants.java index fcf1a51fc56..d85f86b11cf 100644 --- a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/Constants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/Constants.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.configcenter; +package org.apache.dubbo.common.config.configcenter; public interface Constants { String CONFIG_CLUSTER_KEY = "config.cluster"; diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/DynamicConfiguration.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/DynamicConfiguration.java similarity index 99% rename from dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/DynamicConfiguration.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/DynamicConfiguration.java index 804dd8bd568..26e831d17e7 100644 --- a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/DynamicConfiguration.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/DynamicConfiguration.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.configcenter; +package org.apache.dubbo.common.config.configcenter; import org.apache.dubbo.common.config.Configuration; import org.apache.dubbo.common.config.Environment; diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/DynamicConfigurationFactory.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/DynamicConfigurationFactory.java similarity index 95% rename from dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/DynamicConfigurationFactory.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/DynamicConfigurationFactory.java index 4e0b9b521c8..59c27ce0cb4 100644 --- a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/DynamicConfigurationFactory.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/DynamicConfigurationFactory.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.configcenter; +package org.apache.dubbo.common.config.configcenter; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.SPI; diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfiguration.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/nop/NopDynamicConfiguration.java similarity index 91% rename from dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfiguration.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/nop/NopDynamicConfiguration.java index 56e1191aa5f..3e3f0551b9b 100644 --- a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfiguration.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/nop/NopDynamicConfiguration.java @@ -14,11 +14,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.configcenter.support.nop; +package org.apache.dubbo.common.config.configcenter.nop; import org.apache.dubbo.common.URL; -import org.apache.dubbo.configcenter.ConfigurationListener; -import org.apache.dubbo.configcenter.DynamicConfiguration; +import org.apache.dubbo.common.config.configcenter.ConfigurationListener; +import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import java.util.SortedSet; diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfigurationFactory.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/nop/NopDynamicConfigurationFactory.java similarity index 83% rename from dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfigurationFactory.java rename to dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/nop/NopDynamicConfigurationFactory.java index 0b6aee6a351..bd45e7f736e 100644 --- a/dubbo-configcenter/dubbo-configcenter-api/src/main/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfigurationFactory.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/nop/NopDynamicConfigurationFactory.java @@ -14,11 +14,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.configcenter.support.nop; +package org.apache.dubbo.common.config.configcenter.nop; import org.apache.dubbo.common.URL; -import org.apache.dubbo.configcenter.AbstractDynamicConfigurationFactory; -import org.apache.dubbo.configcenter.DynamicConfiguration; +import org.apache.dubbo.common.config.configcenter.AbstractDynamicConfigurationFactory; +import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; /** * diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/wrapper/CompositeDynamicConfiguration.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/wrapper/CompositeDynamicConfiguration.java new file mode 100644 index 00000000000..7f98d383d7d --- /dev/null +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/wrapper/CompositeDynamicConfiguration.java @@ -0,0 +1,98 @@ +/* + * 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.common.config.configcenter.wrapper; + +import org.apache.dubbo.common.config.configcenter.ConfigurationListener; +import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; + +import java.util.HashSet; +import java.util.Set; +import java.util.SortedMap; +import java.util.SortedSet; +import java.util.function.Consumer; +import java.util.function.Function; + +/** + * support multiple config center, simply iterating each underlying config center. + */ +public class CompositeDynamicConfiguration implements DynamicConfiguration { + + public static final String NAME = "COMPOSITE"; + + private Set configurations = new HashSet<>(); + + public void addConfiguration(DynamicConfiguration configuration) { + this.configurations.add(configuration); + } + + @Override + public void addListener(String key, String group, ConfigurationListener listener) { + iterateListenerOperation(configuration -> configuration.addListener(key, group, listener)); + } + + @Override + public void removeListener(String key, String group, ConfigurationListener listener) { + iterateListenerOperation(configuration -> configuration.removeListener(key, group, listener)); + } + + @Override + public String getConfig(String key, String group, long timeout) throws IllegalStateException { + return (String) iterateConfigOperation(configuration -> configuration.getConfig(key, group, timeout)); + } + + @Override + public String getConfigs(String key, String group, long timeout) throws IllegalStateException { + return (String) iterateConfigOperation(configuration -> configuration.getConfigs(key, group, timeout)); + } + + @Override + public Object getInternalProperty(String key) { + return iterateConfigOperation(configuration -> configuration.getInternalProperty(key)); + } + + @Override + public boolean publishConfig(String key, String group, String content) throws UnsupportedOperationException { + return (boolean) iterateConfigOperation(configuration -> configuration.publishConfig(key, group, content)); + } + + @Override + public SortedSet getConfigKeys(String group) throws UnsupportedOperationException { + return (SortedSet) iterateConfigOperation(configuration -> configuration.getConfigKeys(group)); + } + + @Override + public SortedMap getConfigs(String group) throws UnsupportedOperationException { + return (SortedMap) iterateConfigOperation(configuration -> configuration.getConfigs(group)); + } + + private void iterateListenerOperation(Consumer consumer) { + for (DynamicConfiguration configuration : configurations) { + consumer.accept(configuration); + } + } + + private Object iterateConfigOperation(Function func) { + Object value = null; + for (DynamicConfiguration configuration : configurations) { + value = func.apply(configuration); + if (value != null) { + break; + } + } + return value; + } +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java index 5e2e55047f8..661dad4c5aa 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java @@ -153,6 +153,10 @@ public interface CommonConstants { String METADATA_REVISION = "metadata.revision"; + String METADATA_KEY = "metadata"; + + String METADATA_DEFAULT = "local"; + /** * package version in the manifest */ diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java index 548c48f4391..b4739f20735 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java @@ -498,4 +498,25 @@ static boolean isItemMatch(String pattern, String value) { return "*".equals(pattern) || pattern.equals(value); } } + + /** + * @param serviceKey, {group}/{interfaceName}:{version} + * @return [group, interfaceName, version] + */ + public static String[] parseServiceKey(String serviceKey) { + String[] arr = new String[3]; + int i = serviceKey.indexOf("/"); + if (i > 0) { + arr[0] = serviceKey.substring(0, i); + serviceKey = serviceKey.substring(i + 1); + } + + int j = serviceKey.indexOf(":"); + if (j > 0) { + arr[2] = serviceKey.substring(j + 1); + serviceKey = serviceKey.substring(0, j); + } + arr[1] = serviceKey; + return arr; + } } diff --git a/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory b/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory new file mode 100644 index 00000000000..42d6a251120 --- /dev/null +++ b/dubbo-common/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory @@ -0,0 +1 @@ +nop=org.apache.dubbo.common.config.configcenter.nop.NopDynamicConfigurationFactory \ No newline at end of file diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java index 7b489a3e2c7..f488c8d65e1 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java @@ -36,7 +36,7 @@ public class Constants implements CommonConstants, org.apache.dubbo.rpc.Constants, org.apache.dubbo.rpc.protocol.dubbo.Constants, org.apache.dubbo.common.serialize.Constants, - org.apache.dubbo.configcenter.Constants, + org.apache.dubbo.common.config.configcenter.Constants, org.apache.dubbo.metadata.support.Constants, org.apache.dubbo.rpc.protocol.rest.Constants, org.apache.dubbo.registry.Constants { diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml index b8f5938b112..896feef7aa4 100644 --- a/dubbo-config/dubbo-config-api/pom.xml +++ b/dubbo-config/dubbo-config-api/pom.xml @@ -66,12 +66,6 @@ ${project.parent.version} - - org.apache.dubbo - dubbo-metadata - ${project.parent.version} - - org.apache.dubbo diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractConfig.java index 246694822a7..4d59f91f9d4 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractConfig.java @@ -114,9 +114,6 @@ public abstract class AbstractConfig implements Serializable { LEGACY_PROPERTIES.put("dubbo.consumer.retries", "dubbo.service.max.retry.providers"); LEGACY_PROPERTIES.put("dubbo.consumer.check", "dubbo.service.allow.no.provider"); LEGACY_PROPERTIES.put("dubbo.service.url", "dubbo.service.address"); - - // this is only for compatibility - DubboShutdownHook.getDubboShutdownHook().register(); } /** diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java index 8130a5fc044..1ad15ecb725 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java @@ -19,8 +19,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.Version; -import org.apache.dubbo.common.config.Environment; -import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ConfigUtils; @@ -30,9 +28,6 @@ import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.config.support.Parameter; -import org.apache.dubbo.configcenter.DynamicConfiguration; -import org.apache.dubbo.configcenter.DynamicConfigurationFactory; -import org.apache.dubbo.metadata.integration.MetadataReportService; import org.apache.dubbo.monitor.MonitorFactory; import org.apache.dubbo.monitor.MonitorService; import org.apache.dubbo.registry.RegistryService; @@ -43,19 +38,14 @@ import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.support.MockInvoker; -import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Set; -import static org.apache.dubbo.common.config.ConfigurationUtils.parseProperties; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.common.constants.CommonConstants.FILE_KEY; @@ -73,7 +63,6 @@ import static org.apache.dubbo.config.Constants.DUBBO_IP_TO_REGISTRY; import static org.apache.dubbo.config.Constants.LAYER_KEY; import static org.apache.dubbo.config.Constants.LISTENER_KEY; -import static org.apache.dubbo.config.Constants.REGISTRIES_SUFFIX; import static org.apache.dubbo.monitor.Constants.LOGSTAT_PROTOCOL; import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY; import static org.apache.dubbo.registry.Constants.REGISTER_KEY; @@ -203,8 +192,6 @@ protected void checkRegistry() { "The registry config is: " + registryConfig); } } - - useRegistryForConfigIfNecessary(); } @SuppressWarnings("deprecation") @@ -267,55 +254,6 @@ protected void checkMetadataReport() { } } - - void startConfigCenter() { - if (configCenter == null) { - ConfigManager.getInstance().getConfigCenter().ifPresent(cc -> this.configCenter = cc); - } - - if (this.configCenter != null) { - // TODO there may have duplicate refresh - this.configCenter.refresh(); - prepareEnvironment(); - } - ConfigManager.getInstance().refreshAll(); - } - - private void prepareEnvironment() { - if (configCenter.isValid()) { - if (!configCenter.checkOrUpdateInited()) { - return; - } - DynamicConfiguration dynamicConfiguration = getDynamicConfiguration(configCenter.toUrl()); - String configContent = dynamicConfiguration.getConfigs(configCenter.getConfigFile(), configCenter.getGroup()); - - String appGroup = application != null ? application.getName() : null; - String appConfigContent = null; - if (StringUtils.isNotEmpty(appGroup)) { - appConfigContent = dynamicConfiguration.getConfigs - (StringUtils.isNotEmpty(configCenter.getAppConfigFile()) ? configCenter.getAppConfigFile() : configCenter.getConfigFile(), - appGroup - ); - } - try { - Environment.getInstance().setConfigCenterFirst(configCenter.isHighestPriority()); - Environment.getInstance().updateExternalConfigurationMap(parseProperties(configContent)); - Environment.getInstance().updateAppExternalConfigurationMap(parseProperties(appConfigContent)); - } catch (IOException e) { - throw new IllegalStateException("Failed to parse configurations from Config Center.", e); - } - } - } - - private DynamicConfiguration getDynamicConfiguration(URL url) { - DynamicConfigurationFactory factories = ExtensionLoader - .getExtensionLoader(DynamicConfigurationFactory.class) - .getExtension(url.getProtocol()); - DynamicConfiguration configuration = factories.getDynamicConfiguration(url); - Environment.getInstance().setDynamicConfiguration(configuration); - return configuration; - } - /** * * Load the registry and conversion it to {@link URL}, the priority order is: system property > dubbo registry config @@ -415,24 +353,6 @@ static void appendRuntimeParameters(Map map) { } } - private URL loadMetadataReporterURL() { - String address = metadataReportConfig.getAddress(); - if (StringUtils.isEmpty(address)) { - return null; - } - Map map = new HashMap(); - appendParameters(map, metadataReportConfig); - return UrlUtils.parseURL(address, map); - } - - protected MetadataReportService getMetadataReportService() { - - if (metadataReportConfig == null || !metadataReportConfig.isValid()) { - return null; - } - return MetadataReportService.instance(this::loadMetadataReporterURL); - } - /** * Check whether the remote service interface and the methods meet with Dubbo's requirements.it mainly check, if the * methods configured in the configuration file are included in the interface of remote service @@ -544,16 +464,6 @@ private void verify(Class interfaceClass, Class localClass) { } private void convertRegistryIdsToRegistries() { - if (StringUtils.isEmpty(registryIds) && CollectionUtils.isEmpty(registries)) { - Set configedRegistries = new HashSet<>(); - configedRegistries.addAll(getSubProperties(Environment.getInstance().getExternalConfigurationMap(), - REGISTRIES_SUFFIX)); - configedRegistries.addAll(getSubProperties(Environment.getInstance().getAppExternalConfigurationMap(), - REGISTRIES_SUFFIX)); - - registryIds = String.join(COMMA_SEPARATOR, configedRegistries); - } - if (StringUtils.isEmpty(registryIds)) { if (CollectionUtils.isEmpty(registries)) { setRegistries( @@ -571,12 +481,7 @@ private void convertRegistryIdsToRegistries() { List tmpRegistries = CollectionUtils.isNotEmpty(registries) ? registries : new ArrayList<>(); Arrays.stream(ids).forEach(id -> { if (tmpRegistries.stream().noneMatch(reg -> reg.getId().equals(id))) { - tmpRegistries.add(ConfigManager.getInstance().getRegistry(id).orElseGet(() -> { - RegistryConfig registryConfig = new RegistryConfig(); - registryConfig.setId(id); - registryConfig.refresh(); - return registryConfig; - })); + ConfigManager.getInstance().getRegistry(id).ifPresent(tmpRegistries::add); } }); @@ -609,26 +514,6 @@ private void loadRegistriesFromBackwardConfig() { } } - /** - * For compatibility purpose, use registry as the default config center if the registry protocol is zookeeper and - * there's no config center specified explicitly. - */ - private void useRegistryForConfigIfNecessary() { - registries.stream().filter(RegistryConfig::isZookeeperProtocol).findFirst().ifPresent(rc -> { - // we use the loading status of DynamicConfiguration to decide whether ConfigCenter has been initiated. - Environment.getInstance().getDynamicConfiguration().orElseGet(() -> { - ConfigManager configManager = ConfigManager.getInstance(); - ConfigCenterConfig cc = configManager.getConfigCenter().orElse(new ConfigCenterConfig()); - cc.setProtocol(rc.getProtocol()); - cc.setAddress(rc.getAddress()); - cc.setHighestPriority(false); - setConfigCenter(cc); - startConfigCenter(); - return null; - }); - }); - } - /** * @return local * @deprecated Replace to getStub() @@ -783,7 +668,7 @@ public List getRegistries() { @SuppressWarnings({"unchecked"}) public void setRegistries(List registries) { - ConfigManager.getInstance().addRegistries((List) registries); + ConfigManager.getInstance().addRegistries((List) registries, false); this.registries = (List) registries; } @@ -823,7 +708,7 @@ public ConfigCenterConfig getConfigCenter() { } public void setConfigCenter(ConfigCenterConfig configCenter) { - ConfigManager.getInstance().setConfigCenter(configCenter); + ConfigManager.getInstance().addConfigCenter(configCenter); this.configCenter = configCenter; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java index 8aff2aa7a89..dc40e52bc9b 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java @@ -27,8 +27,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.rpc.Constants.SERVICE_FILTER_KEY; import static org.apache.dubbo.rpc.Constants.EXPORTER_LISTENER_KEY; +import static org.apache.dubbo.rpc.Constants.SERVICE_FILTER_KEY; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** @@ -206,7 +206,7 @@ public List getProtocols() { @SuppressWarnings({"unchecked"}) public void setProtocols(List protocols) { - ConfigManager.getInstance().addProtocols((List) protocols); + ConfigManager.getInstance().addProtocols((List) protocols, false); this.protocols = (List) protocols; } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java index 7caae5634ec..fb8b2e52b33 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java @@ -26,17 +26,17 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; +import static org.apache.dubbo.common.config.configcenter.Constants.CONFIG_CHECK_KEY; +import static org.apache.dubbo.common.config.configcenter.Constants.CONFIG_CLUSTER_KEY; +import static org.apache.dubbo.common.config.configcenter.Constants.CONFIG_GROUP_KEY; +import static org.apache.dubbo.common.config.configcenter.Constants.CONFIG_NAMESPACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; -import static org.apache.dubbo.configcenter.Constants.CONFIG_CHECK_KEY; -import static org.apache.dubbo.configcenter.Constants.CONFIG_CLUSTER_KEY; -import static org.apache.dubbo.configcenter.Constants.CONFIG_GROUP_KEY; -import static org.apache.dubbo.configcenter.Constants.CONFIG_NAMESPACE_KEY; -import static org.apache.dubbo.config.Constants.ZOOKEEPER_PROTOCOL; import static org.apache.dubbo.config.Constants.CONFIG_CONFIGFILE_KEY; import static org.apache.dubbo.config.Constants.CONFIG_ENABLE_KEY; import static org.apache.dubbo.config.Constants.CONFIG_TIMEOUT_KEY; +import static org.apache.dubbo.config.Constants.ZOOKEEPER_PROTOCOL; /** * ConfigCenterConfig diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MetadataReportConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MetadataReportConfig.java index 5233171e011..30e5bcb600e 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MetadataReportConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/MetadataReportConfig.java @@ -16,9 +16,12 @@ */ package org.apache.dubbo.config; +import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; +import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.config.support.Parameter; +import java.util.HashMap; import java.util.Map; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO; @@ -83,6 +86,16 @@ public MetadataReportConfig(String address) { setAddress(address); } + public URL toUrl() { + String address = this.getAddress(); + if (StringUtils.isEmpty(address)) { + return null; + } + Map map = new HashMap(); + appendParameters(map, this); + return UrlUtils.parseURL(address, map); + } + @Parameter(excluded = true) public String getAddress() { return address; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index ee2e9b63ebd..c33a82e6089 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -32,7 +32,7 @@ import org.apache.dubbo.config.support.Parameter; import org.apache.dubbo.event.Event; import org.apache.dubbo.event.EventDispatcher; -import org.apache.dubbo.metadata.integration.MetadataReportService; +import org.apache.dubbo.metadata.integration.RemoteWritableMetadataService; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; @@ -228,7 +228,6 @@ public void checkAndUpdateSubConfigs() { throw new IllegalStateException(" interface not allow null!"); } completeCompoundConfigs(); - startConfigCenter(); // get consumer's global configuration checkDefault(); this.refresh(); @@ -340,10 +339,11 @@ private void init() { } map.put(REGISTER_IP_KEY, hostToRegistry); - ref = createProxy(map); - String serviceKey = URL.buildKey(interfaceName, group, version); ApplicationModel.initConsumerModel(serviceKey, buildConsumerModel(serviceKey, attributes)); + ref = createProxy(map); + ApplicationModel.getConsumerModel(serviceKey).setProxyObject(ref); + initialized = true; // dispatch a ReferenceConfigInitializedEvent since 2.7.3 @@ -441,8 +441,8 @@ private T createProxy(Map map) { * @since 2.7.0 * ServiceData Store */ - MetadataReportService metadataReportService = null; - if ((metadataReportService = getMetadataReportService()) != null) { + RemoteWritableMetadataService metadataReportService = RemoteWritableMetadataService.instance(); + if (metadataReportService != null) { URL consumerURL = new URL(CONSUMER_PROTOCOL, map.remove(REGISTER_IP_KEY), 0, map.get(INTERFACE_KEY), map); metadataReportService.publishConsumer(consumerURL); } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java index c9a96cb2a51..ef8476672b8 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java @@ -149,6 +149,11 @@ public class RegistryConfig extends AbstractConfig { */ private String extraKeys; + /** + * Metadata type, local or remote, if choose remote, you need to further specify metadata center. + */ + private String metadata; + public RegistryConfig() { } @@ -407,6 +412,14 @@ public void setExtraKeys(String extraKeys) { this.extraKeys = extraKeys; } + public String getMetadata() { + return metadata; + } + + public void setMetadata(String metadata) { + this.metadata = metadata; + } + @Parameter(excluded = true) public boolean isZookeeperProtocol() { if (!isValid()) { diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index cc1138ae66b..7156f5df644 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -21,7 +21,6 @@ import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.bytecode.Wrapper; -import org.apache.dubbo.common.config.Environment; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.CollectionUtils; @@ -36,7 +35,7 @@ import org.apache.dubbo.config.support.Parameter; import org.apache.dubbo.event.Event; import org.apache.dubbo.event.EventDispatcher; -import org.apache.dubbo.metadata.integration.MetadataReportService; +import org.apache.dubbo.metadata.integration.RemoteWritableMetadataService; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; @@ -87,7 +86,6 @@ import static org.apache.dubbo.config.Constants.DUBBO_PORT_TO_BIND; import static org.apache.dubbo.config.Constants.DUBBO_PORT_TO_REGISTRY; import static org.apache.dubbo.config.Constants.MULTICAST; -import static org.apache.dubbo.config.Constants.PROTOCOLS_SUFFIX; import static org.apache.dubbo.config.Constants.SCOPE_NONE; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL; @@ -301,10 +299,8 @@ public boolean isUnexported() { } public void checkAndUpdateSubConfigs() { - // Use default configs defined explicitly on global configs + // Use default configs defined explicitly on global scope completeCompoundConfigs(); - // Config Center should always being started first. - startConfigCenter(); checkDefault(); checkProtocol(); checkApplication(); @@ -635,8 +631,8 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r * @since 2.7.0 * ServiceData Store */ - MetadataReportService metadataReportService = null; - if ((metadataReportService = getMetadataReportService()) != null) { + RemoteWritableMetadataService metadataReportService = RemoteWritableMetadataService.instance(); + if (metadataReportService != null) { metadataReportService.publishProvider(url); } } @@ -882,16 +878,6 @@ private void checkProtocol() { } private void convertProtocolIdsToProtocols() { - if (StringUtils.isEmpty(protocolIds) && CollectionUtils.isEmpty(protocols)) { - List configedProtocols = new ArrayList<>(); - configedProtocols.addAll(getSubProperties(Environment.getInstance() - .getExternalConfigurationMap(), PROTOCOLS_SUFFIX)); - configedProtocols.addAll(getSubProperties(Environment.getInstance() - .getAppExternalConfigurationMap(), PROTOCOLS_SUFFIX)); - - protocolIds = String.join(",", configedProtocols); - } - if (StringUtils.isEmpty(protocolIds)) { if (CollectionUtils.isEmpty(protocols)) { setProtocols( @@ -909,12 +895,7 @@ private void convertProtocolIdsToProtocols() { List tmpProtocols = CollectionUtils.isNotEmpty(protocols) ? protocols : new ArrayList<>(); Arrays.stream(arr).forEach(id -> { if (tmpProtocols.stream().noneMatch(prot -> prot.getId().equals(id))) { - tmpProtocols.add(ConfigManager.getInstance().getProtocol(id).orElseGet(() -> { - ProtocolConfig protocolConfig = new ProtocolConfig(); - protocolConfig.setId(id); - protocolConfig.refresh(); - return protocolConfig; - })); + ConfigManager.getInstance().getProtocol(id).ifPresent(tmpProtocols::add); } }); if (tmpProtocols.size() > arr.length) { diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ApplicationBuilder.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ApplicationBuilder.java index 7ab59a6bf8c..0a81b40798a 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ApplicationBuilder.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ApplicationBuilder.java @@ -51,6 +51,10 @@ public class ApplicationBuilder extends AbstractBuilder parameters; private String shutwait; + public static ApplicationBuilder newBuilder() { + return new ApplicationBuilder(); + } + public ApplicationBuilder name(String name) { this.name = name; return getThis(); diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ProtocolBuilder.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ProtocolBuilder.java index 4ddd943e903..70e94c35c51 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ProtocolBuilder.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ProtocolBuilder.java @@ -185,6 +185,10 @@ public class ProtocolBuilder extends AbstractBuilder extends AbstractReferenceBuilder id(String id) { return super.id(id); } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/RegistryBuilder.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/RegistryBuilder.java index 616e6af09a5..9dc9e1b68a7 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/RegistryBuilder.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/RegistryBuilder.java @@ -134,6 +134,10 @@ public class RegistryBuilder extends AbstractBuilder extends AbstractServiceBuilder protocols = new ConcurrentHashMap<>(); private Map registries = new ConcurrentHashMap<>(); private Map providers = new ConcurrentHashMap<>(); private Map consumers = new ConcurrentHashMap<>(); + private List defaultProtocols = new ArrayList<>(); + private List defaultRegistries = new ArrayList<>(); + + private Set configCenters = new HashSet<>(); + private Set metadataConfigs = new HashSet<>(); + private Set registryIds = new HashSet<>(); + private Set protocolIds = new HashSet<>(); + + private List> serviceConfigs = new ArrayList<>(); + private List> referenceConfigs = new ArrayList<>(); + public static ConfigManager getInstance() { return CONFIG_MANAGER; } @@ -126,14 +146,35 @@ public void setModule(ModuleConfig module) { } } - public Optional getConfigCenter() { - return Optional.ofNullable(configCenter); + public Set getConfigCenters() { + return configCenters; + } + + public void addConfigCenter(ConfigCenterConfig configCenter) { + if (configCenter != null && !configCenters.contains(configCenter)) { + this.configCenters.add(configCenter); + } + } + + public void addConfigCenter(List configCenters) { + if (CollectionUtils.isNotEmpty(configCenters)) { + this.configCenters.addAll(configCenters); + } + } + + public Set getMetadataConfigs() { + return metadataConfigs; } - public void setConfigCenter(ConfigCenterConfig configCenter) { - if (configCenter != null) { - checkDuplicate(this.configCenter, configCenter); - this.configCenter = configCenter; + public void addMetadataReport(MetadataReportConfig metadataReportConfig) { + if (metadataReportConfig != null && !metadataConfigs.contains(metadataReportConfig)) { + this.metadataConfigs.add(metadataReportConfig); + } + } + + public void addMetadataReport(List metadataReportConfigs) { + if (CollectionUtils.isNotEmpty(metadataReportConfigs)) { + this.metadataConfigs.addAll(metadataReportConfigs); } } @@ -200,31 +241,28 @@ public Optional getProtocol(String id) { } public Optional> getDefaultProtocols() { - List defaults = new ArrayList<>(); - protocols.forEach((k, v) -> { - if (DEFAULT_KEY.equalsIgnoreCase(k)) { - defaults.add(v); - } else if (v.isDefault() == null || v.isDefault()) { - defaults.add(v); - } - }); - return Optional.of(defaults); - } - - public void addProtocols(List protocolConfigs) { + return Optional.of(defaultProtocols); + } + + public void addProtocols(List protocolConfigs, boolean canBeDefault) { if (protocolConfigs != null) { - protocolConfigs.forEach(this::addProtocol); + protocolConfigs.forEach(pc -> this.addProtocol(pc, canBeDefault)); } } - public void addProtocol(ProtocolConfig protocolConfig) { + public void addProtocol(ProtocolConfig protocolConfig, boolean canBeDefault) { if (protocolConfig == null) { return; } + // if isDefault is not false and a ProtocolConfig is not specified being false. + if (canBeDefault && (protocolConfig.isDefault() == null || protocolConfig.isDefault())) { + this.defaultProtocols.add(protocolConfig); + } + String key = StringUtils.isNotEmpty(protocolConfig.getId()) ? protocolConfig.getId() - : (protocolConfig.isDefault() == null || protocolConfig.isDefault()) ? DEFAULT_KEY : null; + : DEFAULT_KEY; if (StringUtils.isEmpty(key)) { throw new IllegalStateException("A ProtocolConfig should either has an id or it's the default one, " + protocolConfig); @@ -243,31 +281,26 @@ public Optional getRegistry(String id) { } public Optional> getDefaultRegistries() { - List defaults = new ArrayList<>(); - registries.forEach((k, v) -> { - if (DEFAULT_KEY.equalsIgnoreCase(k)) { - defaults.add(v); - } else if (v.isDefault() == null || v.isDefault()) { - defaults.add(v); - } - }); - return Optional.of(defaults); - } - - public void addRegistries(List registryConfigs) { + return Optional.of(defaultRegistries); + } + + public void addRegistries(List registryConfigs, boolean canBeDefault) { if (registryConfigs != null) { - registryConfigs.forEach(this::addRegistry); + registryConfigs.forEach(rc -> this.addRegistry(rc, canBeDefault)); } } - public void addRegistry(RegistryConfig registryConfig) { + public void addRegistry(RegistryConfig registryConfig, boolean canBeDefault) { if (registryConfig == null) { return; } + if (canBeDefault && (registryConfig.isDefault() == null || registryConfig.isDefault())) { + this.defaultRegistries.add(registryConfig); + } String key = StringUtils.isNotEmpty(registryConfig.getId()) ? registryConfig.getId() - : (registryConfig.isDefault() == null || registryConfig.isDefault()) ? DEFAULT_KEY : null; + : DEFAULT_KEY; if (StringUtils.isEmpty(key)) { throw new IllegalStateException("A RegistryConfig should either has an id or it's the default one, " + registryConfig); @@ -281,6 +314,51 @@ public void addRegistry(RegistryConfig registryConfig) { } } + public void addProtocolIds(List protocolIds) { + this.protocolIds.addAll(protocolIds); + } + + public void addRegistryIds(List registryIds) { + this.registryIds.addAll(registryIds); + } + + public void addService(ServiceConfig serviceConfig) { + this.serviceConfigs.add(serviceConfig); + } + + public void addReference(ReferenceConfig referenceConfig) { + this.referenceConfigs.add(referenceConfig); + } + + public Set getRegistryIds() { + Set configedRegistries = new HashSet<>(); + configedRegistries.addAll(getSubProperties(Environment.getInstance().getExternalConfigurationMap(), + REGISTRIES_SUFFIX)); + configedRegistries.addAll(getSubProperties(Environment.getInstance().getAppExternalConfigurationMap(), + REGISTRIES_SUFFIX)); + + configedRegistries.addAll(registryIds); + return configedRegistries; + } + + public Set getProtocolIds() { + Set configedProtocols = new HashSet<>(); + configedProtocols.addAll(getSubProperties(Environment.getInstance() + .getExternalConfigurationMap(), PROTOCOLS_SUFFIX)); + configedProtocols.addAll(getSubProperties(Environment.getInstance() + .getAppExternalConfigurationMap(), PROTOCOLS_SUFFIX)); + + configedProtocols.addAll(protocolIds); + return configedProtocols; + } + + protected static Set getSubProperties(Map properties, String prefix) { + return properties.keySet().stream().filter(k -> k.contains(prefix)).map(k -> { + k = k.substring(prefix.length()); + return k.substring(0, k.indexOf(".")); + }).collect(Collectors.toSet()); + } + public Map getProtocols() { return protocols; } @@ -297,6 +375,14 @@ public Map getConsumers() { return consumers; } + public List> getServiceConfigs() { + return serviceConfigs; + } + + public List> getReferenceConfigs() { + return referenceConfigs; + } + public void refreshAll() { // refresh all configs here, getApplication().ifPresent(ApplicationConfig::refresh); @@ -319,13 +405,16 @@ private void checkDuplicate(AbstractConfig oldOne, AbstractConfig newOne) { // For test purpose public void clear() { this.application = null; - this.configCenter = null; this.monitor = null; this.module = null; this.registries.clear(); this.protocols.clear(); this.providers.clear(); this.consumers.clear(); + this.configCenters.clear(); + this.metadataConfigs.clear(); + this.registryIds.clear(); + this.protocolIds.clear(); } } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java index ac36f9e477d..bf14658f5ac 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java @@ -25,9 +25,9 @@ import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.context.ConfigManager; -import org.apache.dubbo.metadata.LocalMetadataService; import org.apache.dubbo.metadata.MetadataService; import org.apache.dubbo.metadata.MetadataServiceExporter; +import org.apache.dubbo.metadata.WritableMetadataService; import java.util.Collection; import java.util.LinkedList; @@ -79,7 +79,7 @@ public List export() { if (!isExported()) { - LocalMetadataService metadataService = LocalMetadataService.getDefaultExtension(); + WritableMetadataService metadataService = WritableMetadataService.getDefaultExtension(); ServiceConfig serviceConfig = new ServiceConfig<>(); serviceConfig.setApplication(applicationConfig); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/ShutdownTelnetHandler.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/telnet/ShutdownTelnetHandler.java similarity index 98% rename from dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/ShutdownTelnetHandler.java rename to dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/telnet/ShutdownTelnetHandler.java index ff5bf07cb33..3c24cebb319 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/ShutdownTelnetHandler.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/telnet/ShutdownTelnetHandler.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.rpc.protocol.dubbo.telnet; +package org.apache.dubbo.config.telnet; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.StringUtils; diff --git a/dubbo-config/dubbo-config-api/src/main/resources/META-INF/services/org.apache.dubbo.remoting.telnet.TelnetHandler b/dubbo-config/dubbo-config-api/src/main/resources/META-INF/services/org.apache.dubbo.remoting.telnet.TelnetHandler new file mode 100644 index 00000000000..3e87526883d --- /dev/null +++ b/dubbo-config/dubbo-config-api/src/main/resources/META-INF/services/org.apache.dubbo.remoting.telnet.TelnetHandler @@ -0,0 +1 @@ +shutdown=org.apache.dubbo.rpc.protocol.dubbo.telnet.ShutdownTelnetHandler \ No newline at end of file diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporterTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporterTest.java index 66200aca1ea..ec841a55a3c 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporterTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporterTest.java @@ -49,9 +49,9 @@ public static void init() { configManager.setApplication(applicationConfig); // Add ProtocolConfig - configManager.addProtocol(protocolConfig()); + configManager.addProtocol(protocolConfig(), true); // Add RegistryConfig - configManager.addRegistry(registryConfig()); + configManager.addRegistry(registryConfig(), true); } private static ProtocolConfig protocolConfig() { diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/service/DemoException.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/service/DemoException.java similarity index 96% rename from dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/service/DemoException.java rename to dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/service/DemoException.java index ceb187c0d9f..dc02d4e6062 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/service/DemoException.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/service/DemoException.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.dubbo.rpc.service; +package org.apache.dubbo.config.service; /** * DemoException diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/service/DemoService.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/service/DemoService.java similarity index 96% rename from dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/service/DemoService.java rename to dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/service/DemoService.java index 38ba742c679..cbc131a5cb3 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/service/DemoService.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/service/DemoService.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.dubbo.rpc.service; +package org.apache.dubbo.config.service; import java.util.List; diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/service/DemoServiceImpl.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/service/DemoServiceImpl.java similarity index 96% rename from dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/service/DemoServiceImpl.java rename to dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/service/DemoServiceImpl.java index 4ef72c33352..7bd467e052e 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/service/DemoServiceImpl.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/service/DemoServiceImpl.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.dubbo.rpc.service; +package org.apache.dubbo.config.service; import java.util.List; diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/service/GenericServiceTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/service/GenericServiceTest.java similarity index 99% rename from dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/service/GenericServiceTest.java rename to dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/service/GenericServiceTest.java index e99c6fce095..921800ccf58 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/service/GenericServiceTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/service/GenericServiceTest.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.dubbo.rpc.service; +package org.apache.dubbo.config.service; import org.apache.dubbo.common.beanutil.JavaBeanAccessor; import org.apache.dubbo.common.beanutil.JavaBeanDescriptor; @@ -29,6 +29,8 @@ import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.ServiceConfig; +import org.apache.dubbo.rpc.service.GenericException; +import org.apache.dubbo.rpc.service.GenericService; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; @@ -42,8 +44,8 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicReference; -import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_NATIVE_JAVA; import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_BEAN; +import static org.apache.dubbo.rpc.Constants.GENERIC_SERIALIZATION_NATIVE_JAVA; /** * GenericServiceTest diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/service/User.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/service/User.java similarity index 97% rename from dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/service/User.java rename to dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/service/User.java index 901001b56aa..7ba76a2eccf 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/service/User.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/service/User.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.dubbo.rpc.service; +package org.apache.dubbo.config.service; import java.io.Serializable; diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/ShutdownTelnetHandlerTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/telnet/ShutdownTelnetHandlerTest.java similarity index 97% rename from dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/ShutdownTelnetHandlerTest.java rename to dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/telnet/ShutdownTelnetHandlerTest.java index 6dbd026300e..2fc4110d571 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/ShutdownTelnetHandlerTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/telnet/ShutdownTelnetHandlerTest.java @@ -14,11 +14,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.rpc.protocol.dubbo.telnet; +package org.apache.dubbo.config.telnet; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.telnet.TelnetHandler; + import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/validation/ValidationParameter.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/validation/ValidationParameter.java similarity index 98% rename from dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/validation/ValidationParameter.java rename to dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/validation/ValidationParameter.java index 77841d51013..14a571df8c0 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/validation/ValidationParameter.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/validation/ValidationParameter.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.dubbo.rpc.validation; +package org.apache.dubbo.config.validation; import javax.validation.constraints.Future; import javax.validation.constraints.Max; diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/validation/ValidationService.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/validation/ValidationService.java similarity index 98% rename from dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/validation/ValidationService.java rename to dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/validation/ValidationService.java index 262c9967eec..0d15b6dfb66 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/validation/ValidationService.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/validation/ValidationService.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.dubbo.rpc.validation; +package org.apache.dubbo.config.validation; import org.apache.dubbo.validation.MethodValidated; diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/validation/ValidationServiceImpl.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/validation/ValidationServiceImpl.java similarity index 96% rename from dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/validation/ValidationServiceImpl.java rename to dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/validation/ValidationServiceImpl.java index 8a621aaa27f..783cff524c9 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/validation/ValidationServiceImpl.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/validation/ValidationServiceImpl.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.dubbo.rpc.validation; +package org.apache.dubbo.config.validation; /** * ValidationServiceImpl diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/validation/ValidationTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/validation/ValidationTest.java similarity index 99% rename from dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/validation/ValidationTest.java rename to dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/validation/ValidationTest.java index 691f925216c..04a45eac7f8 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/validation/ValidationTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/validation/ValidationTest.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.dubbo.rpc.validation; +package org.apache.dubbo.config.validation; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ProtocolConfig; diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/compat/dubbo.xsd b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/compat/dubbo.xsd index 756f6dae665..0f642733690 100644 --- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/compat/dubbo.xsd +++ b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/compat/dubbo.xsd @@ -575,6 +575,11 @@ + + + + + diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd index 4a8cf56c8d8..fd9e4d22d2c 100644 --- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd +++ b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd @@ -569,6 +569,11 @@ + + + + + diff --git a/dubbo-configcenter/dubbo-configcenter-api/pom.xml b/dubbo-configcenter/dubbo-configcenter-api/pom.xml deleted file mode 100644 index bab80eb0fdc..00000000000 --- a/dubbo-configcenter/dubbo-configcenter-api/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - 4.0.0 - - org.apache.dubbo - dubbo-configcenter - ${revision} - - dubbo-configcenter-api - jar - ${project.artifactId} - The api definition of the service config-center module - - false - - - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.configcenter.DynamicConfigurationFactory b/dubbo-configcenter/dubbo-configcenter-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.configcenter.DynamicConfigurationFactory deleted file mode 100644 index 51c40041765..00000000000 --- a/dubbo-configcenter/dubbo-configcenter-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.configcenter.DynamicConfigurationFactory +++ /dev/null @@ -1 +0,0 @@ -nop=org.apache.dubbo.configcenter.support.nop.NopDynamicConfigurationFactory \ No newline at end of file diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/mock/AbstractDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/mock/AbstractDynamicConfigurationTest.java deleted file mode 100644 index a5f669a2715..00000000000 --- a/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/mock/AbstractDynamicConfigurationTest.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.configcenter.mock; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.configcenter.DynamicConfiguration; -import org.apache.dubbo.configcenter.DynamicConfigurationFactory; -import org.apache.dubbo.configcenter.support.nop.NopDynamicConfigurationFactory; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * - */ -public class AbstractDynamicConfigurationTest { - public DynamicConfigurationFactory configurationFactory = ExtensionLoader.getExtensionLoader(DynamicConfigurationFactory.class).getExtension("mock"); - public URL url = URL.valueOf("nop://127.0.0.1:10880/DynamicConfiguration"); - - @Test - public void testInit() { - DynamicConfiguration configuration1 = configurationFactory.getDynamicConfiguration(url); - DynamicConfiguration configuration2 = configurationFactory.getDynamicConfiguration(url); - Assertions.assertEquals(configuration1, configuration2); - } - - @Test - public void testDefaultExtension() { - DynamicConfigurationFactory factory = ExtensionLoader.getExtensionLoader(DynamicConfigurationFactory.class).getDefaultExtension(); - Assertions.assertTrue(factory instanceof NopDynamicConfigurationFactory); - } -} diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/mock/MockDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/mock/MockDynamicConfiguration.java deleted file mode 100644 index 05ce68b32d7..00000000000 --- a/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/mock/MockDynamicConfiguration.java +++ /dev/null @@ -1,54 +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.mock; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.configcenter.ConfigurationListener; -import org.apache.dubbo.configcenter.DynamicConfiguration; - -/** - * - */ -public class MockDynamicConfiguration implements DynamicConfiguration { - public MockDynamicConfiguration(URL url) { - } - - @Override - public Object getInternalProperty(String key) { - return null; - } - - @Override - public void addListener(String key, String group, ConfigurationListener listener) { - - } - - @Override - public void removeListener(String key, String group, ConfigurationListener listener) { - - } - - @Override - public String getConfig(String key, String group, long timeout) throws IllegalStateException { - return null; - } - - @Override - public String getConfigs(String key, String group, long timeout) throws IllegalStateException { - return null; - } -} diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfigurationTest.java deleted file mode 100644 index cd549dd62c1..00000000000 --- a/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/support/nop/NopDynamicConfigurationTest.java +++ /dev/null @@ -1,70 +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.nop; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * {@link NopDynamicConfiguration} Test - * - * @since 2.7.3 - */ -public class NopDynamicConfigurationTest { - - private NopDynamicConfiguration configuration = new NopDynamicConfiguration(null); - - @Test - public void testGetInternalProperty() { - assertNull(configuration.getInternalProperty(null)); - } - - @Test - public void testGetConfig() { - assertNull(configuration.getConfig(null, null, -1)); - } - - - @Test - public void testGetConfigs() { - assertNull(configuration.getConfigs(null, null, -1)); - } - - @Test - public void testAddListener() { - configuration.addListener(null, null, null); - } - - @Test - public void testRemoveListener() { - configuration.removeListener(null, null, null); - } - - @Test - public void testPublishConfig() { - assertTrue(configuration.publishConfig(null, null, null)); - } - - @Test - public void testGetConfigKeys() { - assertTrue(configuration.getConfigKeys(null).isEmpty()); - } - - -} diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.configcenter.DynamicConfigurationFactory b/dubbo-configcenter/dubbo-configcenter-api/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.configcenter.DynamicConfigurationFactory deleted file mode 100644 index 211d45e8a7c..00000000000 --- a/dubbo-configcenter/dubbo-configcenter-api/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.configcenter.DynamicConfigurationFactory +++ /dev/null @@ -1 +0,0 @@ -mock=org.apache.dubbo.configcenter.mock.MockDynamicConfigurationFactory \ No newline at end of file diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml b/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml index 26d2e88fb28..6f3d8de8b15 100644 --- a/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml +++ b/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml @@ -32,7 +32,7 @@ org.apache.dubbo - dubbo-configcenter-api + dubbo-common ${project.parent.version} diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java index f67c1e03236..e092b7155d6 100644 --- a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java @@ -17,13 +17,13 @@ package org.apache.dubbo.configcenter.support.apollo; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.config.configcenter.ConfigChangeEvent; +import org.apache.dubbo.common.config.configcenter.ConfigChangeType; +import org.apache.dubbo.common.config.configcenter.ConfigurationListener; +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.configcenter.ConfigChangeEvent; -import org.apache.dubbo.configcenter.ConfigChangeType; -import org.apache.dubbo.configcenter.ConfigurationListener; -import org.apache.dubbo.configcenter.DynamicConfiguration; import com.ctrip.framework.apollo.Config; import com.ctrip.framework.apollo.ConfigChangeListener; @@ -42,12 +42,12 @@ import java.util.concurrent.CopyOnWriteArraySet; import java.util.stream.Collectors; +import static org.apache.dubbo.common.config.configcenter.Constants.CONFIG_CHECK_KEY; +import static org.apache.dubbo.common.config.configcenter.Constants.CONFIG_CLUSTER_KEY; +import static org.apache.dubbo.common.config.configcenter.Constants.CONFIG_NAMESPACE_KEY; 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.COMMA_SPLIT_PATTERN; -import static org.apache.dubbo.configcenter.Constants.CONFIG_CHECK_KEY; -import static org.apache.dubbo.configcenter.Constants.CONFIG_CLUSTER_KEY; -import static org.apache.dubbo.configcenter.Constants.CONFIG_NAMESPACE_KEY; /** * Apollo implementation, https://github.com/ctripcorp/apollo diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationFactory.java b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationFactory.java index b7e877c2096..6a8ce304f4b 100644 --- a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationFactory.java +++ b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationFactory.java @@ -17,8 +17,8 @@ package org.apache.dubbo.configcenter.support.apollo; import org.apache.dubbo.common.URL; -import org.apache.dubbo.configcenter.AbstractDynamicConfigurationFactory; -import org.apache.dubbo.configcenter.DynamicConfiguration; +import org.apache.dubbo.common.config.configcenter.AbstractDynamicConfigurationFactory; +import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; /** * diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.configcenter.DynamicConfigurationFactory b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory similarity index 100% rename from dubbo-configcenter/dubbo-configcenter-apollo/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.configcenter.DynamicConfigurationFactory rename to dubbo-configcenter/dubbo-configcenter-apollo/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory diff --git a/dubbo-configcenter/dubbo-configcenter-consul/pom.xml b/dubbo-configcenter/dubbo-configcenter-consul/pom.xml index 6f8b24ff666..830c6bd71b4 100644 --- a/dubbo-configcenter/dubbo-configcenter-consul/pom.xml +++ b/dubbo-configcenter/dubbo-configcenter-consul/pom.xml @@ -29,7 +29,7 @@ org.apache.dubbo - dubbo-configcenter-api + dubbo-common ${project.parent.version} 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 index 2e67bbd7c89..030398481a3 100644 --- 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 @@ -18,14 +18,14 @@ package org.apache.dubbo.configcenter.consul; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.config.configcenter.ConfigChangeEvent; +import org.apache.dubbo.common.config.configcenter.ConfigChangeType; +import org.apache.dubbo.common.config.configcenter.ConfigurationListener; +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.NamedThreadFactory; import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.configcenter.ConfigChangeEvent; -import org.apache.dubbo.configcenter.ConfigChangeType; -import org.apache.dubbo.configcenter.ConfigurationListener; -import org.apache.dubbo.configcenter.DynamicConfiguration; import com.ecwid.consul.v1.ConsulClient; import com.ecwid.consul.v1.QueryParams; @@ -39,9 +39,9 @@ import java.util.concurrent.ExecutorService; import static java.util.concurrent.Executors.newCachedThreadPool; +import static org.apache.dubbo.common.config.configcenter.ConfigChangeType.ADDED; +import static org.apache.dubbo.common.config.configcenter.Constants.CONFIG_NAMESPACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; -import static org.apache.dubbo.configcenter.Constants.CONFIG_NAMESPACE_KEY; -import static org.apache.dubbo.configcenter.ConfigChangeType.ADDED; /** * config center implementation for consul 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 index 813b6174662..980a1562348 100644 --- 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 @@ -18,8 +18,8 @@ package org.apache.dubbo.configcenter.consul; import org.apache.dubbo.common.URL; -import org.apache.dubbo.configcenter.AbstractDynamicConfigurationFactory; -import org.apache.dubbo.configcenter.DynamicConfiguration; +import org.apache.dubbo.common.config.configcenter.AbstractDynamicConfigurationFactory; +import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; /** * Config center factory for consul diff --git a/dubbo-configcenter/dubbo-configcenter-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.configcenter.DynamicConfigurationFactory b/dubbo-configcenter/dubbo-configcenter-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory similarity index 100% rename from dubbo-configcenter/dubbo-configcenter-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.configcenter.DynamicConfigurationFactory rename to dubbo-configcenter/dubbo-configcenter-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory diff --git a/dubbo-configcenter/dubbo-configcenter-etcd/pom.xml b/dubbo-configcenter/dubbo-configcenter-etcd/pom.xml index 66d2dfa0f42..76eaeb3a368 100644 --- a/dubbo-configcenter/dubbo-configcenter-etcd/pom.xml +++ b/dubbo-configcenter/dubbo-configcenter-etcd/pom.xml @@ -32,11 +32,6 @@ The etcd implementation of the config-center api - - org.apache.dubbo - dubbo-configcenter-api - ${project.parent.version} - io.etcd jetcd-launcher @@ -47,6 +42,12 @@ testcontainers test + + + org.apache.dubbo + dubbo-common + ${project.parent.version} + org.apache.dubbo dubbo-remoting-etcd3 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 index 10c50b66dd0..6925f030a93 100644 --- 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 @@ -18,11 +18,11 @@ package org.apache.dubbo.configcenter.support.etcd; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.config.configcenter.ConfigChangeEvent; +import org.apache.dubbo.common.config.configcenter.ConfigChangeType; +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.configcenter.ConfigChangeEvent; -import org.apache.dubbo.configcenter.ConfigChangeType; -import org.apache.dubbo.configcenter.ConfigurationListener; -import org.apache.dubbo.configcenter.DynamicConfiguration; import org.apache.dubbo.remoting.etcd.StateListener; import org.apache.dubbo.remoting.etcd.jetcd.JEtcdClient; @@ -40,8 +40,8 @@ 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; -import static org.apache.dubbo.configcenter.Constants.CONFIG_NAMESPACE_KEY; /** * The etcd implementation of {@link DynamicConfiguration} 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 index 02e91a62db7..269cee6046e 100644 --- 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 @@ -18,8 +18,8 @@ package org.apache.dubbo.configcenter.support.etcd; import org.apache.dubbo.common.URL; -import org.apache.dubbo.configcenter.AbstractDynamicConfigurationFactory; -import org.apache.dubbo.configcenter.DynamicConfiguration; +import org.apache.dubbo.common.config.configcenter.AbstractDynamicConfigurationFactory; +import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; /** * The etcd implementation of {@link AbstractDynamicConfigurationFactory} diff --git a/dubbo-configcenter/dubbo-configcenter-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.configcenter.DynamicConfigurationFactory b/dubbo-configcenter/dubbo-configcenter-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory similarity index 100% rename from dubbo-configcenter/dubbo-configcenter-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.configcenter.DynamicConfigurationFactory rename to dubbo-configcenter/dubbo-configcenter-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory 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 index d56f3c4649c..8b4f739be17 100644 --- 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 @@ -18,8 +18,8 @@ package org.apache.dubbo.configcenter.support.etcd; import org.apache.dubbo.common.URL; -import org.apache.dubbo.configcenter.ConfigChangeEvent; -import org.apache.dubbo.configcenter.ConfigurationListener; +import org.apache.dubbo.common.config.configcenter.ConfigChangeEvent; +import org.apache.dubbo.common.config.configcenter.ConfigurationListener; import io.etcd.jetcd.ByteSequence; import io.etcd.jetcd.Client; diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml b/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml index bd5397c92b6..68dc27150fa 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml +++ b/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml @@ -34,7 +34,7 @@ org.apache.dubbo - dubbo-configcenter-api + dubbo-common ${project.parent.version} diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java index 96bec25f1dd..8c827a332f1 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java @@ -18,13 +18,13 @@ package org.apache.dubbo.configcenter.support.nacos; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.config.configcenter.ConfigChangeEvent; +import org.apache.dubbo.common.config.configcenter.ConfigChangeType; +import org.apache.dubbo.common.config.configcenter.ConfigurationListener; +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.configcenter.ConfigChangeEvent; -import org.apache.dubbo.configcenter.ConfigChangeType; -import org.apache.dubbo.configcenter.ConfigurationListener; -import org.apache.dubbo.configcenter.DynamicConfiguration; import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.config.ConfigService; @@ -46,9 +46,9 @@ import static com.alibaba.nacos.api.PropertyKeyConst.SECRET_KEY; import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; import static com.alibaba.nacos.client.naming.utils.UtilAndComs.NACOS_NAMING_LOG_NAME; +import static org.apache.dubbo.common.config.configcenter.Constants.CONFIG_NAMESPACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_CHAR_SEPERATOR; import static org.apache.dubbo.common.constants.CommonConstants.PROPERTIES_CHAR_SEPERATOR; -import static org.apache.dubbo.configcenter.Constants.CONFIG_NAMESPACE_KEY; import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; /** diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationFactory.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationFactory.java index 804e216a590..61c02b48cfb 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationFactory.java +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationFactory.java @@ -18,9 +18,9 @@ package org.apache.dubbo.configcenter.support.nacos; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.config.configcenter.AbstractDynamicConfigurationFactory; +import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.constants.CommonConstants; -import org.apache.dubbo.configcenter.AbstractDynamicConfigurationFactory; -import org.apache.dubbo.configcenter.DynamicConfiguration; import com.alibaba.nacos.api.PropertyKeyConst; diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.configcenter.DynamicConfigurationFactory b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory similarity index 100% rename from dubbo-configcenter/dubbo-configcenter-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.configcenter.DynamicConfigurationFactory rename to dubbo-configcenter/dubbo-configcenter-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java index ff785b974a6..e48699c6658 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java @@ -18,8 +18,8 @@ package org.apache.dubbo.configcenter.support.nacos; import org.apache.dubbo.common.URL; -import org.apache.dubbo.configcenter.ConfigChangeEvent; -import org.apache.dubbo.configcenter.ConfigurationListener; +import org.apache.dubbo.common.config.configcenter.ConfigChangeEvent; +import org.apache.dubbo.common.config.configcenter.ConfigurationListener; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/pom.xml b/dubbo-configcenter/dubbo-configcenter-zookeeper/pom.xml index 9f028ce05c7..54977b8954c 100644 --- a/dubbo-configcenter/dubbo-configcenter-zookeeper/pom.xml +++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/pom.xml @@ -29,7 +29,7 @@ org.apache.dubbo - dubbo-configcenter-api + dubbo-common ${project.parent.version} diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/CacheListener.java b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/CacheListener.java index 3eaa96b28a9..baaaf8e4c64 100644 --- a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/CacheListener.java +++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/CacheListener.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.configcenter.support.zookeeper; +import org.apache.dubbo.common.config.configcenter.ConfigChangeEvent; +import org.apache.dubbo.common.config.configcenter.ConfigChangeType; +import org.apache.dubbo.common.config.configcenter.ConfigurationListener; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.configcenter.ConfigChangeEvent; -import org.apache.dubbo.configcenter.ConfigChangeType; -import org.apache.dubbo.configcenter.ConfigurationListener; import org.apache.dubbo.remoting.zookeeper.DataListener; import org.apache.dubbo.remoting.zookeeper.EventType; diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java index 5b034ca3740..8ee45817d36 100644 --- a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java @@ -17,10 +17,10 @@ package org.apache.dubbo.configcenter.support.zookeeper; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.config.configcenter.ConfigurationListener; +import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.configcenter.ConfigurationListener; -import org.apache.dubbo.configcenter.DynamicConfiguration; import org.apache.dubbo.remoting.zookeeper.ZookeeperClient; import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter; @@ -36,8 +36,8 @@ import static java.util.Collections.emptySortedSet; import static java.util.Collections.unmodifiableSortedSet; +import static org.apache.dubbo.common.config.configcenter.Constants.CONFIG_NAMESPACE_KEY; import static org.apache.dubbo.common.utils.CollectionUtils.isEmpty; -import static org.apache.dubbo.configcenter.Constants.CONFIG_NAMESPACE_KEY; /** * diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationFactory.java b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationFactory.java index 4d78133dbaf..0eb307ceac4 100644 --- a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationFactory.java +++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationFactory.java @@ -17,8 +17,8 @@ package org.apache.dubbo.configcenter.support.zookeeper; import org.apache.dubbo.common.URL; -import org.apache.dubbo.configcenter.AbstractDynamicConfigurationFactory; -import org.apache.dubbo.configcenter.DynamicConfiguration; +import org.apache.dubbo.common.config.configcenter.AbstractDynamicConfigurationFactory; +import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter; /** diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.configcenter.DynamicConfigurationFactory b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory similarity index 100% rename from dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.configcenter.DynamicConfigurationFactory rename to dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/test/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/test/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationTest.java index df440acc620..c9fb747554e 100644 --- a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/test/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationTest.java +++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/test/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationTest.java @@ -17,12 +17,12 @@ package org.apache.dubbo.configcenter.support.zookeeper; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.config.configcenter.ConfigChangeEvent; +import org.apache.dubbo.common.config.configcenter.ConfigurationListener; +import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; +import org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.configcenter.ConfigChangeEvent; -import org.apache.dubbo.configcenter.ConfigurationListener; -import org.apache.dubbo.configcenter.DynamicConfiguration; -import org.apache.dubbo.configcenter.DynamicConfigurationFactory; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; diff --git a/dubbo-configcenter/pom.xml b/dubbo-configcenter/pom.xml index 0de20d319c7..312fc3cbc3e 100644 --- a/dubbo-configcenter/pom.xml +++ b/dubbo-configcenter/pom.xml @@ -30,7 +30,6 @@ - dubbo-configcenter-api dubbo-configcenter-zookeeper dubbo-configcenter-apollo dubbo-configcenter-consul diff --git a/dubbo-container/dubbo-container-log4j/pom.xml b/dubbo-container/dubbo-container-log4j/pom.xml index a83b66165f5..d4503df1c88 100644 --- a/dubbo-container/dubbo-container-log4j/pom.xml +++ b/dubbo-container/dubbo-container-log4j/pom.xml @@ -34,10 +34,5 @@ dubbo-container-api ${project.parent.version} - - org.apache.dubbo - dubbo-configcenter-api - ${project.parent.version} - \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-api/dubbo-demo-api-consumer/pom.xml b/dubbo-demo/dubbo-demo-api/dubbo-demo-api-consumer/pom.xml index f668a8540db..e273e313737 100644 --- a/dubbo-demo/dubbo-demo-api/dubbo-demo-api-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-api/dubbo-demo-api-consumer/pom.xml @@ -33,6 +33,11 @@ + + org.apache.dubbo + dubbo-config-api + ${project.parent.version} + org.apache.dubbo dubbo-demo-interface diff --git a/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/pom.xml b/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/pom.xml index ff5d9ced5b7..04a2ae29ff0 100644 --- a/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/pom.xml @@ -35,6 +35,11 @@ + + org.apache.dubbo + dubbo-config-api + ${project.parent.version} + org.apache.dubbo dubbo-demo-interface diff --git a/dubbo-metadata-report/dubbo-metadata-definition/pom.xml b/dubbo-metadata/dubbo-metadata-api/pom.xml similarity index 50% rename from dubbo-metadata-report/dubbo-metadata-definition/pom.xml rename to dubbo-metadata/dubbo-metadata-api/pom.xml index 093c7e29824..3f5665a0917 100644 --- a/dubbo-metadata-report/dubbo-metadata-definition/pom.xml +++ b/dubbo-metadata/dubbo-metadata-api/pom.xml @@ -14,25 +14,55 @@ See the License for the specific language governing permissions and limitations under the License. --> - + - dubbo-metadata-report org.apache.dubbo + dubbo-metadata ${revision} + ../pom.xml 4.0.0 - dubbo-metadata-definition + dubbo-metadata-api + jar + + dubbo-metadata-api + The metadata module of Dubbo project + + org.apache.dubbo + dubbo-rpc-api + ${project.parent.version} + true + + + + org.apache.dubbo + dubbo-cluster + ${project.parent.version} + com.google.code.gson gson + + org.apache.dubbo - dubbo-common + dubbo-configcenter-zookeeper ${project.parent.version} + test + + + + org.apache.curator + curator-test + test + - + + \ No newline at end of file diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMapping.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMapping.java similarity index 98% rename from dubbo-metadata/src/main/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMapping.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMapping.java index f535a517dad..287ba734c52 100644 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMapping.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMapping.java @@ -16,9 +16,9 @@ */ package org.apache.dubbo.metadata; +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.configcenter.DynamicConfiguration; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Collections; diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataService.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataService.java similarity index 95% rename from dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataService.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataService.java index f73d5f6e8cb..7dba967919b 100644 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataService.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataService.java @@ -32,7 +32,7 @@ * {@link #getExportedURLs()} and {@link #getSubscribedURLs()} respectively. What's more, {@link MetadataService} * also providers the fine-grain methods for the precise queries. * - * @see LocalMetadataService + * @see WritableMetadataService * @since 2.7.3 */ public interface MetadataService { @@ -136,6 +136,17 @@ default List getExportedURLs(String serviceInterface, String group, Stri */ List getExportedURLs(String serviceInterface, String group, String version, String protocol); + /** + * Interface definition. + * @return + */ + String getServiceDefinition(String interfaceName, String version, String group); + + /** + * Interface definition. + * @return + */ + String getServiceDefinition(String serviceKey); /** * Convert the multiple {@link URL urls} to a {@link List list} of {@link URL urls} diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceExporter.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataServiceExporter.java similarity index 100% rename from dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceExporter.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataServiceExporter.java diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java similarity index 100% rename from dubbo-metadata/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/LocalMetadataService.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/WritableMetadataService.java similarity index 79% rename from dubbo-metadata/src/main/java/org/apache/dubbo/metadata/LocalMetadataService.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/WritableMetadataService.java index 172409524ec..27f75a16857 100644 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/LocalMetadataService.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/WritableMetadataService.java @@ -19,6 +19,7 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.extension.SPI; +import org.apache.dubbo.metadata.store.InMemoryWritableMetadataService; import org.apache.dubbo.rpc.model.ApplicationModel; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; @@ -29,8 +30,8 @@ * * @since 2.7.3 */ -@SPI("default") -public interface LocalMetadataService extends MetadataService { +@SPI("local") +public interface WritableMetadataService extends MetadataService { /** * Gets the current Dubbo Service name @@ -74,15 +75,20 @@ default String serviceName() { */ boolean unsubscribeURL(URL url); + void publishServiceDefinition(URL providerUrl); /** - * Get {@link ExtensionLoader#getDefaultExtension() the defautl extension} of {@link LocalMetadataService} + * Get {@link ExtensionLoader#getDefaultExtension() the defautl extension} of {@link WritableMetadataService} * * @return non-null - * @see InMemoryLocalMetadataService + * @see InMemoryWritableMetadataService */ - public static LocalMetadataService getDefaultExtension() { - return getExtensionLoader(LocalMetadataService.class).getDefaultExtension(); + static WritableMetadataService getDefaultExtension() { + return getExtensionLoader(WritableMetadataService.class).getDefaultExtension(); + } + + static WritableMetadataService getExtension(String name) { + return getExtensionLoader(WritableMetadataService.class).getExtension(name); } } diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/ServiceDefinitionBuilder.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/ServiceDefinitionBuilder.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/ServiceDefinitionBuilder.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/ServiceDefinitionBuilder.java diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/TypeDefinitionBuilder.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/TypeDefinitionBuilder.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/TypeDefinitionBuilder.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/TypeDefinitionBuilder.java diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/builder/ArrayTypeBuilder.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/builder/ArrayTypeBuilder.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/builder/ArrayTypeBuilder.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/builder/ArrayTypeBuilder.java diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/builder/CollectionTypeBuilder.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/builder/CollectionTypeBuilder.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/builder/CollectionTypeBuilder.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/builder/CollectionTypeBuilder.java diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/builder/DefaultTypeBuilder.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/builder/DefaultTypeBuilder.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/builder/DefaultTypeBuilder.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/builder/DefaultTypeBuilder.java diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/builder/EnumTypeBuilder.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/builder/EnumTypeBuilder.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/builder/EnumTypeBuilder.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/builder/EnumTypeBuilder.java diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/builder/MapTypeBuilder.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/builder/MapTypeBuilder.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/builder/MapTypeBuilder.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/builder/MapTypeBuilder.java diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/builder/TypeBuilder.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/builder/TypeBuilder.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/builder/TypeBuilder.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/builder/TypeBuilder.java diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/model/FullServiceDefinition.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/model/FullServiceDefinition.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/model/FullServiceDefinition.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/model/FullServiceDefinition.java diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/model/MethodDefinition.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/model/MethodDefinition.java similarity index 97% rename from dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/model/MethodDefinition.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/model/MethodDefinition.java index 41ebda505cd..36356216c8b 100755 --- a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/model/MethodDefinition.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/model/MethodDefinition.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.metadata.definition.model; +import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -24,7 +25,7 @@ /** * 2015/1/27. */ -public class MethodDefinition { +public class MethodDefinition implements Serializable { private String name; private String[] parameterTypes; diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/model/ServiceDefinition.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/model/ServiceDefinition.java similarity index 97% rename from dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/model/ServiceDefinition.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/model/ServiceDefinition.java index ebc586d2629..8b202df8167 100755 --- a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/model/ServiceDefinition.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/model/ServiceDefinition.java @@ -16,6 +16,7 @@ */ package org.apache.dubbo.metadata.definition.model; +import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -23,7 +24,7 @@ /** * 2015/1/27. */ -public class ServiceDefinition { +public class ServiceDefinition implements Serializable { private String canonicalName; private String codeSource; diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/model/TypeDefinition.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/model/TypeDefinition.java similarity index 97% rename from dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/model/TypeDefinition.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/model/TypeDefinition.java index bb434dc848b..4ae4f462aa7 100755 --- a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/model/TypeDefinition.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/model/TypeDefinition.java @@ -18,6 +18,7 @@ import com.google.gson.annotations.SerializedName; +import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -27,7 +28,7 @@ /** * 2015/1/27. */ -public class TypeDefinition { +public class TypeDefinition implements Serializable { private String id; private String type; diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/util/ClassUtils.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/util/ClassUtils.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/util/ClassUtils.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/util/ClassUtils.java diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/util/JaketConfigurationUtils.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/util/JaketConfigurationUtils.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-definition/src/main/java/org/apache/dubbo/metadata/definition/util/JaketConfigurationUtils.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/definition/util/JaketConfigurationUtils.java diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/store/InMemoryWritableMetadataService.java similarity index 76% rename from dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/store/InMemoryWritableMetadataService.java index 947a9fbd284..41779036bd2 100644 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/store/InMemoryWritableMetadataService.java @@ -14,11 +14,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metadata; +package org.apache.dubbo.metadata.store; 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.MetadataService; +import org.apache.dubbo.metadata.WritableMetadataService; +import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder; +import org.apache.dubbo.metadata.definition.model.ServiceDefinition; + +import com.google.gson.Gson; import java.util.Collection; import java.util.LinkedList; @@ -34,18 +41,19 @@ import static java.util.Collections.emptyList; import static java.util.Collections.unmodifiableList; import static org.apache.dubbo.common.URL.buildKey; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.utils.CollectionUtils.isEmpty; /** - * The {@link LocalMetadataService} implementation stores the metadata of Dubbo services in memory locally when they + * The {@link WritableMetadataService} implementation stores the metadata of Dubbo services in memory locally when they * exported. * * @see MetadataService - * @see LocalMetadataService + * @see WritableMetadataService * @since 2.7.3 */ -public class InMemoryLocalMetadataService implements LocalMetadataService { +public class InMemoryWritableMetadataService implements WritableMetadataService { /** * The class name of {@link MetadataService} @@ -75,6 +83,8 @@ public class InMemoryLocalMetadataService implements LocalMetadataService { */ private final ConcurrentMap> subscribedServiceURLs = new ConcurrentHashMap<>(); + private final ConcurrentHashMap serviceDefinitions = new ConcurrentHashMap<>(); + // ==================================================================================== // @Override @@ -117,6 +127,35 @@ public boolean unsubscribeURL(URL url) { return removeURL(subscribedServiceURLs, url); } + @Override + public void publishServiceDefinition(URL providerUrl) { + try { + String interfaceName = providerUrl.getParameter(INTERFACE_KEY); + if (StringUtils.isNotEmpty(interfaceName)) { + Class interfaceClass = Class.forName(interfaceName); + ServiceDefinition serviceDefinition = ServiceDefinitionBuilder.build(interfaceClass); + Gson gson = new Gson(); + String data = gson.toJson(serviceDefinition); + serviceDefinitions.put(providerUrl.getServiceKey(), data); + return; + } + logger.error("publishProvider interfaceName is empty . providerUrl: " + providerUrl.toFullString()); + } catch (ClassNotFoundException e) { + //ignore error + logger.error("publishProvider getServiceDescriptor error. providerUrl: " + providerUrl.toFullString(), e); + } + } + + @Override + public String getServiceDefinition(String interfaceName, String version, String group) { + return serviceDefinitions.get(URL.buildKey(interfaceName, group, version)); + } + + @Override + public String getServiceDefinition(String serviceKey) { + return serviceDefinitions.get(serviceKey); + } + private boolean addURL(Map> serviceURLs, URL url) { return executeMutually(() -> { List urls = serviceURLs.computeIfAbsent(url.getServiceKey(), s -> new LinkedList()); diff --git a/dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.ServiceNameMapping b/dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.ServiceNameMapping similarity index 100% rename from dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.ServiceNameMapping rename to dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.ServiceNameMapping diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.WritableMetadataService b/dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.WritableMetadataService new file mode 100644 index 00000000000..3380b9aa13e --- /dev/null +++ b/dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.WritableMetadataService @@ -0,0 +1 @@ +local=org.apache.dubbo.metadata.store.InMemoryWritableMetadataService \ No newline at end of file diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.definition.builder.TypeBuilder b/dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.definition.builder.TypeBuilder similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-definition/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.definition.builder.TypeBuilder rename to dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.definition.builder.TypeBuilder diff --git a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMappingTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMappingTest.java similarity index 96% rename from dubbo-metadata/src/test/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMappingTest.java rename to dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMappingTest.java index 95e7a1689ad..4fa96178942 100644 --- a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMappingTest.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMappingTest.java @@ -18,9 +18,9 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.Environment; +import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; +import org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory; import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.configcenter.DynamicConfiguration; -import org.apache.dubbo.configcenter.DynamicConfigurationFactory; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.curator.framework.CuratorFramework; diff --git a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/InMemoryLocalMetadataServiceTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/InMemoryWritableMetadataServiceTest.java similarity index 95% rename from dubbo-metadata/src/test/java/org/apache/dubbo/metadata/InMemoryLocalMetadataServiceTest.java rename to dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/InMemoryWritableMetadataServiceTest.java index 406e4aeb98e..8ffbd4cddd0 100644 --- a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/InMemoryLocalMetadataServiceTest.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/InMemoryWritableMetadataServiceTest.java @@ -17,6 +17,7 @@ package org.apache.dubbo.metadata; import org.apache.dubbo.common.URL; +import org.apache.dubbo.metadata.store.InMemoryWritableMetadataService; import org.apache.dubbo.rpc.model.ApplicationModel; import org.junit.jupiter.api.BeforeAll; @@ -34,13 +35,13 @@ import static org.junit.jupiter.api.Assertions.assertTrue; /** - * {@link InMemoryLocalMetadataService} Test + * {@link InMemoryWritableMetadataService} Test * * @since 2.7.3 */ -public class InMemoryLocalMetadataServiceTest { +public class InMemoryWritableMetadataServiceTest { - private LocalMetadataService metadataService = new InMemoryLocalMetadataService(); + private WritableMetadataService metadataService = new InMemoryWritableMetadataService(); private static final String TEST_SERVICE = "org.apache.dubbo.test.TestService"; diff --git a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java similarity index 82% rename from dubbo-metadata/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java rename to dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java index 508a9598738..e34ed13c779 100644 --- a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java @@ -16,12 +16,14 @@ */ package org.apache.dubbo.metadata; +import org.apache.dubbo.metadata.store.InMemoryWritableMetadataService; + import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** - * {@link LocalMetadataService} Test + * {@link WritableMetadataService} Test * * @since 2.7.3 */ @@ -29,6 +31,6 @@ public class LocalMetadataServiceTest { @Test public void testDefaultExtension() { - assertEquals(InMemoryLocalMetadataService.class, LocalMetadataService.getDefaultExtension().getClass()); + assertEquals(InMemoryWritableMetadataService.class, WritableMetadataService.getDefaultExtension().getClass()); } } diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/test/java/org/apache/dubbo/metadata/definition/MetadataTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/definition/MetadataTest.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-definition/src/test/java/org/apache/dubbo/metadata/definition/MetadataTest.java rename to dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/definition/MetadataTest.java diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/test/java/org/apache/dubbo/metadata/definition/MetadataUtils.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/definition/MetadataUtils.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-definition/src/test/java/org/apache/dubbo/metadata/definition/MetadataUtils.java rename to dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/definition/MetadataUtils.java diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/test/java/org/apache/dubbo/metadata/definition/ServiceDefinitionBuildderTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/definition/ServiceDefinitionBuildderTest.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-definition/src/test/java/org/apache/dubbo/metadata/definition/ServiceDefinitionBuildderTest.java rename to dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/definition/ServiceDefinitionBuildderTest.java diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/test/java/org/apache/dubbo/metadata/definition/common/ClassExtendsMap.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/definition/common/ClassExtendsMap.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-definition/src/test/java/org/apache/dubbo/metadata/definition/common/ClassExtendsMap.java rename to dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/definition/common/ClassExtendsMap.java diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/test/java/org/apache/dubbo/metadata/definition/common/ColorEnum.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/definition/common/ColorEnum.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-definition/src/test/java/org/apache/dubbo/metadata/definition/common/ColorEnum.java rename to dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/definition/common/ColorEnum.java diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/test/java/org/apache/dubbo/metadata/definition/common/OuterClass.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/definition/common/OuterClass.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-definition/src/test/java/org/apache/dubbo/metadata/definition/common/OuterClass.java rename to dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/definition/common/OuterClass.java diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/test/java/org/apache/dubbo/metadata/definition/common/ResultWithRawCollections.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/definition/common/ResultWithRawCollections.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-definition/src/test/java/org/apache/dubbo/metadata/definition/common/ResultWithRawCollections.java rename to dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/definition/common/ResultWithRawCollections.java diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/test/java/org/apache/dubbo/metadata/definition/common/TestService.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/definition/common/TestService.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-definition/src/test/java/org/apache/dubbo/metadata/definition/common/TestService.java rename to dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/definition/common/TestService.java diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/test/java/org/apache/dubbo/metadata/definition/service/ComplexObject.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/definition/service/ComplexObject.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-definition/src/test/java/org/apache/dubbo/metadata/definition/service/ComplexObject.java rename to dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/definition/service/ComplexObject.java diff --git a/dubbo-metadata-report/dubbo-metadata-definition/src/test/java/org/apache/dubbo/metadata/definition/service/DemoService.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/definition/service/DemoService.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-definition/src/test/java/org/apache/dubbo/metadata/definition/service/DemoService.java rename to dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/definition/service/DemoService.java diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/pom.xml b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/pom.xml similarity index 97% rename from dubbo-metadata-report/dubbo-metadata-report-api/pom.xml rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/pom.xml index b892598c800..bcdde95afaf 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/pom.xml +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/pom.xml @@ -34,6 +34,11 @@ dubbo-cluster ${project.parent.version} + + org.apache.dubbo + dubbo-metadata-api + ${project.parent.version} + org.apache.dubbo dubbo-common @@ -57,11 +62,6 @@ ${project.parent.version} test - - org.apache.dubbo - dubbo-metadata-definition - ${project.parent.version} - com.google.code.gson gson diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java similarity index 86% rename from dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java index f9b7e4c35f3..3ad16f53fb9 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java @@ -67,7 +67,11 @@ public String getUniqueKey(KeyTypeEnum keyType) { } public String getIdentifierKey() { - return serviceInterface + SEPARATOR + (version == null ? "" : version + SEPARATOR) + (group == null ? "" : group + SEPARATOR) + side + SEPARATOR + application; + return serviceInterface + SEPARATOR + + (version == null ? "" : version + SEPARATOR) + + (group == null ? "" : group + SEPARATOR) + + (side == null ? "" : side) + SEPARATOR + + (getApplication() == null ? "" : getApplication()); } private String getFilePathKey() { @@ -75,8 +79,12 @@ private String getFilePathKey() { } private String getFilePathKey(String pathTag) { - return pathTag + PATH_SEPARATOR + toServicePath() + PATH_SEPARATOR + (version == null ? "" : (version + PATH_SEPARATOR)) - + (group == null ? "" : (group + PATH_SEPARATOR)) + side + PATH_SEPARATOR + getApplication(); + return pathTag + PATH_SEPARATOR + + toServicePath() + PATH_SEPARATOR + + (version == null ? "" : (version + PATH_SEPARATOR)) + + (group == null ? "" : (group + PATH_SEPARATOR)) + + (side == null ? "" : side) + PATH_SEPARATOR + + (getApplication() == null ? "" : getApplication()); } private String toServicePath() { diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/MetadataReportService.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/RemoteWritableMetadataService.java similarity index 56% rename from dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/MetadataReportService.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/RemoteWritableMetadataService.java index 06d39b6f6ac..2379fbc67f0 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/MetadataReportService.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/RemoteWritableMetadataService.java @@ -22,14 +22,19 @@ 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.common.utils.UrlUtils; +import org.apache.dubbo.metadata.WritableMetadataService; import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder; import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; +import org.apache.dubbo.metadata.definition.model.ServiceDefinition; import org.apache.dubbo.metadata.identifier.MetadataIdentifier; import org.apache.dubbo.metadata.store.MetadataReport; import org.apache.dubbo.metadata.store.MetadataReportFactory; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.RpcException; +import java.util.List; +import java.util.function.Consumer; import java.util.function.Supplier; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; @@ -46,18 +51,21 @@ /** * @since 2.7.0 */ -public class MetadataReportService { +public class RemoteWritableMetadataService implements WritableMetadataService { protected final Logger logger = LoggerFactory.getLogger(getClass()); - private static volatile MetadataReportService metadataReportService; + private static volatile RemoteWritableMetadataService metadataReportService; private static Object lock = new Object(); - private MetadataReportFactory metadataReportFactory = ExtensionLoader.getExtensionLoader(MetadataReportFactory.class).getAdaptiveExtension(); - MetadataReport metadataReport; - URL metadataReportUrl; + private static MetadataReportFactory metadataReportFactory = ExtensionLoader.getExtensionLoader(MetadataReportFactory.class).getAdaptiveExtension(); + private static MetadataReport metadataReport; - MetadataReportService(URL metadataReportURL) { + RemoteWritableMetadataService() { + this.metadataReport = ; + } + + RemoteWritableMetadataService(URL metadataReportURL) { if (METADATA_REPORT_KEY.equals(metadataReportURL.getProtocol())) { String protocol = metadataReportURL.getParameter(METADATA_REPORT_KEY, DEFAULT_DIRECTORY); metadataReportURL = URLBuilder.from(metadataReportURL) @@ -65,13 +73,14 @@ public class MetadataReportService { .removeParameter(METADATA_REPORT_KEY) .build(); } - this.metadataReportUrl = metadataReportURL; - metadataReport = metadataReportFactory.getMetadataReport(this.metadataReportUrl); - + metadataReport = metadataReportFactory.getMetadataReport(metadataReportURL); } + public static RemoteWritableMetadataService instance() { + return metadataReportService; + } - public static MetadataReportService instance(Supplier metadataReportUrl) { + public static RemoteWritableMetadataService instance(Supplier metadataReportUrl) { if (metadataReportService == null) { synchronized (lock) { if (metadataReportService == null) { @@ -79,13 +88,36 @@ public static MetadataReportService instance(Supplier metadataReportUrl) { if (metadataReportURLTmp == null) { return null; } - metadataReportService = new MetadataReportService(metadataReportURLTmp); + metadataReportService = new RemoteWritableMetadataService(metadataReportURLTmp); } } } return metadataReportService; } + @Override + public void publishServiceDefinition(URL providerUrl) { + try { + String interfaceName = providerUrl.getParameter(INTERFACE_KEY); + if (StringUtils.isNotEmpty(interfaceName)) { + Class interfaceClass = Class.forName(interfaceName); + ServiceDefinition serviceDefinition = ServiceDefinitionBuilder.build(interfaceClass); + metadataReport.storeProviderMetadata(new MetadataIdentifier(providerUrl.getServiceInterface(), + providerUrl.getParameter(VERSION_KEY), providerUrl.getParameter(GROUP_KEY), + null, null), serviceDefinition); + return; + } + logger.error("publishProvider interfaceName is empty . providerUrl: " + providerUrl.toFullString()); + } catch (ClassNotFoundException e) { + //ignore error + logger.error("publishProvider getServiceDescriptor error. providerUrl: " + providerUrl.toFullString(), e); + } + + // backward compatibility + publishProvider(providerUrl); + } + + @Deprecated public void publishProvider(URL providerUrl) throws RpcException { //first add into the list // remove the individul param @@ -108,6 +140,7 @@ public void publishProvider(URL providerUrl) throws RpcException { } } + @Deprecated public void publishConsumer(URL consumerURL) throws RpcException { consumerURL = consumerURL.removeParameters(PID_KEY, TIMESTAMP_KEY, Constants.BIND_IP_KEY, Constants.BIND_PORT_KEY, TIMESTAMP_KEY); metadataReport.storeConsumerMetadata(new MetadataIdentifier(consumerURL.getServiceInterface(), @@ -115,4 +148,58 @@ public void publishConsumer(URL consumerURL) throws RpcException { consumerURL.getParameter(APPLICATION_KEY)), consumerURL.getParameters()); } + @Override + public boolean exportURL(URL url) { + return throwableAction(metadataReport::saveMetadata, url); + } + + @Override + public boolean unexportURL(URL url) { + return throwableAction(metadataReport::removeMetadata, url); + } + + @Override + public boolean subscribeURL(URL url) { + return throwableAction(metadataReport::saveMetadata, url); + } + + @Override + public boolean unsubscribeURL(URL url) { + return throwableAction(metadataReport::removeMetadata, url); + } + + @Override + public List getSubscribedURLs() { + return metadataReport.getSubscribedURLs(); + } + + // TODO, protocol should be used + @Override + public List getExportedURLs(String serviceInterface, String group, String version, String protocol) { + return metadataReport.getExportedURLs(new MetadataIdentifier(serviceInterface, group, version, null, null)); + } + + @Override + public String getServiceDefinition(String interfaceName, String version, String group) { + return metadataReport.getServiceDefinition(new MetadataIdentifier(interfaceName, + version, group, null, null)); + } + + @Override + public String getServiceDefinition(String serviceKey) { + String[] services = UrlUtils.parseServiceKey(serviceKey); + return metadataReport.getServiceDefinition(new MetadataIdentifier(services[1], + services[0], services[2], null, null)); + } + + private boolean throwableAction(Consumer consumer, URL url) { + try { + consumer.accept(url); + } catch (Exception e) { + logger.error("Failed to remove url metadata to remote center, url is: " + url); + return false; + } + return true; + } + } diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/store/MetadataReport.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/store/MetadataReport.java similarity index 65% rename from dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/store/MetadataReport.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/store/MetadataReport.java index 1afcc83438b..26ca68aa388 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/store/MetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/store/MetadataReport.java @@ -17,17 +17,34 @@ package org.apache.dubbo.metadata.store; -import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.extension.ExtensionLoader; +import org.apache.dubbo.metadata.definition.model.ServiceDefinition; import org.apache.dubbo.metadata.identifier.MetadataIdentifier; +import java.util.List; import java.util.Map; /** */ public interface MetadataReport { - void storeProviderMetadata(MetadataIdentifier providerMetadataIdentifier, FullServiceDefinition serviceDefinition); + void storeProviderMetadata(MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition); void storeConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, Map serviceParameterMap); + void saveMetadata(URL url); + + void removeMetadata(URL url); + + List getExportedURLs(MetadataIdentifier metadataIdentifier); + + List getSubscribedURLs(); + + String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier); + + static MetadataReport getMetadataReport() { + ExtensionLoader.getExtensionLoader(MetadataReport.class).get + } + } diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/store/MetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/store/MetadataReportFactory.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/store/MetadataReportFactory.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/store/MetadataReportFactory.java diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java similarity index 94% rename from dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java index 12085084cbd..283252f7ade 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java @@ -37,6 +37,7 @@ import java.nio.channels.FileLock; import java.util.Calendar; import java.util.Iterator; +import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; @@ -225,7 +226,7 @@ public void run() { } @Override - public void storeProviderMetadata(MetadataIdentifier providerMetadataIdentifier, FullServiceDefinition serviceDefinition) { + public void storeProviderMetadata(MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) { if (syncReport) { storeProviderMetadataTask(providerMetadataIdentifier, serviceDefinition); } else { @@ -281,6 +282,35 @@ public void storeConsumerMetadataTask(MetadataIdentifier consumerMetadataIdentif } } + @Override + public void saveMetadata(URL url) { + if (syncReport) { + doSaveMetadata(url); + } else { + reportCacheExecutor.execute(() -> doSaveMetadata(url)); + } + } + + @Override + public void removeMetadata(URL url) { + if (syncReport) { + doRemoveMetadata(url); + } else { + reportCacheExecutor.execute(() -> doRemoveMetadata(url)); + } + } + + @Override + public List getExportedURLs(MetadataIdentifier metadataIdentifier) { + // TODO, fallback to local cache + return doGetExportedURLs(); + } + + @Override + public List getSubscribedURLs() { + // TODO, fallback to local cache + return doGetSubscribedURLs(); + } String getProtocol(URL url) { String protocol = url.getParameter(SIDE_KEY); @@ -391,4 +421,12 @@ void cancelRetryTask() { protected abstract void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, String serviceParameterString); + protected abstract void doSaveMetadata(URL url); + + protected abstract void doRemoveMetadata(URL url); + + protected abstract List doGetExportedURLs(); + + protected abstract List doGetSubscribedURLs(); + } diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactory.java similarity index 93% rename from dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactory.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactory.java index fd4895c584c..782164a806a 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactory.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactory.java @@ -31,7 +31,7 @@ public abstract class AbstractMetadataReportFactory implements MetadataReportFac // The lock for the acquisition process of the registry private static final ReentrantLock LOCK = new ReentrantLock(); - // Registry Collection Map + // Registry Collection Map private static final Map SERVICE_STORE_MAP = new ConcurrentHashMap(); @Override @@ -39,7 +39,7 @@ public MetadataReport getMetadataReport(URL url) { url = url.setPath(MetadataReport.class.getName()) .removeParameters(EXPORT_KEY, REFER_KEY); String key = url.toServiceString(); - // Lock the registry access process to ensure a single instance of the registry + // Lock the metadata access process to ensure a single instance of the metadata instance LOCK.lock(); try { MetadataReport metadataReport = SERVICE_STORE_MAP.get(key); diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/Constants.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/Constants.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/Constants.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/Constants.java diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.WritableMetadataService b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.WritableMetadataService new file mode 100644 index 00000000000..44f58de8ae0 --- /dev/null +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.WritableMetadataService @@ -0,0 +1 @@ +remote=org.apache.dubbo.metadata.integration.RemoteWritableMetadataService \ No newline at end of file diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/identifier/MetadataIdentifierTest.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/identifier/MetadataIdentifierTest.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/identifier/MetadataIdentifierTest.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/identifier/MetadataIdentifierTest.java diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/InterfaceNameTestService.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/InterfaceNameTestService.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/InterfaceNameTestService.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/InterfaceNameTestService.java diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/InterfaceNameTestService2.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/InterfaceNameTestService2.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/InterfaceNameTestService2.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/InterfaceNameTestService2.java diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/MetadataReportServiceTest.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/MetadataReportServiceTest.java similarity index 95% rename from dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/MetadataReportServiceTest.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/MetadataReportServiceTest.java index d6ec49112f5..4b2cdae3dda 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/MetadataReportServiceTest.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/MetadataReportServiceTest.java @@ -34,17 +34,17 @@ */ public class MetadataReportServiceTest { URL url = URL.valueOf("JTest://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic"); - MetadataReportService metadataReportService1; + RemoteWritableMetadataService metadataReportService1; @BeforeEach public void before() { - metadataReportService1 = MetadataReportService.instance(() -> url); + metadataReportService1 = RemoteWritableMetadataService.instance(() -> url); } @Test public void testInstance() { - MetadataReportService metadataReportService2 = MetadataReportService.instance(new Supplier() { + RemoteWritableMetadataService metadataReportService2 = RemoteWritableMetadataService.instance(new Supplier() { @Override public URL get() { return url; diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/RetryTestService.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/RetryTestService.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/RetryTestService.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/RetryTestService.java diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReport4Test.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReport4Test.java similarity index 77% rename from dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReport4Test.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReport4Test.java index e01a71ab5f4..2b474152dad 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReport4Test.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReport4Test.java @@ -22,6 +22,7 @@ import org.apache.dubbo.metadata.identifier.MetadataIdentifier; import org.apache.dubbo.metadata.support.AbstractMetadataReport; +import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -58,6 +59,26 @@ protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdenti store.put(consumerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY), serviceParameterString); } + @Override + protected void doSaveMetadata(URL url) { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + + @Override + protected void doRemoveMetadata(URL url) { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + + @Override + protected List doGetExportedURLs() { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + + @Override + protected List doGetSubscribedURLs() { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + public static String getProviderKey(URL url) { return new MetadataIdentifier(url).getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY); } diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReportFactory4Test.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReportFactory4Test.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReportFactory4Test.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReportFactory4Test.java diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactoryTest.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactoryTest.java similarity index 88% rename from dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactoryTest.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactoryTest.java index 62bcbe81365..57b008c74bf 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactoryTest.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactoryTest.java @@ -18,15 +18,14 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; import org.apache.dubbo.metadata.identifier.MetadataIdentifier; import org.apache.dubbo.metadata.store.MetadataReport; import com.alibaba.fastjson.JSON; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -41,10 +40,30 @@ protected MetadataReport createMetadataReport(URL url) { return new MetadataReport() { @Override - public void storeProviderMetadata(MetadataIdentifier providerMetadataIdentifier, FullServiceDefinition serviceDefinition) { + public void storeProviderMetadata(MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) { store.put(providerMetadataIdentifier.getIdentifierKey(), JSON.toJSONString(serviceDefinition)); } + @Override + public void saveMetadata(URL url) { + + } + + @Override + public void removeMetadata(URL url) { + + } + + @Override + public List getExportedURLs(MetadataIdentifier metadataIdentifier) { + return null; + } + + @Override + public List getSubscribedURLs() { + return null; + } + @Override public void storeConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, Map serviceParameterMap) { store.put(consumerMetadataIdentifier.getIdentifierKey(), JSON.toJSONString(serviceParameterMap)); diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportTest.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportTest.java similarity index 90% rename from dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportTest.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportTest.java index d74c7905437..2a6f1dd66bb 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportTest.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportTest.java @@ -30,6 +30,7 @@ import java.util.Calendar; import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -287,6 +288,26 @@ protected void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdenti protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, String serviceParameterString) { store.put(consumerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY), serviceParameterString); } + + @Override + protected void doSaveMetadata(URL url) { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + + @Override + protected void doRemoveMetadata(URL url) { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + + @Override + protected List doGetExportedURLs() { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + + @Override + protected List doGetSubscribedURLs() { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } } private static class RetryMetadataReport extends AbstractMetadataReport { @@ -319,6 +340,26 @@ protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdenti store.put(consumerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY), serviceParameterString); } + @Override + protected void doSaveMetadata(URL url) { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + + @Override + protected void doRemoveMetadata(URL url) { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + + @Override + protected List doGetExportedURLs() { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + + @Override + protected List doGetSubscribedURLs() { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + } diff --git a/dubbo-metadata-report/dubbo-metadata-report-api/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-api/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory diff --git a/dubbo-metadata-report/dubbo-metadata-report-consul/pom.xml b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/pom.xml similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-consul/pom.xml rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/pom.xml diff --git a/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java similarity index 76% rename from dubbo-metadata-report/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java index 42a2f600f63..a00b30aaf9c 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java @@ -26,6 +26,8 @@ import com.ecwid.consul.v1.ConsulClient; +import java.util.List; + /** * metadata report impl for consul */ @@ -53,6 +55,26 @@ protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdenti this.storeMetadata(consumerMetadataIdentifier, value); } + @Override + protected void doSaveMetadata(URL url) { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + + @Override + protected void doRemoveMetadata(URL url) { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + + @Override + protected List doGetExportedURLs() { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + + @Override + protected List doGetSubscribedURLs() { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + private void storeMetadata(MetadataIdentifier identifier, String v) { try { client.setKVValue(identifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY), v); diff --git a/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReportFactory.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReportFactory.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReportFactory.java diff --git a/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory diff --git a/dubbo-metadata-report/dubbo-metadata-report-etcd/pom.xml b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/pom.xml similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-etcd/pom.xml rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/pom.xml diff --git a/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java similarity index 82% rename from dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java index 5ee950611a2..9577da80550 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java @@ -40,6 +40,8 @@ import org.apache.dubbo.metadata.support.AbstractMetadataReport; import org.apache.dubbo.remoting.etcd.jetcd.JEtcdClient; +import java.util.List; + import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; @@ -80,6 +82,26 @@ protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdenti storeMetadata(consumerMetadataIdentifier, value); } + @Override + protected void doSaveMetadata(URL url) { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + + @Override + protected void doRemoveMetadata(URL url) { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + + @Override + protected List doGetExportedURLs() { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + + @Override + protected List doGetSubscribedURLs() { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + private void storeMetadata(MetadataIdentifier identifier, String v) { String key = getNodeKey(identifier); if (!etcdClient.put(key, v)) { diff --git a/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportFactory.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportFactory.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportFactory.java diff --git a/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory diff --git a/dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadata4TstService.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadata4TstService.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadata4TstService.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadata4TstService.java diff --git a/dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java diff --git a/dubbo-metadata-report/dubbo-metadata-report-nacos/pom.xml b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/pom.xml similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-nacos/pom.xml rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/pom.xml diff --git a/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java similarity index 87% rename from dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java index 03bdeb8f958..78e8189a914 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java @@ -17,9 +17,6 @@ package org.apache.dubbo.metadata.store.nacos; -import com.alibaba.nacos.api.NacosFactory; -import com.alibaba.nacos.api.config.ConfigService; -import com.alibaba.nacos.api.exception.NacosException; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -28,14 +25,19 @@ import org.apache.dubbo.metadata.support.AbstractMetadataReport; import org.apache.dubbo.rpc.RpcException; +import com.alibaba.nacos.api.NacosFactory; +import com.alibaba.nacos.api.config.ConfigService; +import com.alibaba.nacos.api.exception.NacosException; + +import java.util.List; import java.util.Properties; -import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; -import static com.alibaba.nacos.api.PropertyKeyConst.SECRET_KEY; import static com.alibaba.nacos.api.PropertyKeyConst.ACCESS_KEY; +import static com.alibaba.nacos.api.PropertyKeyConst.CLUSTER_NAME; import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT; import static com.alibaba.nacos.api.PropertyKeyConst.NAMESPACE; -import static com.alibaba.nacos.api.PropertyKeyConst.CLUSTER_NAME; +import static com.alibaba.nacos.api.PropertyKeyConst.SECRET_KEY; +import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; import static com.alibaba.nacos.client.naming.utils.UtilAndComs.NACOS_NAMING_LOG_NAME; import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; @@ -111,6 +113,26 @@ protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdenti this.storeMetadata(consumerMetadataIdentifier, value); } + @Override + protected void doSaveMetadata(URL url) { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + + @Override + protected void doRemoveMetadata(URL url) { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + + @Override + protected List doGetExportedURLs() { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + + @Override + protected List doGetSubscribedURLs() { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + private void storeMetadata(MetadataIdentifier identifier, String value) { try { boolean publishResult = configService.publishConfig(identifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY), identifier.getGroup(), value); diff --git a/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java diff --git a/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory diff --git a/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadata4TstService.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadata4TstService.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadata4TstService.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadata4TstService.java diff --git a/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java diff --git a/dubbo-metadata-report/dubbo-metadata-report-redis/pom.xml b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/pom.xml similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-redis/pom.xml rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/pom.xml diff --git a/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java similarity index 93% rename from dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java index 6f3810476c8..69ae2ec9a7f 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java @@ -76,6 +76,26 @@ protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdenti this.storeMetadata(consumerMetadataIdentifier, value); } + @Override + protected void doSaveMetadata(URL url) { + + } + + @Override + protected void doRemoveMetadata(URL url) { + + } + + @Override + protected List doGetExportedURLs() { + return null; + } + + @Override + protected List doGetSubscribedURLs() { + return null; + } + private void storeMetadata(MetadataIdentifier metadataIdentifier, String v) { if (pool != null) { storeMetadataStandalone(metadataIdentifier, v); diff --git a/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportFactory.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportFactory.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportFactory.java diff --git a/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-redis/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory diff --git a/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadata4TstService.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadata4TstService.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadata4TstService.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadata4TstService.java diff --git a/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java diff --git a/dubbo-metadata-report/dubbo-metadata-report-zookeeper/pom.xml b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/pom.xml similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-zookeeper/pom.xml rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/pom.xml diff --git a/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java similarity index 88% rename from dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java index 66353f6817d..7f5c4bca20e 100644 --- a/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java @@ -24,6 +24,8 @@ import org.apache.dubbo.remoting.zookeeper.ZookeeperClient; import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter; +import java.util.List; + import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; @@ -68,6 +70,26 @@ protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdenti storeMetadata(consumerMetadataIdentifier, value); } + @Override + protected void doSaveMetadata(URL url) { +// zkClient.create(, URL.encode(url.toFullString())); + } + + @Override + protected void doRemoveMetadata(URL url) { + + } + + @Override + protected List doGetExportedURLs() { + return null; + } + + @Override + protected List doGetSubscribedURLs() { + return null; + } + private void storeMetadata(MetadataIdentifier metadataIdentifier, String v) { zkClient.create(getNodePath(metadataIdentifier), v, false); } diff --git a/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportFactory.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportFactory.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportFactory.java diff --git a/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory diff --git a/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport4TstService.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport4TstService.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport4TstService.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport4TstService.java diff --git a/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportTest.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportTest.java similarity index 100% rename from dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportTest.java rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportTest.java diff --git a/dubbo-metadata-report/pom.xml b/dubbo-metadata/dubbo-metadata-report/pom.xml similarity index 94% rename from dubbo-metadata-report/pom.xml rename to dubbo-metadata/dubbo-metadata-report/pom.xml index 5e0fb1a4287..02496c38e11 100644 --- a/dubbo-metadata-report/pom.xml +++ b/dubbo-metadata/dubbo-metadata-report/pom.xml @@ -16,7 +16,7 @@ --> - dubbo-parent + dubbo-metadata org.apache.dubbo ${revision} @@ -28,7 +28,6 @@ dubbo-metadata-report-api dubbo-metadata-report-zookeeper dubbo-metadata-report-redis - dubbo-metadata-definition dubbo-metadata-report-consul dubbo-metadata-report-etcd dubbo-metadata-report-nacos diff --git a/dubbo-metadata/pom.xml b/dubbo-metadata/pom.xml index 9a690ae58a5..2115c452c67 100644 --- a/dubbo-metadata/pom.xml +++ b/dubbo-metadata/pom.xml @@ -26,41 +26,10 @@ 4.0.0 dubbo-metadata - jar - - dubbo-metadata - The metadata module of Dubbo project - - - - - org.apache.dubbo - dubbo-config-api - ${project.parent.version} - true - - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - true - - - - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.parent.version} - test - - - - org.apache.curator - curator-test - test - - - + pom + + dubbo-metadata-api + dubbo-metadata-report + \ No newline at end of file diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/DefaultMetadataServiceProxyFactory.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/DefaultMetadataServiceProxyFactory.java deleted file mode 100644 index 74c6c1d917c..00000000000 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/DefaultMetadataServiceProxyFactory.java +++ /dev/null @@ -1,72 +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; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.registry.client.ServiceInstance; -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.directory.StaticDirectory; -import org.apache.dubbo.rpc.cluster.support.AvailableCluster; - -import java.lang.reflect.Proxy; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * The factory of {@link MetadataService}'s {@link Proxy} - * - * @since 2.7.3 - */ -public class DefaultMetadataServiceProxyFactory implements MetadataServiceProxyFactory { - - private final Map proxys = new HashMap<>(); - - private ProxyFactory proxyFactory; - - private Protocol protocol; - - private Cluster cluster = ExtensionLoader.getExtensionLoader(Cluster.class).getExtension(AvailableCluster.NAME); - - public void setProtocol(Protocol protocol) { - this.protocol = protocol; - } - - public void setProxyFactory(ProxyFactory proxyFactory) { - this.proxyFactory = proxyFactory; - } - - @Override - public MetadataService getProxy(ServiceInstance serviceInstance) { - return proxys.computeIfAbsent(serviceInstance.getId(), id -> createProxy(serviceInstance)); - } - - protected MetadataService createProxy(ServiceInstance serviceInstance) { - List urls = ServiceInstance.toUrls(serviceInstance); - List> invokers = urls.stream() - .map(url -> protocol.refer(MetadataService.class, url)) - .collect(Collectors.toList()); - - Invoker invoker = cluster.join(new StaticDirectory<>(invokers)); - return proxyFactory.getProxy(invoker); - } -} diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceProxyFactory.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceProxyFactory.java deleted file mode 100644 index eefa7556712..00000000000 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceProxyFactory.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. - */ -package org.apache.dubbo.metadata; - -import org.apache.dubbo.common.extension.SPI; -import org.apache.dubbo.registry.client.ServiceInstance; - -import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; - -/** - * A factory to create a {@link MetadataService} proxy - * - * @see ServiceInstance - * @see MetadataService - * @since 2.7.3 - */ -@SPI("default") -public interface MetadataServiceProxyFactory { - - /** - * Create a {@link MetadataService} proxy via the specified {@link ServiceInstance} - * - * @param serviceInstance the instance of {@link ServiceInstance} - * @return non-null - */ - MetadataService getProxy(ServiceInstance serviceInstance); - - /** - * Get the default extension of {@link MetadataServiceProxyFactory} - * - * @return non-null - */ - static MetadataServiceProxyFactory getDefaultExtension() { - return getExtensionLoader(MetadataServiceProxyFactory.class).getDefaultExtension(); - } -} diff --git a/dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.LocalMetadataService b/dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.LocalMetadataService deleted file mode 100644 index 2af06fde611..00000000000 --- a/dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.LocalMetadataService +++ /dev/null @@ -1 +0,0 @@ -default=org.apache.dubbo.metadata.InMemoryLocalMetadataService \ No newline at end of file diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Ls.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Ls.java index 469a40a3391..cf0dc68cf8d 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Ls.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Ls.java @@ -20,15 +20,13 @@ import org.apache.dubbo.qos.command.CommandContext; import org.apache.dubbo.qos.command.annotation.Cmd; import org.apache.dubbo.qos.textui.TTable; +import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ConsumerModel; import org.apache.dubbo.rpc.model.ProviderModel; import java.util.Collection; -import static org.apache.dubbo.registry.support.ProviderConsumerRegTable.getConsumerAddressNum; -import static org.apache.dubbo.registry.support.ProviderConsumerRegTable.isRegistered; - @Cmd(name = "ls", summary = "ls service", example = { "ls" }) @@ -57,7 +55,7 @@ public String listProvider() { //Content for (ProviderModel providerModel : providerModelList) { - tTable.addRow(providerModel.getServiceName(), isRegistered(providerModel.getServiceName()) ? "Y" : "N"); + tTable.addRow(providerModel.getServiceKey(), ApplicationModel.isRegistered(providerModel.getServiceKey()) ? "Y" : "N"); } stringBuilder.append(tTable.rendering()); @@ -80,7 +78,8 @@ public String listConsumer() { //Content //TODO to calculate consumerAddressNum for (ConsumerModel consumerModel : consumerModelList) { - tTable.addRow(consumerModel.getServiceName(), getConsumerAddressNum(consumerModel.getServiceName())); + AbstractClusterInvoker clusterInvoker = (AbstractClusterInvoker) consumerModel.getInvoker(); + tTable.addRow(consumerModel.getServiceKey(), clusterInvoker.getDirectory().getAllInvokers().size()); } stringBuilder.append(tTable.rendering()); diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Offline.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Offline.java index 79c41f3b669..fcbf548a2f4 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Offline.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Offline.java @@ -24,13 +24,11 @@ import org.apache.dubbo.qos.command.annotation.Cmd; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.RegistryFactory; -import org.apache.dubbo.registry.support.ProviderConsumerRegTable; -import org.apache.dubbo.registry.support.ProviderInvokerWrapper; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ProviderModel; +import org.apache.dubbo.rpc.model.invoker.ProviderInvokerWrapper; import java.util.Collection; -import java.util.Set; @Cmd(name = "offline", summary = "offline dubbo", example = { "offline dubbo", @@ -51,9 +49,9 @@ public String execute(CommandContext commandContext, String[] args) { Collection providerModelList = ApplicationModel.allProviderModels(); for (ProviderModel providerModel : providerModelList) { - if (providerModel.getServiceName().matches(servicePattern)) { + if (providerModel.getServiceKey().matches(servicePattern)) { hasService = true; - Set providerInvokerWrapperSet = ProviderConsumerRegTable.getProviderInvoker(providerModel.getServiceName()); + Collection providerInvokerWrapperSet = ApplicationModel.getProviderInvokers(providerModel.getServiceKey()); for (ProviderInvokerWrapper providerInvokerWrapper : providerInvokerWrapperSet) { if (!providerInvokerWrapper.isReg()) { continue; diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Online.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Online.java index 30ba14b6fe0..ae3d17f266c 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Online.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Online.java @@ -25,13 +25,11 @@ import org.apache.dubbo.qos.command.annotation.Cmd; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.RegistryFactory; -import org.apache.dubbo.registry.support.ProviderConsumerRegTable; -import org.apache.dubbo.registry.support.ProviderInvokerWrapper; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ProviderModel; +import org.apache.dubbo.rpc.model.invoker.ProviderInvokerWrapper; import java.util.Collection; -import java.util.Set; @Cmd(name = "online", summary = "online dubbo", example = { "online dubbo", @@ -53,9 +51,9 @@ public String execute(CommandContext commandContext, String[] args) { Collection providerModelList = ApplicationModel.allProviderModels(); for (ProviderModel providerModel : providerModelList) { - if (providerModel.getServiceName().matches(servicePattern)) { + if (providerModel.getServiceKey().matches(servicePattern)) { hasService = true; - Set providerInvokerWrapperSet = ProviderConsumerRegTable.getProviderInvoker(providerModel.getServiceName()); + Collection providerInvokerWrapperSet = ApplicationModel.getProviderInvokers(providerModel.getServiceKey()); for (ProviderInvokerWrapper providerInvokerWrapper : providerInvokerWrapperSet) { if (providerInvokerWrapper.isReg()) { continue; diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/LsTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/LsTest.java index c82e2d5d685..bef3088e4e0 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/LsTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/LsTest.java @@ -19,20 +19,19 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.qos.command.CommandContext; import org.apache.dubbo.registry.integration.RegistryDirectory; -import org.apache.dubbo.registry.support.ProviderConsumerRegTable; -import org.apache.dubbo.registry.support.ProviderInvokerWrapper; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ConsumerModel; import org.apache.dubbo.rpc.model.ProviderModel; +import org.apache.dubbo.rpc.model.invoker.ProviderInvokerWrapper; + import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.Map; -import static org.apache.dubbo.registry.support.ProviderConsumerRegTable.getProviderInvoker; -import static org.hamcrest.Matchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -40,9 +39,9 @@ public class LsTest { @Test public void testExecute() throws Exception { ConsumerModel consumerModel = mock(ConsumerModel.class); - when(consumerModel.getServiceName()).thenReturn("org.apache.dubbo.FooService"); + when(consumerModel.getServiceKey()).thenReturn("org.apache.dubbo.FooService"); ProviderModel providerModel = mock(ProviderModel.class); - when(providerModel.getServiceName()).thenReturn("org.apache.dubbo.BarService"); + when(providerModel.getServiceKey()).thenReturn("org.apache.dubbo.BarService"); ApplicationModel.initConsumerModel("org.apache.dubbo.FooService", consumerModel); ApplicationModel.initProviderModel("org.apache.dubbo.BarService", providerModel); @@ -53,8 +52,8 @@ public void testExecute() throws Exception { when(providerUrl.getServiceKey()).thenReturn("org.apache.dubbo.BarService"); when(providerUrl.toFullString()).thenReturn("dubbo://localhost:8888/org.apache.dubbo.BarService"); when(providerInvoker.getUrl()).thenReturn(providerUrl); - ProviderConsumerRegTable.registerProvider(providerInvoker, registryUrl, providerUrl); - for (ProviderInvokerWrapper wrapper : getProviderInvoker("org.apache.dubbo.BarService")) { + ApplicationModel.registerProviderInvoker(providerInvoker, registryUrl, providerUrl); + for (ProviderInvokerWrapper wrapper : ApplicationModel.getProviderInvokers("org.apache.dubbo.BarService")) { wrapper.setReg(true); } @@ -67,7 +66,7 @@ public void testExecute() throws Exception { Map invokers = Mockito.mock(Map.class); when(invokers.size()).thenReturn(100); when(directory.getUrlInvokerMap()).thenReturn(invokers); - ProviderConsumerRegTable.registerConsumer(consumerInvoker, registryUrl, consumerUrl, directory); + ApplicationModel.registerConsumerInvoker(consumerInvoker, consumerUrl.getServiceKey()); Ls ls = new Ls(); String output = ls.execute(mock(CommandContext.class), null); diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/OfflineTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/OfflineTest.java index f498d5aeb34..8d27d12f309 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/OfflineTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/OfflineTest.java @@ -19,18 +19,17 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.qos.command.CommandContext; import org.apache.dubbo.registry.Registry; -import org.apache.dubbo.registry.support.ProviderConsumerRegTable; -import org.apache.dubbo.registry.support.ProviderInvokerWrapper; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ProviderModel; +import org.apache.dubbo.rpc.model.invoker.ProviderInvokerWrapper; + import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import static org.apache.dubbo.registry.support.ProviderConsumerRegTable.getProviderInvoker; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.core.Is.is; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -38,7 +37,7 @@ public class OfflineTest { @Test public void testExecute() throws Exception { ProviderModel providerModel = mock(ProviderModel.class); - when(providerModel.getServiceName()).thenReturn("org.apache.dubbo.BarService"); + when(providerModel.getServiceKey()).thenReturn("org.apache.dubbo.BarService"); ApplicationModel.initProviderModel("org.apache.dubbo.BarService", providerModel); Invoker providerInvoker = mock(Invoker.class); @@ -48,8 +47,8 @@ public void testExecute() throws Exception { when(providerUrl.getServiceKey()).thenReturn("org.apache.dubbo.BarService"); when(providerUrl.toFullString()).thenReturn("dubbo://localhost:8888/org.apache.dubbo.BarService"); when(providerInvoker.getUrl()).thenReturn(providerUrl); - ProviderConsumerRegTable.registerProvider(providerInvoker, registryUrl, providerUrl); - for (ProviderInvokerWrapper wrapper : getProviderInvoker("org.apache.dubbo.BarService")) { + ApplicationModel.registerProviderInvoker(providerInvoker, registryUrl, providerUrl); + for (ProviderInvokerWrapper wrapper : ApplicationModel.getProviderInvokers("org.apache.dubbo.BarService")) { wrapper.setReg(true); } @@ -60,7 +59,7 @@ public void testExecute() throws Exception { String output = offline.execute(mock(CommandContext.class), new String[]{"org.apache.dubbo.BarService"}); assertThat(output, containsString("OK")); Mockito.verify(registry).unregister(providerUrl); - for (ProviderInvokerWrapper wrapper : getProviderInvoker("org.apache.dubbo.BarService")) { + for (ProviderInvokerWrapper wrapper : ApplicationModel.getProviderInvokers("org.apache.dubbo.BarService")) { assertThat(wrapper.isReg(), is(false)); } diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/OnlineTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/OnlineTest.java index 71132c09551..7474b68a516 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/OnlineTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/OnlineTest.java @@ -19,16 +19,15 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.qos.command.CommandContext; import org.apache.dubbo.registry.Registry; -import org.apache.dubbo.registry.support.ProviderConsumerRegTable; -import org.apache.dubbo.registry.support.ProviderInvokerWrapper; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ProviderModel; +import org.apache.dubbo.rpc.model.invoker.ProviderInvokerWrapper; + import org.junit.jupiter.api.Test; -import static org.apache.dubbo.registry.support.ProviderConsumerRegTable.getProviderInvoker; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -37,7 +36,7 @@ public class OnlineTest { @Test public void testExecute() throws Exception { ProviderModel providerModel = mock(ProviderModel.class); - when(providerModel.getServiceName()).thenReturn("org.apache.dubbo.BarService"); + when(providerModel.getServiceKey()).thenReturn("org.apache.dubbo.BarService"); ApplicationModel.initProviderModel("org.apache.dubbo.BarService", providerModel); Invoker providerInvoker = mock(Invoker.class); @@ -47,7 +46,7 @@ public void testExecute() throws Exception { when(providerUrl.getServiceKey()).thenReturn("org.apache.dubbo.BarService"); when(providerUrl.toFullString()).thenReturn("dubbo://localhost:8888/org.apache.dubbo.BarService"); when(providerInvoker.getUrl()).thenReturn(providerUrl); - ProviderConsumerRegTable.registerProvider(providerInvoker, registryUrl, providerUrl); + ApplicationModel.registerProviderInvoker(providerInvoker, registryUrl, providerUrl); Registry registry = mock(Registry.class); TestRegistryFactory.registry = registry; @@ -55,7 +54,7 @@ public void testExecute() throws Exception { Online online = new Online(); String output = online.execute(mock(CommandContext.class), new String[]{"org.apache.dubbo.BarService"}); assertThat(output, equalTo("OK")); - for (ProviderInvokerWrapper wrapper : getProviderInvoker("org.apache.dubbo.BarService")) { + for (ProviderInvokerWrapper wrapper : ApplicationModel.getProviderInvokers("org.apache.dubbo.BarService")) { assertTrue(wrapper.isReg()); } } diff --git a/dubbo-registry/dubbo-registry-api/pom.xml b/dubbo-registry/dubbo-registry-api/pom.xml index 44eb895b273..7ae8b752d2c 100644 --- a/dubbo-registry/dubbo-registry-api/pom.xml +++ b/dubbo-registry/dubbo-registry-api/pom.xml @@ -32,12 +32,12 @@ org.apache.dubbo - dubbo-cluster + dubbo-common ${project.parent.version} org.apache.dubbo - dubbo-configcenter-api + dubbo-cluster ${project.parent.version} @@ -64,7 +64,12 @@ org.apache.dubbo - dubbo-metadata + dubbo-metadata-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-metadata-report-api ${project.parent.version} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ExportedServicesRevisionMetadataCustomizer.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ExportedServicesRevisionMetadataCustomizer.java index 5c1cc8e9d11..56797235a3f 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ExportedServicesRevisionMetadataCustomizer.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ExportedServicesRevisionMetadataCustomizer.java @@ -18,8 +18,8 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.compiler.support.ClassUtils; -import org.apache.dubbo.metadata.LocalMetadataService; import org.apache.dubbo.metadata.MetadataService; +import org.apache.dubbo.metadata.WritableMetadataService; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.registry.client.ServiceInstanceMetadataCustomizer; @@ -47,8 +47,8 @@ protected String buildMetadataKey(ServiceInstance serviceInstance) { @Override protected String buildMetadataValue(ServiceInstance serviceInstance) { - LocalMetadataService localMetadataService = LocalMetadataService.getDefaultExtension(); - List exportedURLs = localMetadataService.getExportedURLs(); + WritableMetadataService writableMetadataService = WritableMetadataService.getDefaultExtension(); + List exportedURLs = writableMetadataService.getExportedURLs(); Object[] data = exportedURLs.stream() .map(URL::valueOf) // String to URL .map(URL::getServiceInterface) // get the service interface diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLParamsMetadataCustomizer.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLParamsMetadataCustomizer.java index 97ba53c3404..b41873d45ca 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLParamsMetadataCustomizer.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLParamsMetadataCustomizer.java @@ -17,8 +17,8 @@ package org.apache.dubbo.registry.client.metadata; import org.apache.dubbo.common.URL; -import org.apache.dubbo.metadata.LocalMetadataService; import org.apache.dubbo.metadata.MetadataService; +import org.apache.dubbo.metadata.WritableMetadataService; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.registry.client.ServiceInstanceMetadataCustomizer; @@ -45,7 +45,7 @@ public String buildMetadataKey(ServiceInstance serviceInstance) { @Override public String buildMetadataValue(ServiceInstance serviceInstance) { - LocalMetadataService localMetadataService = LocalMetadataService.getDefaultExtension(); + WritableMetadataService writableMetadataService = WritableMetadataService.getDefaultExtension(); String serviceInterface = MetadataService.class.getName(); @@ -53,7 +53,7 @@ public String buildMetadataValue(ServiceInstance serviceInstance) { String version = MetadataService.VERSION; - List urls = localMetadataService.getExportedURLs(serviceInterface, group, version); + List urls = writableMetadataService.getExportedURLs(serviceInterface, group, version); return getMetadataServiceParameter(toURLs(urls)); } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/DefaultMetadataServiceProxyFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/proxy/DefaultMetadataServiceProxyFactory.java similarity index 97% rename from dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/DefaultMetadataServiceProxyFactory.java rename to dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/proxy/DefaultMetadataServiceProxyFactory.java index b1b773b5519..58dca64ac10 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/DefaultMetadataServiceProxyFactory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/proxy/DefaultMetadataServiceProxyFactory.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.registry.client.metadata; +package org.apache.dubbo.registry.client.metadata.proxy; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxyFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/proxy/MetadataServiceProxyFactory.java similarity index 88% rename from dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxyFactory.java rename to dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/proxy/MetadataServiceProxyFactory.java index 9a1e337b886..9ec31dff55b 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceProxyFactory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/proxy/MetadataServiceProxyFactory.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.registry.client.metadata; +package org.apache.dubbo.registry.client.metadata.proxy; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.metadata.MetadataService; @@ -29,7 +29,7 @@ * @see MetadataService * @since 2.7.3 */ -@SPI("default") +@SPI("local") public interface MetadataServiceProxyFactory { /** @@ -48,4 +48,8 @@ public interface MetadataServiceProxyFactory { static MetadataServiceProxyFactory getDefaultExtension() { return getExtensionLoader(MetadataServiceProxyFactory.class).getDefaultExtension(); } + + static MetadataServiceProxyFactory getExtension(String name) { + return getExtensionLoader(MetadataServiceProxyFactory.class).getExtension(name); + } } diff --git a/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/mock/MockDynamicConfigurationFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/proxy/RemoteMetadataServiceProxyFactory.java similarity index 64% rename from dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/mock/MockDynamicConfigurationFactory.java rename to dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/proxy/RemoteMetadataServiceProxyFactory.java index 13482b77296..f8303f18500 100644 --- a/dubbo-configcenter/dubbo-configcenter-api/src/test/java/org/apache/dubbo/configcenter/mock/MockDynamicConfigurationFactory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/proxy/RemoteMetadataServiceProxyFactory.java @@ -14,19 +14,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.configcenter.mock; +package org.apache.dubbo.registry.client.metadata.proxy; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.configcenter.AbstractDynamicConfigurationFactory; -import org.apache.dubbo.configcenter.DynamicConfiguration; +import org.apache.dubbo.metadata.MetadataService; +import org.apache.dubbo.metadata.integration.RemoteWritableMetadataService; +import org.apache.dubbo.registry.client.ServiceInstance; /** * */ -public class MockDynamicConfigurationFactory extends AbstractDynamicConfigurationFactory { +public class RemoteMetadataServiceProxyFactory implements MetadataServiceProxyFactory { @Override - protected DynamicConfiguration createDynamicConfiguration(URL url) { - return new MockDynamicConfiguration(url); + public MetadataService getProxy(ServiceInstance serviceInstance) { + return RemoteWritableMetadataService.instance(); } + } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java index 5258d24c9f4..7a135a79680 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java @@ -16,14 +16,14 @@ */ package org.apache.dubbo.registry.integration; +import org.apache.dubbo.common.config.configcenter.ConfigChangeEvent; +import org.apache.dubbo.common.config.configcenter.ConfigChangeType; +import org.apache.dubbo.common.config.configcenter.ConfigurationListener; +import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.constants.CommonConstants; 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.configcenter.ConfigChangeEvent; -import org.apache.dubbo.configcenter.ConfigChangeType; -import org.apache.dubbo.configcenter.ConfigurationListener; -import org.apache.dubbo.configcenter.DynamicConfiguration; import org.apache.dubbo.rpc.cluster.Configurator; import org.apache.dubbo.rpc.cluster.configurator.parser.ConfigParser; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java index 2f3a83567a4..20759a562f8 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java @@ -19,6 +19,7 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.Version; +import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -27,7 +28,6 @@ import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.UrlUtils; -import org.apache.dubbo.configcenter.DynamicConfiguration; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.remoting.Constants; @@ -604,6 +604,11 @@ public Class getInterface() { return serviceType; } + @Override + public List> getAllInvokers() { + return invokers; + } + @Override public URL getUrl() { return this.overrideDirectoryUrl; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java index 9afa7ab9fd9..a3943882fd3 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java @@ -19,6 +19,7 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.config.ConfigurationUtils; +import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -26,13 +27,10 @@ import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.UrlUtils; -import org.apache.dubbo.configcenter.DynamicConfiguration; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.RegistryFactory; import org.apache.dubbo.registry.RegistryService; -import org.apache.dubbo.registry.support.ProviderConsumerRegTable; -import org.apache.dubbo.registry.support.ProviderInvokerWrapper; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; @@ -41,6 +39,7 @@ import org.apache.dubbo.rpc.cluster.Cluster; import org.apache.dubbo.rpc.cluster.Configurator; import org.apache.dubbo.rpc.model.ApplicationModel; +import org.apache.dubbo.rpc.model.invoker.ProviderInvokerWrapper; import org.apache.dubbo.rpc.protocol.InvokerWrapper; import java.util.ArrayList; @@ -211,7 +210,7 @@ public Exporter export(final Invoker originInvoker) throws RpcExceptio // url to registry final Registry registry = getRegistry(originInvoker); final URL registeredProviderUrl = getRegisteredProviderUrl(providerUrl, registryUrl); - ProviderInvokerWrapper providerInvokerWrapper = ProviderConsumerRegTable.registerProvider(originInvoker, + ProviderInvokerWrapper providerInvokerWrapper = ApplicationModel.registerProviderInvoker(originInvoker, registryUrl, registeredProviderUrl); //to judge if we need to delay publish boolean register = registeredProviderUrl.getParameter("register", true); @@ -254,8 +253,8 @@ public void reExport(final Invoker originInvoker, URL newInvokerUrl) { final URL registeredProviderUrl = getRegisteredProviderUrl(newInvokerUrl, registryUrl); //decide if we need to re-publish - ProviderInvokerWrapper providerInvokerWrapper = ProviderConsumerRegTable.getProviderWrapper(registeredProviderUrl, originInvoker); - ProviderInvokerWrapper newProviderInvokerWrapper = ProviderConsumerRegTable.registerProvider(originInvoker, registryUrl, registeredProviderUrl); + ProviderInvokerWrapper providerInvokerWrapper = ApplicationModel.getProviderInvoker(registeredProviderUrl.getServiceKey(), originInvoker); + ProviderInvokerWrapper newProviderInvokerWrapper = ApplicationModel.registerProviderInvoker(originInvoker, registryUrl, registeredProviderUrl); /** * Only if the new url going to Registry is different with the previous one should we do unregister and register. */ @@ -412,7 +411,7 @@ private Invoker doRefer(Cluster cluster, Registry registry, Class type PROVIDERS_CATEGORY + "," + CONFIGURATORS_CATEGORY + "," + ROUTERS_CATEGORY)); Invoker invoker = cluster.join(directory); - ProviderConsumerRegTable.registerConsumer(invoker, url, subscribeUrl, directory); + ApplicationModel.registerConsumerInvoker(invoker, subscribeUrl.getServiceKey()); return invoker; } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ConsumerInvokerWrapper.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ConsumerInvokerWrapper.java deleted file mode 100644 index 141634de25b..00000000000 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ConsumerInvokerWrapper.java +++ /dev/null @@ -1,88 +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.support; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.registry.integration.RegistryDirectory; -import org.apache.dubbo.rpc.Invocation; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Result; -import org.apache.dubbo.rpc.RpcException; - -/** - * @date 2017/11/23 - */ -public class ConsumerInvokerWrapper implements Invoker { - private Invoker invoker; - private URL originUrl; - private URL registryUrl; - private URL consumerUrl; - private RegistryDirectory registryDirectory; - - public ConsumerInvokerWrapper(Invoker invoker, URL registryUrl, URL consumerUrl, RegistryDirectory registryDirectory) { - this.invoker = invoker; - this.originUrl = URL.valueOf(invoker.getUrl().toFullString()); - this.registryUrl = URL.valueOf(registryUrl.toFullString()); - this.consumerUrl = consumerUrl; - this.registryDirectory = registryDirectory; - } - - @Override - public Class getInterface() { - return invoker.getInterface(); - } - - @Override - public URL getUrl() { - return invoker.getUrl(); - } - - @Override - public boolean isAvailable() { - return invoker.isAvailable(); - } - - @Override - public Result invoke(Invocation invocation) throws RpcException { - return invoker.invoke(invocation); - } - - @Override - public void destroy() { - invoker.destroy(); - } - - public URL getOriginUrl() { - return originUrl; - } - - public URL getRegistryUrl() { - return registryUrl; - } - - public Invoker getInvoker() { - return invoker; - } - - public URL getConsumerUrl() { - return consumerUrl; - } - - public RegistryDirectory getRegistryDirectory() { - return registryDirectory; - } -} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ProviderConsumerRegTable.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ProviderConsumerRegTable.java deleted file mode 100644 index 9af39888e21..00000000000 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ProviderConsumerRegTable.java +++ /dev/null @@ -1,112 +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.support; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.ConcurrentHashSet; -import org.apache.dubbo.registry.integration.RegistryDirectory; -import org.apache.dubbo.rpc.Invoker; - -import java.util.Collections; -import java.util.Map; -import java.util.Objects; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * @date 2017/11/23 - */ -public class ProviderConsumerRegTable { - public static ConcurrentHashMap> providerInvokers = new ConcurrentHashMap<>(); - public static ConcurrentHashMap> consumerInvokers = new ConcurrentHashMap<>(); - - public static ProviderInvokerWrapper registerProvider(Invoker invoker, URL registryUrl, URL providerUrl) { - ProviderInvokerWrapper wrapperInvoker = new ProviderInvokerWrapper<>(invoker, registryUrl, providerUrl); - String serviceUniqueName = providerUrl.getServiceKey(); - ConcurrentMap invokers = providerInvokers.get(serviceUniqueName); - if (invokers == null) { - providerInvokers.putIfAbsent(serviceUniqueName, new ConcurrentHashMap<>()); - invokers = providerInvokers.get(serviceUniqueName); - } - invokers.put(invoker, wrapperInvoker); - return wrapperInvoker; - } - - /*public static ProviderInvokerWrapper removeProviderWrapper(Invoker invoker, URL providerUrl) { - String serviceUniqueName = providerUrl.getServiceKey(); - Set invokers = providerInvokers.get(serviceUniqueName); - if (invokers == null) { - return null; - } - return invokers.remove(new ProviderIndvokerWrapper(invoker, null, null)); - }*/ - - public static Set getProviderInvoker(String serviceUniqueName) { - ConcurrentMap invokers = providerInvokers.get(serviceUniqueName); - if (invokers == null) { - return Collections.emptySet(); - } - return new HashSet<>(invokers.values()); - } - - public static ProviderInvokerWrapper getProviderWrapper(URL registeredProviderUrl, Invoker invoker) { - String serviceUniqueName = registeredProviderUrl.getServiceKey(); - ConcurrentMap invokers = providerInvokers.get(serviceUniqueName); - if (invokers == null) { - return null; - } - - for (Map.Entry entry : invokers.entrySet()) { - if (entry.getKey() == invoker) { - return entry.getValue(); - } - } - - return null; - } - - public static void registerConsumer(Invoker invoker, URL registryUrl, URL consumerUrl, RegistryDirectory registryDirectory) { - ConsumerInvokerWrapper wrapperInvoker = new ConsumerInvokerWrapper(invoker, registryUrl, consumerUrl, registryDirectory); - String serviceUniqueName = consumerUrl.getServiceKey(); - Set invokers = consumerInvokers.get(serviceUniqueName); - if (invokers == null) { - consumerInvokers.putIfAbsent(serviceUniqueName, new ConcurrentHashSet()); - invokers = consumerInvokers.get(serviceUniqueName); - } - invokers.add(wrapperInvoker); - } - - public static Set getConsumerInvoker(String serviceUniqueName) { - Set invokers = consumerInvokers.get(serviceUniqueName); - return invokers == null ? Collections.emptySet() : invokers; - } - - public static boolean isRegistered(String serviceUniqueName) { - Set providerInvokerWrapperSet = ProviderConsumerRegTable.getProviderInvoker(serviceUniqueName); - return providerInvokerWrapperSet.stream().anyMatch(ProviderInvokerWrapper::isReg); - } - - public static int getConsumerAddressNum(String serviceUniqueName) { - Set providerInvokerWrapperSet = ProviderConsumerRegTable.getConsumerInvoker(serviceUniqueName); - return providerInvokerWrapperSet.stream() - .map(w -> w.getRegistryDirectory().getUrlInvokerMap()) - .filter(Objects::nonNull) - .mapToInt(Map::size).sum(); - } -} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java index 34e209e3418..3d1f613b14c 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ServiceOrientedRegistry.java @@ -20,15 +20,15 @@ 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.LocalMetadataService; import org.apache.dubbo.metadata.MetadataService; import org.apache.dubbo.metadata.ServiceNameMapping; +import org.apache.dubbo.metadata.WritableMetadataService; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.client.ServiceDiscovery; import org.apache.dubbo.registry.client.ServiceDiscoveryFactory; import org.apache.dubbo.registry.client.ServiceInstance; -import org.apache.dubbo.registry.client.metadata.MetadataServiceProxyFactory; +import org.apache.dubbo.registry.client.metadata.proxy.MetadataServiceProxyFactory; import org.apache.dubbo.registry.client.selector.ServiceInstanceSelector; import java.util.ArrayList; @@ -50,6 +50,7 @@ import static java.util.stream.Stream.of; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.METADATA_DEFAULT; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; @@ -61,6 +62,7 @@ import static org.apache.dubbo.common.utils.CollectionUtils.isEmpty; import static org.apache.dubbo.common.utils.CollectionUtils.isNotEmpty; import static org.apache.dubbo.common.utils.StringUtils.isBlank; +import static org.apache.dubbo.metadata.support.Constants.METADATA_REPORT_KEY; import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getExportedServicesRevision; import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getMetadataServiceURLsParams; import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getProviderHost; @@ -87,7 +89,7 @@ public class ServiceOrientedRegistry extends FailbackRegistry { private final ServiceNameMapping serviceNameMapping; - private final LocalMetadataService localMetadataService; + private final WritableMetadataService writableMetadataService; private final MetadataServiceProxyFactory metadataServiceProxyFactory; @@ -96,8 +98,10 @@ public ServiceOrientedRegistry(URL registryURL) { this.serviceDiscovery = buildServiceDiscovery(registryURL); this.subscribedServices = buildSubscribedServices(registryURL); this.serviceNameMapping = ServiceNameMapping.getDefaultExtension(); - this.localMetadataService = LocalMetadataService.getDefaultExtension(); - this.metadataServiceProxyFactory = MetadataServiceProxyFactory.getDefaultExtension(); + + String metadata = registryURL.getParameter(METADATA_REPORT_KEY, METADATA_DEFAULT); + this.writableMetadataService = WritableMetadataService.getExtension(metadata); + this.metadataServiceProxyFactory = MetadataServiceProxyFactory.getExtension(metadata); } private Set buildSubscribedServices(URL url) { @@ -139,7 +143,7 @@ public void doRegister(URL url) { if (!shouldRegister(url)) { // Should Not Register return; } - if (localMetadataService.exportURL(url)) { + if (writableMetadataService.exportURL(url)) { if (logger.isInfoEnabled()) { logger.info(format("The URL[%s] registered successfully.", url.toString())); } @@ -155,7 +159,7 @@ public void doUnregister(URL url) { if (!shouldRegister(url)) { return; } - if (localMetadataService.unexportURL(url)) { + if (writableMetadataService.unexportURL(url)) { if (logger.isInfoEnabled()) { logger.info(format("The URL[%s] deregistered successfully.", url.toString())); } @@ -176,7 +180,7 @@ public void doSubscribe(URL url, NotifyListener listener) { @Override public void doUnsubscribe(URL url, NotifyListener listener) { - localMetadataService.unsubscribeURL(url); + writableMetadataService.unsubscribeURL(url); } @Override @@ -193,7 +197,7 @@ public void destroy() { protected void subscribeURLs(URL url, NotifyListener listener) { - localMetadataService.subscribeURL(url); + writableMetadataService.subscribeURL(url); Set serviceNames = getServices(url); diff --git a/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.metadata.MetadataServiceProxyFactory b/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.metadata.MetadataServiceProxyFactory deleted file mode 100644 index 48860587024..00000000000 --- a/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.metadata.MetadataServiceProxyFactory +++ /dev/null @@ -1 +0,0 @@ -default=org.apache.dubbo.registry.client.metadata.DefaultMetadataServiceProxyFactory \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.metadata.proxy.MetadataServiceProxyFactory b/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.metadata.proxy.MetadataServiceProxyFactory new file mode 100644 index 00000000000..d9283dec444 --- /dev/null +++ b/dubbo-registry/dubbo-registry-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.metadata.proxy.MetadataServiceProxyFactory @@ -0,0 +1,2 @@ +local=org.apache.dubbo.registry.client.metadata.proxy.DefaultMetadataServiceProxyFactory +remote=org.apache.dubbo.registry.client.metadata.proxy.RemoteMetadataServiceProxyFactory \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/ServiceOrientedRegistryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/ServiceOrientedRegistryTest.java index bcbd846495e..73b88d48f6a 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/ServiceOrientedRegistryTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/ServiceOrientedRegistryTest.java @@ -17,7 +17,7 @@ package org.apache.dubbo.registry.support; import org.apache.dubbo.common.URL; -import org.apache.dubbo.metadata.LocalMetadataService; +import org.apache.dubbo.metadata.WritableMetadataService; import org.apache.dubbo.registry.NotifyListener; import org.junit.jupiter.api.BeforeEach; @@ -66,7 +66,7 @@ public class ServiceOrientedRegistryTest { private static URL url2 = url.setProtocol("rest"); - private LocalMetadataService metadataService; + private WritableMetadataService metadataService; private ServiceOrientedRegistry registry; @@ -75,7 +75,7 @@ public class ServiceOrientedRegistryTest { @BeforeEach public void init() { registry = ServiceOrientedRegistry.create(registryURL); - metadataService = LocalMetadataService.getDefaultExtension(); + metadataService = WritableMetadataService.getDefaultExtension(); notifyListener = new MyNotifyListener(); } diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryFactory.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryFactory.java index 65ba64fc029..929b17ecaea 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryFactory.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryFactory.java @@ -19,10 +19,6 @@ import org.apache.dubbo.registry.client.ServiceDiscovery; import org.apache.dubbo.registry.client.ServiceDiscoveryFactory; -import com.alibaba.nacos.api.naming.NamingService; - -import static org.apache.dubbo.registry.nacos.util.NacosNamingServiceUtils.createNamingService; - /** * Nacos {@link ServiceDiscoveryFactory} * diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java index 33dcc908e1b..2860a29dad6 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java @@ -16,10 +16,14 @@ */ package org.apache.dubbo.rpc.model; +import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.model.invoker.ProviderInvokerWrapper; import java.util.Collection; +import java.util.Collections; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -33,15 +37,14 @@ * adjust project structure in order to fully utilize the methods introduced here. */ public class ApplicationModel { - protected static final Logger LOGGER = LoggerFactory.getLogger(ApplicationModel.class); /** - * full qualified class name -> provided service + * serviceKey -> exported service */ private static final ConcurrentMap PROVIDED_SERVICES = new ConcurrentHashMap<>(); /** - * full qualified class name -> subscribe service + * serviceKey -> referred service */ private static final ConcurrentMap CONSUMED_SERVICES = new ConcurrentHashMap<>(); @@ -55,12 +58,12 @@ public static Collection allProviderModels() { return PROVIDED_SERVICES.values(); } - public static ProviderModel getProviderModel(String serviceName) { - return PROVIDED_SERVICES.get(serviceName); + public static ProviderModel getProviderModel(String serviceKey) { + return PROVIDED_SERVICES.get(serviceKey); } - public static ConsumerModel getConsumerModel(String serviceName) { - return CONSUMED_SERVICES.get(serviceName); + public static ConsumerModel getConsumerModel(String serviceKey) { + return CONSUMED_SERVICES.get(serviceKey); } public static void initConsumerModel(String serviceName, ConsumerModel consumerModel) { @@ -83,6 +86,39 @@ public static void setApplication(String application) { ApplicationModel.application = application; } + public static ProviderInvokerWrapper registerProviderInvoker(Invoker invoker, URL registryUrl, URL providerUrl) { + ProviderInvokerWrapper wrapperInvoker = new ProviderInvokerWrapper<>(invoker, registryUrl, providerUrl); + ProviderModel providerModel = getProviderModel(providerUrl.getServiceKey()); + providerModel.addInvoker(wrapperInvoker); + return wrapperInvoker; + } + + public static Collection getProviderInvokers(String serviceKey) { + ProviderModel providerModel = getProviderModel(serviceKey); + if (providerModel == null) { + return Collections.emptySet(); + } + return providerModel.getInvokers(); + } + + public static ProviderInvokerWrapper getProviderInvoker(String serviceKey, Invoker invoker) { + ProviderModel providerModel = getProviderModel(serviceKey); + return providerModel.getInvoker(invoker.getUrl().getProtocol()); + } + + public static boolean isRegistered(String serviceKey) { + return getProviderInvokers(serviceKey).stream().anyMatch(ProviderInvokerWrapper::isReg); + } + + public static void registerConsumerInvoker(Invoker invoker, String serviceKey) { + ConsumerModel consumerModel = getConsumerModel(serviceKey); + consumerModel.setInvoker(invoker); + } + + public static Invoker getConsumerInvoker(String serviceKey) { + return (Invoker) getConsumerModel(serviceKey).getInvoker(); + } + /** * For unit test */ diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ConsumerModel.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ConsumerModel.java index 4c990a5088c..851cd062133 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ConsumerModel.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ConsumerModel.java @@ -17,6 +17,7 @@ package org.apache.dubbo.rpc.model; import org.apache.dubbo.common.utils.Assert; +import org.apache.dubbo.rpc.Invoker; import java.lang.reflect.Method; import java.util.ArrayList; @@ -29,34 +30,35 @@ * Consumer Model which is about subscribed services. */ public class ConsumerModel { - private final Object proxyObject; - private final String serviceName; + private final String serviceKey; private final Class serviceInterfaceClass; private final Map methodModels = new IdentityHashMap(); + private Object proxyObject; + private Invoker invoker; + /** * This constructor create an instance of ConsumerModel and passed objects should not be null. * If service name, service instance, proxy object,methods should not be null. If these are null * then this constructor will throw {@link IllegalArgumentException} - * @param serviceName Name of the service. + * @param serviceKey Name of the service. * @param serviceInterfaceClass Service interface class. * @param proxyObject Proxy object. * @param methods Methods of service class * @param attributes Attributes of methods. */ - public ConsumerModel(String serviceName + public ConsumerModel(String serviceKey , Class serviceInterfaceClass , Object proxyObject , Method[] methods , Map attributes) { - Assert.notEmptyString(serviceName, "Service name can't be null or blank"); + Assert.notEmptyString(serviceKey, "Service name can't be null or blank"); Assert.notNull(serviceInterfaceClass, "Service interface class can't null"); - Assert.notNull(proxyObject, "Proxy object can't be null"); Assert.notNull(methods, "Methods can't be null"); - this.serviceName = serviceName; + this.serviceKey = serviceKey; this.serviceInterfaceClass = serviceInterfaceClass; this.proxyObject = proxyObject; for (Method method : methods) { @@ -106,7 +108,19 @@ public Class getServiceInterfaceClass() { return serviceInterfaceClass; } - public String getServiceName() { - return serviceName; + public String getServiceKey() { + return serviceKey; + } + + public void setProxyObject(Object proxyObject) { + this.proxyObject = proxyObject; + } + + public Invoker getInvoker() { + return invoker; + } + + public void setInvoker(Invoker invoker) { + this.invoker = invoker; } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ProviderModel.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ProviderModel.java index 6fb9bebd7ea..48d9ac76d4d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ProviderModel.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/ProviderModel.java @@ -16,9 +16,13 @@ */ package org.apache.dubbo.rpc.model; +import org.apache.dubbo.rpc.model.invoker.ProviderInvokerWrapper; + import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -27,17 +31,20 @@ * ProviderModel which is about published services */ public class ProviderModel { - private final String serviceName; + private final String serviceKey; private final Object serviceInstance; private final Class serviceInterfaceClass; private final Map> methods = new HashMap>(); - public ProviderModel(String serviceName, Object serviceInstance, Class serviceInterfaceClass) { + private Map protocolInvokers = new HashMap<>(); + + + public ProviderModel(String serviceKey, Object serviceInstance, Class serviceInterfaceClass) { if (null == serviceInstance) { - throw new IllegalArgumentException("Service[" + serviceName + "]Target is NULL."); + throw new IllegalArgumentException("Service[" + serviceKey + "]Target is NULL."); } - this.serviceName = serviceName; + this.serviceKey = serviceKey; this.serviceInstance = serviceInstance; this.serviceInterfaceClass = serviceInterfaceClass; @@ -45,8 +52,8 @@ public ProviderModel(String serviceName, Object serviceInstance, Class servic } - public String getServiceName() { - return serviceName; + public String getServiceKey() { + return serviceKey; } public Class getServiceInterfaceClass() { @@ -89,8 +96,20 @@ private void initMethod() { methodModels = new ArrayList(1); methods.put(method.getName(), methodModels); } - methodModels.add(new ProviderMethodModel(method, serviceName)); + methodModels.add(new ProviderMethodModel(method, serviceKey)); } } + + public void addInvoker(ProviderInvokerWrapper invoker) { + protocolInvokers.put(invoker.getUrl().getProtocol(), invoker); + } + + public ProviderInvokerWrapper getInvoker(String protocol) { + return protocolInvokers.get(protocol); + } + + public Collection getInvokers() { + return Collections.unmodifiableCollection(protocolInvokers.values()); + } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ProviderInvokerWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/invoker/ProviderInvokerWrapper.java similarity index 95% rename from dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ProviderInvokerWrapper.java rename to dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/invoker/ProviderInvokerWrapper.java index ce079b743e4..cc1958959db 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/ProviderInvokerWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/model/invoker/ProviderInvokerWrapper.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.registry.support; +package org.apache.dubbo.rpc.model.invoker; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; @@ -32,7 +32,7 @@ public class ProviderInvokerWrapper implements Invoker { private URL providerUrl; private volatile boolean isReg; - public ProviderInvokerWrapper(Invoker invoker,URL registryUrl,URL providerUrl) { + public ProviderInvokerWrapper(Invoker invoker, URL registryUrl, URL providerUrl) { this.invoker = invoker; this.originUrl = URL.valueOf(invoker.getUrl().toFullString()); this.registryUrl = URL.valueOf(registryUrl.toFullString()); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/pom.xml b/dubbo-rpc/dubbo-rpc-dubbo/pom.xml index dc6cd2295f8..99fdf5a8b96 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/pom.xml +++ b/dubbo-rpc/dubbo-rpc-dubbo/pom.xml @@ -41,8 +41,8 @@ org.apache.dubbo - dubbo-config-api - ${project.version} + dubbo-cluster + ${project.parent.version} org.apache.dubbo @@ -59,11 +59,6 @@ - - org.apache.dubbo - dubbo-configcenter-api - ${project.parent.version} - org.apache.dubbo dubbo-remoting-netty4 diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/InvokeTelnetHandler.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/InvokeTelnetHandler.java index 3998026b70b..de3a2a5e7c1 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/InvokeTelnetHandler.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/InvokeTelnetHandler.java @@ -152,7 +152,7 @@ public String telnet(Channel channel, String message) { private boolean isServiceMatch(String service, ProviderModel provider) { - return provider.getServiceName().equalsIgnoreCase(service) + return provider.getServiceKey().equalsIgnoreCase(service) || provider.getServiceInterfaceClass().getSimpleName().equalsIgnoreCase(service) || provider.getServiceInterfaceClass().getName().equalsIgnoreCase(service) || StringUtils.isEmpty(service); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/ListTelnetHandler.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/ListTelnetHandler.java index 0eaf1a22d0a..9dd0a8a36b0 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/ListTelnetHandler.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/telnet/ListTelnetHandler.java @@ -22,6 +22,7 @@ import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.telnet.TelnetHandler; import org.apache.dubbo.remoting.telnet.support.Help; +import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ConsumerMethodModel; import org.apache.dubbo.rpc.model.ConsumerModel; @@ -30,9 +31,6 @@ import java.lang.reflect.Method; -import static org.apache.dubbo.registry.support.ProviderConsumerRegTable.getConsumerAddressNum; -import static org.apache.dubbo.registry.support.ProviderConsumerRegTable.isRegistered; - /** * ListTelnetHandler handler list services and its methods details. */ @@ -87,11 +85,11 @@ private void printAllProvidedServices(StringBuilder buf, boolean detail) { } for (ProviderModel provider : ApplicationModel.allProviderModels()) { - buf.append(provider.getServiceName()); + buf.append(provider.getServiceKey()); if (detail) { buf.append(" -> "); buf.append(" published: "); - buf.append(isRegistered(provider.getServiceName()) ? "Y" : "N"); + buf.append(ApplicationModel.isRegistered(provider.getServiceKey()) ? "Y" : "N"); } buf.append("\r\n"); } @@ -103,11 +101,11 @@ private void printAllReferredServices(StringBuilder buf, boolean detail) { } for (ConsumerModel consumer : ApplicationModel.allConsumerModels()) { - buf.append(consumer.getServiceName()); + buf.append(consumer.getServiceKey()); if (detail) { buf.append(" -> "); buf.append(" addresses: "); - buf.append(getConsumerAddressNum(consumer.getServiceName())); + buf.append(((AbstractClusterInvoker) consumer.getInvoker()).getDirectory().getAllInvokers().size()); } } } @@ -120,7 +118,7 @@ private void printSpecifiedService(String service, StringBuilder buf, boolean de private void printSpecifiedProvidedService(String service, StringBuilder buf, boolean detail) { for (ProviderModel provider : ApplicationModel.allProviderModels()) { if (isProviderMatched(service,provider)) { - buf.append(provider.getServiceName()).append(" (as provider):\r\n"); + buf.append(provider.getServiceKey()).append(" (as provider):\r\n"); for (ProviderMethodModel method : provider.getAllMethods()) { printMethod(method.getMethod(), buf, detail); } @@ -131,7 +129,7 @@ private void printSpecifiedProvidedService(String service, StringBuilder buf, bo private void printSpecifiedReferredService(String service, StringBuilder buf, boolean detail) { for (ConsumerModel consumer : ApplicationModel.allConsumerModels()) { if (isConsumerMatcher(service,consumer)) { - buf.append(consumer.getServiceName()).append(" (as consumer):\r\n"); + buf.append(consumer.getServiceKey()).append(" (as consumer):\r\n"); for (ConsumerMethodModel method : consumer.getAllMethods()) { printMethod(method.getMethod(), buf, detail); } @@ -149,13 +147,13 @@ private void printMethod(Method method, StringBuilder buf, boolean detail) { } private boolean isProviderMatched(String service, ProviderModel provider) { - return service.equalsIgnoreCase(provider.getServiceName()) + return service.equalsIgnoreCase(provider.getServiceKey()) || service.equalsIgnoreCase(provider.getServiceInterfaceClass().getName()) || service.equalsIgnoreCase(provider.getServiceInterfaceClass().getSimpleName()); } private boolean isConsumerMatcher(String service,ConsumerModel consumer) { - return service.equalsIgnoreCase(consumer.getServiceName()) + return service.equalsIgnoreCase(consumer.getServiceKey()) || service.equalsIgnoreCase(consumer.getServiceInterfaceClass().getName()) || service.equalsIgnoreCase(consumer.getServiceInterfaceClass().getSimpleName()); } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.telnet.TelnetHandler b/dubbo-rpc/dubbo-rpc-dubbo/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.telnet.TelnetHandler index 99111639c26..ef32515fe7a 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.telnet.TelnetHandler +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.telnet.TelnetHandler @@ -5,5 +5,4 @@ pwd=org.apache.dubbo.rpc.protocol.dubbo.telnet.CurrentTelnetHandler invoke=org.apache.dubbo.rpc.protocol.dubbo.telnet.InvokeTelnetHandler trace=org.apache.dubbo.rpc.protocol.dubbo.telnet.TraceTelnetHandler count=org.apache.dubbo.rpc.protocol.dubbo.telnet.CountTelnetHandler -select=org.apache.dubbo.rpc.protocol.dubbo.telnet.SelectTelnetHandler -shutdown=org.apache.dubbo.rpc.protocol.dubbo.telnet.ShutdownTelnetHandler \ No newline at end of file +select=org.apache.dubbo.rpc.protocol.dubbo.telnet.SelectTelnetHandler \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java index 500a95eeacb..1a1b0fd4f11 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java @@ -30,7 +30,6 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import static org.apache.dubbo.config.Constants.ON_THROW_METHOD_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -77,7 +76,7 @@ public void testSyncCallbackHasException() throws RpcException, Throwable { AppResponse result = new AppResponse(); result.setException(new RuntimeException()); given(invoker.invoke(invocation)).willReturn(result); - URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1&" + ON_THROW_METHOD_KEY + "=echo"); + URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1&onthrow.method=echo"); given(invoker.getUrl()).willReturn(url); eventFilter.invoke(invoker, invocation).recreate(); diff --git a/pom.xml b/pom.xml index 084674489c5..7bdde08179c 100644 --- a/pom.xml +++ b/pom.xml @@ -146,7 +146,6 @@ dubbo-bom dubbo-all dubbo-distribution - dubbo-metadata-report dubbo-configcenter dubbo-dependencies dubbo-event From 3fd05f77234afabc74f4e0f73aa512f77118ed48 Mon Sep 17 00:00:00 2001 From: "ken.lj" Date: Thu, 20 Jun 2019 17:11:55 +0800 Subject: [PATCH 43/46] unify metadata implementation --- dubbo-bootstrap/pom.xml | 7 ++ .../dubbo/bootstrap/DubboBootstrap.java | 13 +++- .../DubboServiceProviderBootstrap.java | 7 +- .../common/constants/CommonConstants.java | 2 + .../dubbo/config/ApplicationConfig.java | 12 ++++ .../apache/dubbo/config/ReferenceConfig.java | 11 +-- .../apache/dubbo/config/RegistryConfig.java | 13 ---- .../apache/dubbo/config/ServiceConfig.java | 10 +-- .../config/builders/ApplicationBuilder.java | 7 ++ .../builders/MetadataReportBuilder.java | 4 ++ .../main/resources/META-INF/compat/dubbo.xsd | 10 +-- .../src/main/resources/META-INF/dubbo.xsd | 10 +-- .../metadata/report}/MetadataReport.java | 10 +-- .../report}/MetadataReportFactory.java | 2 +- .../identifier/MetadataIdentifier.java | 25 +++---- .../support/AbstractMetadataReport.java | 23 +++--- .../AbstractMetadataReportFactory.java | 6 +- .../metadata/report}/support/Constants.java | 2 +- .../store}/RemoteWritableMetadataService.java | 43 +++--------- ...che.dubbo.metadata.WritableMetadataService | 3 +- .../AbstractMetadataReportFactoryTest.java | 12 +++- .../support/AbstractMetadataReportTest.java | 14 +++- .../store}/InterfaceNameTestService.java | 2 +- .../store}/InterfaceNameTestService2.java | 2 +- .../RemoteWritableMeatadataServiceTest.java} | 37 +++++----- .../metadata/store}/RetryTestService.java | 2 +- .../test/JTestMetadataReport4Test.java | 10 ++- .../test/JTestMetadataReportFactory4Test.java | 6 +- .../dubbo-metadata-report-api/pom.xml | 70 ------------------- ...che.dubbo.metadata.WritableMetadataService | 1 - ...dubbo.metadata.store.MetadataReportFactory | 1 - .../dubbo-metadata-report-consul/pom.xml | 2 +- .../store/consul/ConsulMetadataReport.java | 9 ++- .../consul/ConsulMetadataReportFactory.java | 4 +- ...bbo.metadata.report.MetadataReportFactory} | 0 .../dubbo-metadata-report-etcd/pom.xml | 2 +- .../store/etcd/EtcdMetadataReport.java | 9 ++- .../store/etcd/EtcdMetadataReportFactory.java | 4 +- ...bbo.metadata.report.MetadataReportFactory} | 0 .../store/etcd/EtcdMetadataReportTest.java | 2 +- .../dubbo-metadata-report-nacos/pom.xml | 2 +- .../store/nacos/NacosMetadataReport.java | 9 ++- .../nacos/NacosMetadataReportFactory.java | 4 +- ...bbo.metadata.report.MetadataReportFactory} | 0 .../store/nacos/NacosMetadataReportTest.java | 2 +- .../dubbo-metadata-report-redis/pom.xml | 2 +- .../store/redis/RedisMetadataReport.java | 11 ++- .../redis/RedisMetadataReportFactory.java | 4 +- ...bbo.metadata.report.MetadataReportFactory} | 0 .../store/redis/RedisMetadataReportTest.java | 4 +- .../dubbo-metadata-report-zookeeper/pom.xml | 2 +- .../zookeeper/ZookeeperMetadataReport.java | 9 ++- .../ZookeeperMetadataReportFactory.java | 4 +- ...bbo.metadata.report.MetadataReportFactory} | 0 .../ZookeeperMetadataReportTest.java | 2 +- dubbo-metadata/dubbo-metadata-report/pom.xml | 1 - dubbo-metadata/pom.xml | 35 ---------- .../RemoteMetadataServiceProxyFactory.java | 6 +- 58 files changed, 227 insertions(+), 279 deletions(-) rename dubbo-metadata/{dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/store => dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report}/MetadataReport.java (83%) rename dubbo-metadata/{dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/store => dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report}/MetadataReportFactory.java (96%) rename dubbo-metadata/{dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata => dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report}/identifier/MetadataIdentifier.java (82%) rename dubbo-metadata/{dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata => dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report}/support/AbstractMetadataReport.java (94%) rename dubbo-metadata/{dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata => dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report}/support/AbstractMetadataReportFactory.java (93%) rename dubbo-metadata/{dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata => dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report}/support/Constants.java (96%) rename dubbo-metadata/{dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration => dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/store}/RemoteWritableMetadataService.java (83%) rename dubbo-metadata/{dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata => dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report}/support/AbstractMetadataReportFactoryTest.java (92%) rename dubbo-metadata/{dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata => dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report}/support/AbstractMetadataReportTest.java (96%) rename dubbo-metadata/{dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration => dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store}/InterfaceNameTestService.java (95%) rename dubbo-metadata/{dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration => dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store}/InterfaceNameTestService2.java (95%) rename dubbo-metadata/{dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/MetadataReportServiceTest.java => dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/RemoteWritableMeatadataServiceTest.java} (78%) rename dubbo-metadata/{dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration => dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store}/RetryTestService.java (95%) rename dubbo-metadata/{dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store => dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata}/test/JTestMetadataReport4Test.java (91%) rename dubbo-metadata/{dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store => dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata}/test/JTestMetadataReportFactory4Test.java (86%) delete mode 100644 dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/pom.xml delete mode 100644 dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.WritableMetadataService delete mode 100644 dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory rename dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/resources/META-INF/dubbo/internal/{org.apache.dubbo.metadata.store.MetadataReportFactory => org.apache.dubbo.metadata.report.MetadataReportFactory} (100%) rename dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/resources/META-INF/dubbo/internal/{org.apache.dubbo.metadata.store.MetadataReportFactory => org.apache.dubbo.metadata.report.MetadataReportFactory} (100%) rename dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/resources/META-INF/dubbo/internal/{org.apache.dubbo.metadata.store.MetadataReportFactory => org.apache.dubbo.metadata.report.MetadataReportFactory} (100%) rename dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/resources/META-INF/dubbo/internal/{org.apache.dubbo.metadata.store.MetadataReportFactory => org.apache.dubbo.metadata.report.MetadataReportFactory} (100%) rename dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/resources/META-INF/dubbo/internal/{org.apache.dubbo.metadata.store.MetadataReportFactory => org.apache.dubbo.metadata.report.MetadataReportFactory} (100%) delete mode 100644 dubbo-metadata/pom.xml diff --git a/dubbo-bootstrap/pom.xml b/dubbo-bootstrap/pom.xml index f7ec2641730..17df1344efa 100644 --- a/dubbo-bootstrap/pom.xml +++ b/dubbo-bootstrap/pom.xml @@ -34,6 +34,13 @@ test + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${project.parent.version} + test + + org.apache.dubbo dubbo-configcenter-zookeeper diff --git a/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java index 76e520070cc..1273dcfc74c 100644 --- a/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java +++ b/dubbo-bootstrap/src/main/java/org/apache/dubbo/bootstrap/DubboBootstrap.java @@ -21,6 +21,7 @@ import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory; import org.apache.dubbo.common.config.configcenter.wrapper.CompositeDynamicConfiguration; +import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -49,7 +50,8 @@ import org.apache.dubbo.config.metadata.ConfigurableMetadataServiceExporter; import org.apache.dubbo.event.EventDispatcher; import org.apache.dubbo.event.EventListener; -import org.apache.dubbo.metadata.integration.RemoteWritableMetadataService; +import org.apache.dubbo.metadata.WritableMetadataService; +import org.apache.dubbo.metadata.store.RemoteWritableMetadataService; import org.apache.dubbo.registry.client.DefaultServiceInstance; import org.apache.dubbo.registry.client.ServiceDiscovery; import org.apache.dubbo.registry.client.ServiceInstance; @@ -489,9 +491,14 @@ private ReferenceBuilder initReferenceBuilder(String id) { /* serve for builder apis, end */ private void startMetadataReport() { + ApplicationConfig applicationConfig = ConfigManager.getInstance().getApplication().orElseThrow(() -> new IllegalStateException("There's no ApplicationConfig specified.")); + // FIXME, multiple metadata config support. Set metadataReportConfigs = ConfigManager.getInstance().getMetadataConfigs(); if (CollectionUtils.isEmpty(metadataReportConfigs)) { + if (CommonConstants.METADATA_REMOTE.equals(applicationConfig.getMetadata())) { + throw new IllegalStateException("No MetadataConfig found, you must specify the remote Metadata Center address when set 'metadata=remote'."); + } return; } MetadataReportConfig metadataReportConfig = metadataReportConfigs.iterator().next(); @@ -499,7 +506,9 @@ private void startMetadataReport() { return; } - RemoteWritableMetadataService.instance(metadataReportConfig::toUrl); + RemoteWritableMetadataService remoteMetadataService = + (RemoteWritableMetadataService) WritableMetadataService.getExtension(applicationConfig.getMetadata()); + remoteMetadataService.initMetadataReport(metadataReportConfig.toUrl()); } private void startConfigCenter() { diff --git a/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceProviderBootstrap.java b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceProviderBootstrap.java index e8499a20282..45ceed6965d 100644 --- a/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceProviderBootstrap.java +++ b/dubbo-bootstrap/src/test/java/org/apache/dubbo/bootstrap/DubboServiceProviderBootstrap.java @@ -17,6 +17,7 @@ package org.apache.dubbo.bootstrap; import org.apache.dubbo.config.builders.ApplicationBuilder; +import org.apache.dubbo.config.builders.MetadataReportBuilder; import org.apache.dubbo.config.builders.ProtocolBuilder; import org.apache.dubbo.config.builders.RegistryBuilder; import org.apache.dubbo.config.builders.ServiceBuilder; @@ -33,8 +34,10 @@ public class DubboServiceProviderBootstrap { public static void main(String[] args) throws IOException { new DubboBootstrap() - .application(ApplicationBuilder.newBuilder().name("dubbo-provider-demo").build()) - .registry(RegistryBuilder.newBuilder().address("zookeeper://127.0.0.1:2181?registry-type=service&metadata=remote").build()) + .application(ApplicationBuilder.newBuilder().name("dubbo-provider-demo").metadata("remote").build()) + .metadataReport(MetadataReportBuilder.newBuilder().address("zookeeper://127.0.0.1:2181").build()) +// .application(ApplicationBuilder.newBuilder().name("dubbo-provider-demo").build()) + .registry(RegistryBuilder.newBuilder().address("zookeeper://127.0.0.1:2181?registry-type=service").build()) .protocol(ProtocolBuilder.newBuilder().port(-1).name("dubbo").build()) .service(ServiceBuilder.newBuilder().id("test").interfaceClass(EchoService.class).ref(new EchoServiceImpl()).build()) .start() diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java index 661dad4c5aa..c1a1357e0c9 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java @@ -157,6 +157,8 @@ public interface CommonConstants { String METADATA_DEFAULT = "local"; + String METADATA_REMOTE = "remote"; + /** * package version in the manifest */ diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java index 83fc6db2e9a..b33ec75786c 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ApplicationConfig.java @@ -137,6 +137,11 @@ public class ApplicationConfig extends AbstractConfig { */ private String shutwait; + /** + * Metadata type, local or remote, if choose remote, you need to further specify metadata center. + */ + private String metadata; + public ApplicationConfig() { } @@ -374,4 +379,11 @@ public boolean isValid() { return !StringUtils.isEmpty(name); } + public String getMetadata() { + return metadata; + } + + public void setMetadata(String metadata) { + this.metadata = metadata; + } } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index c33a82e6089..1b08ba00a02 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -32,7 +32,7 @@ import org.apache.dubbo.config.support.Parameter; import org.apache.dubbo.event.Event; import org.apache.dubbo.event.EventDispatcher; -import org.apache.dubbo.metadata.integration.RemoteWritableMetadataService; +import org.apache.dubbo.metadata.WritableMetadataService; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; @@ -66,6 +66,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.DUBBO; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.METADATA_DEFAULT; +import static org.apache.dubbo.common.constants.CommonConstants.METADATA_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY; @@ -441,10 +443,11 @@ private T createProxy(Map map) { * @since 2.7.0 * ServiceData Store */ - RemoteWritableMetadataService metadataReportService = RemoteWritableMetadataService.instance(); - if (metadataReportService != null) { + String metadata = map.get(METADATA_KEY); + WritableMetadataService metadataService = WritableMetadataService.getExtension(metadata == null ? METADATA_DEFAULT : metadata); + if (metadataService != null) { URL consumerURL = new URL(CONSUMER_PROTOCOL, map.remove(REGISTER_IP_KEY), 0, map.get(INTERFACE_KEY), map); - metadataReportService.publishConsumer(consumerURL); + metadataService.publishServiceDefinition(consumerURL); } // create service proxy return (T) PROXY_FACTORY.getProxy(invoker); diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java index ef8476672b8..c9a96cb2a51 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/RegistryConfig.java @@ -149,11 +149,6 @@ public class RegistryConfig extends AbstractConfig { */ private String extraKeys; - /** - * Metadata type, local or remote, if choose remote, you need to further specify metadata center. - */ - private String metadata; - public RegistryConfig() { } @@ -412,14 +407,6 @@ public void setExtraKeys(String extraKeys) { this.extraKeys = extraKeys; } - public String getMetadata() { - return metadata; - } - - public void setMetadata(String metadata) { - this.metadata = metadata; - } - @Parameter(excluded = true) public boolean isZookeeperProtocol() { if (!isValid()) { diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index 7156f5df644..dc7d5a97674 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -35,7 +35,7 @@ import org.apache.dubbo.config.support.Parameter; import org.apache.dubbo.event.Event; import org.apache.dubbo.event.EventDispatcher; -import org.apache.dubbo.metadata.integration.RemoteWritableMetadataService; +import org.apache.dubbo.metadata.WritableMetadataService; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; @@ -71,6 +71,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.DUBBO; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_IP_TO_BIND; import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE; +import static org.apache.dubbo.common.constants.CommonConstants.METADATA_DEFAULT; +import static org.apache.dubbo.common.constants.CommonConstants.METADATA_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; @@ -631,9 +633,9 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r * @since 2.7.0 * ServiceData Store */ - RemoteWritableMetadataService metadataReportService = RemoteWritableMetadataService.instance(); - if (metadataReportService != null) { - metadataReportService.publishProvider(url); + WritableMetadataService metadataService = WritableMetadataService.getExtension(url.getParameter(METADATA_KEY, METADATA_DEFAULT)); + if (metadataService != null) { + metadataService.publishServiceDefinition(url); } } } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ApplicationBuilder.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ApplicationBuilder.java index 0a81b40798a..f4a804745c1 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ApplicationBuilder.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/ApplicationBuilder.java @@ -33,6 +33,7 @@ */ public class ApplicationBuilder extends AbstractBuilder { private String name; + private String metadata; private String version; private String owner; private String organization; @@ -60,6 +61,11 @@ public ApplicationBuilder name(String name) { return getThis(); } + public ApplicationBuilder metadata(String metadata) { + this.metadata = metadata; + return getThis(); + } + public ApplicationBuilder version(String version) { this.version = version; return getThis(); @@ -171,6 +177,7 @@ public ApplicationConfig build() { super.build(config); config.setName(name); + config.setMetadata(metadata); config.setVersion(this.version); config.setOwner(this.owner); config.setOrganization(this.organization); diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/MetadataReportBuilder.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/MetadataReportBuilder.java index 140ea137907..62777ef94b9 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/MetadataReportBuilder.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/builders/MetadataReportBuilder.java @@ -60,6 +60,10 @@ public class MetadataReportBuilder extends AbstractBuilder + + + + + @@ -575,11 +580,6 @@ - - - - - diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd index fd9e4d22d2c..f7124c856b0 100644 --- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd +++ b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd @@ -392,6 +392,11 @@ + + + + + @@ -569,11 +574,6 @@ - - - - - diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/store/MetadataReport.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReport.java similarity index 83% rename from dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/store/MetadataReport.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReport.java index 26ca68aa388..ab6f7a85a28 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/store/MetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReport.java @@ -14,13 +14,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metadata.store; +package org.apache.dubbo.metadata.report; import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.metadata.definition.model.ServiceDefinition; -import org.apache.dubbo.metadata.identifier.MetadataIdentifier; +import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; import java.util.List; import java.util.Map; @@ -42,9 +41,4 @@ public interface MetadataReport { List getSubscribedURLs(); String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier); - - static MetadataReport getMetadataReport() { - ExtensionLoader.getExtensionLoader(MetadataReport.class).get - } - } diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/store/MetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportFactory.java similarity index 96% rename from dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/store/MetadataReportFactory.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportFactory.java index 7f42da75aa7..1414c8b2138 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/store/MetadataReportFactory.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportFactory.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metadata.store; +package org.apache.dubbo.metadata.report; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Adaptive; diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/MetadataIdentifier.java similarity index 82% rename from dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/MetadataIdentifier.java index 3ad16f53fb9..7ffa2a9ed4c 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/identifier/MetadataIdentifier.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/MetadataIdentifier.java @@ -14,9 +14,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metadata.identifier; +package org.apache.dubbo.metadata.report.identifier; import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.utils.StringUtils; import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; @@ -67,11 +68,11 @@ public String getUniqueKey(KeyTypeEnum keyType) { } public String getIdentifierKey() { - return serviceInterface + SEPARATOR - + (version == null ? "" : version + SEPARATOR) - + (group == null ? "" : group + SEPARATOR) - + (side == null ? "" : side) + SEPARATOR - + (getApplication() == null ? "" : getApplication()); + return serviceInterface + + (version == null ? "" : (SEPARATOR + version)) + + (group == null ? "" : (SEPARATOR + version)) + + (side == null ? "" : (SEPARATOR + side)) + + (getApplication() == null ? "" : (SEPARATOR + getApplication())); } private String getFilePathKey() { @@ -79,12 +80,12 @@ private String getFilePathKey() { } private String getFilePathKey(String pathTag) { - return pathTag + PATH_SEPARATOR - + toServicePath() + PATH_SEPARATOR - + (version == null ? "" : (version + PATH_SEPARATOR)) - + (group == null ? "" : (group + PATH_SEPARATOR)) - + (side == null ? "" : side) + PATH_SEPARATOR - + (getApplication() == null ? "" : getApplication()); + return pathTag + + (StringUtils.isEmpty(toServicePath()) ? "" : (PATH_SEPARATOR + toServicePath())) + + (version == null ? "" : (PATH_SEPARATOR + version)) + + (group == null ? "" : (PATH_SEPARATOR + group)) + + (side == null ? "" : (PATH_SEPARATOR + side)) + + (getApplication() == null ? "" : (PATH_SEPARATOR + getApplication())); } private String toServicePath() { diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java similarity index 94% rename from dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java index 283252f7ade..a64c88737fb 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metadata.support; +package org.apache.dubbo.metadata.report.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; @@ -22,8 +22,9 @@ import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; -import org.apache.dubbo.metadata.identifier.MetadataIdentifier; -import org.apache.dubbo.metadata.store.MetadataReport; +import org.apache.dubbo.metadata.definition.model.ServiceDefinition; +import org.apache.dubbo.metadata.report.MetadataReport; +import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; import com.google.gson.Gson; @@ -56,13 +57,13 @@ import static org.apache.dubbo.common.constants.CommonConstants.FILE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; -import static org.apache.dubbo.metadata.support.Constants.CYCLE_REPORT_KEY; -import static org.apache.dubbo.metadata.support.Constants.DEFAULT_METADATA_REPORT_CYCLE_REPORT; -import static org.apache.dubbo.metadata.support.Constants.DEFAULT_METADATA_REPORT_RETRY_PERIOD; -import static org.apache.dubbo.metadata.support.Constants.DEFAULT_METADATA_REPORT_RETRY_TIMES; -import static org.apache.dubbo.metadata.support.Constants.RETRY_PERIOD_KEY; -import static org.apache.dubbo.metadata.support.Constants.RETRY_TIMES_KEY; -import static org.apache.dubbo.metadata.support.Constants.SYNC_REPORT_KEY; +import static org.apache.dubbo.metadata.report.support.Constants.CYCLE_REPORT_KEY; +import static org.apache.dubbo.metadata.report.support.Constants.DEFAULT_METADATA_REPORT_CYCLE_REPORT; +import static org.apache.dubbo.metadata.report.support.Constants.DEFAULT_METADATA_REPORT_RETRY_PERIOD; +import static org.apache.dubbo.metadata.report.support.Constants.DEFAULT_METADATA_REPORT_RETRY_TIMES; +import static org.apache.dubbo.metadata.report.support.Constants.RETRY_PERIOD_KEY; +import static org.apache.dubbo.metadata.report.support.Constants.RETRY_TIMES_KEY; +import static org.apache.dubbo.metadata.report.support.Constants.SYNC_REPORT_KEY; /** * @@ -234,7 +235,7 @@ public void storeProviderMetadata(MetadataIdentifier providerMetadataIdentifier, } } - private void storeProviderMetadataTask(MetadataIdentifier providerMetadataIdentifier, FullServiceDefinition serviceDefinition) { + private void storeProviderMetadataTask(MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) { try { if (logger.isInfoEnabled()) { logger.info("store provider metadata. Identifier : " + providerMetadataIdentifier + "; definition: " + serviceDefinition); diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactory.java similarity index 93% rename from dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactory.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactory.java index 782164a806a..9776e8c287a 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactory.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactory.java @@ -14,11 +14,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metadata.support; +package org.apache.dubbo.metadata.report.support; import org.apache.dubbo.common.URL; -import org.apache.dubbo.metadata.store.MetadataReport; -import org.apache.dubbo.metadata.store.MetadataReportFactory; +import org.apache.dubbo.metadata.report.MetadataReport; +import org.apache.dubbo.metadata.report.MetadataReportFactory; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/Constants.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/Constants.java similarity index 96% rename from dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/Constants.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/Constants.java index 3d74b2bbad9..8cee825051e 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/support/Constants.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/Constants.java @@ -15,7 +15,7 @@ * limitations under the License. */ -package org.apache.dubbo.metadata.support; +package org.apache.dubbo.metadata.report.support; public interface Constants { String METADATA_REPORT_KEY = "metadata"; diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/RemoteWritableMetadataService.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/store/RemoteWritableMetadataService.java similarity index 83% rename from dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/RemoteWritableMetadataService.java rename to dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/store/RemoteWritableMetadataService.java index 2379fbc67f0..c52f5c8aa12 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/java/org/apache/dubbo/metadata/integration/RemoteWritableMetadataService.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/store/RemoteWritableMetadataService.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metadata.integration; +package org.apache.dubbo.metadata.store; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; @@ -27,15 +27,14 @@ import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder; import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; import org.apache.dubbo.metadata.definition.model.ServiceDefinition; -import org.apache.dubbo.metadata.identifier.MetadataIdentifier; -import org.apache.dubbo.metadata.store.MetadataReport; -import org.apache.dubbo.metadata.store.MetadataReportFactory; +import org.apache.dubbo.metadata.report.MetadataReport; +import org.apache.dubbo.metadata.report.MetadataReportFactory; +import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.RpcException; import java.util.List; import java.util.function.Consumer; -import java.util.function.Supplier; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; @@ -46,7 +45,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.metadata.support.Constants.METADATA_REPORT_KEY; +import static org.apache.dubbo.metadata.report.support.Constants.METADATA_REPORT_KEY; /** * @since 2.7.0 @@ -55,17 +54,12 @@ public class RemoteWritableMetadataService implements WritableMetadataService { protected final Logger logger = LoggerFactory.getLogger(getClass()); - private static volatile RemoteWritableMetadataService metadataReportService; - private static Object lock = new Object(); + private MetadataReportFactory metadataReportFactory = ExtensionLoader.getExtensionLoader(MetadataReportFactory.class).getAdaptiveExtension(); + private MetadataReport metadataReport; - private static MetadataReportFactory metadataReportFactory = ExtensionLoader.getExtensionLoader(MetadataReportFactory.class).getAdaptiveExtension(); - private static MetadataReport metadataReport; + public RemoteWritableMetadataService() {} - RemoteWritableMetadataService() { - this.metadataReport = ; - } - - RemoteWritableMetadataService(URL metadataReportURL) { + public void initMetadataReport(URL metadataReportURL) { if (METADATA_REPORT_KEY.equals(metadataReportURL.getProtocol())) { String protocol = metadataReportURL.getParameter(METADATA_REPORT_KEY, DEFAULT_DIRECTORY); metadataReportURL = URLBuilder.from(metadataReportURL) @@ -76,23 +70,8 @@ public class RemoteWritableMetadataService implements WritableMetadataService { metadataReport = metadataReportFactory.getMetadataReport(metadataReportURL); } - public static RemoteWritableMetadataService instance() { - return metadataReportService; - } - - public static RemoteWritableMetadataService instance(Supplier metadataReportUrl) { - if (metadataReportService == null) { - synchronized (lock) { - if (metadataReportService == null) { - URL metadataReportURLTmp = metadataReportUrl.get(); - if (metadataReportURLTmp == null) { - return null; - } - metadataReportService = new RemoteWritableMetadataService(metadataReportURLTmp); - } - } - } - return metadataReportService; + public MetadataReport getMetadataReport() { + return metadataReport; } @Override diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.WritableMetadataService b/dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.WritableMetadataService index 3380b9aa13e..26bc942e704 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.WritableMetadataService +++ b/dubbo-metadata/dubbo-metadata-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.WritableMetadataService @@ -1 +1,2 @@ -local=org.apache.dubbo.metadata.store.InMemoryWritableMetadataService \ No newline at end of file +local=org.apache.dubbo.metadata.store.InMemoryWritableMetadataService +remote=org.apache.dubbo.metadata.store.RemoteWritableMetadataService \ No newline at end of file diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactoryTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactoryTest.java similarity index 92% rename from dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactoryTest.java rename to dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactoryTest.java index 57b008c74bf..1dfc4e74ec2 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportFactoryTest.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactoryTest.java @@ -14,12 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metadata.support; +package org.apache.dubbo.metadata.report.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.metadata.identifier.MetadataIdentifier; -import org.apache.dubbo.metadata.store.MetadataReport; +import org.apache.dubbo.metadata.definition.model.ServiceDefinition; +import org.apache.dubbo.metadata.report.MetadataReport; +import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; import com.alibaba.fastjson.JSON; import org.junit.jupiter.api.Assertions; @@ -64,6 +65,11 @@ public List getSubscribedURLs() { return null; } + @Override + public String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier) { + return null; + } + @Override public void storeConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, Map serviceParameterMap) { store.put(consumerMetadataIdentifier.getIdentifierKey(), JSON.toJSONString(serviceParameterMap)); diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportTest.java similarity index 96% rename from dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportTest.java rename to dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportTest.java index 2a6f1dd66bb..0faf717a6d2 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/support/AbstractMetadataReportTest.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportTest.java @@ -14,13 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metadata.support; +package org.apache.dubbo.metadata.report.support; 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.identifier.MetadataIdentifier; +import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; import com.google.gson.Gson; import org.junit.jupiter.api.Assertions; @@ -308,6 +308,11 @@ protected List doGetExportedURLs() { protected List doGetSubscribedURLs() { throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); } + + @Override + public String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier) { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } } private static class RetryMetadataReport extends AbstractMetadataReport { @@ -360,6 +365,11 @@ protected List doGetSubscribedURLs() { throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); } + @Override + public String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier) { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + } diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/InterfaceNameTestService.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/InterfaceNameTestService.java similarity index 95% rename from dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/InterfaceNameTestService.java rename to dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/InterfaceNameTestService.java index 3622062c312..e45fc382c6f 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/InterfaceNameTestService.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/InterfaceNameTestService.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metadata.integration; +package org.apache.dubbo.metadata.store; /** * 2018/9/19 diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/InterfaceNameTestService2.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/InterfaceNameTestService2.java similarity index 95% rename from dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/InterfaceNameTestService2.java rename to dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/InterfaceNameTestService2.java index 1c27f91525b..938efc249ae 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/InterfaceNameTestService2.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/InterfaceNameTestService2.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metadata.integration; +package org.apache.dubbo.metadata.store; /** * 2018/9/19 diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/MetadataReportServiceTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/RemoteWritableMeatadataServiceTest.java similarity index 78% rename from dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/MetadataReportServiceTest.java rename to dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/RemoteWritableMeatadataServiceTest.java index 4b2cdae3dda..64867a0d636 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/MetadataReportServiceTest.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/RemoteWritableMeatadataServiceTest.java @@ -14,12 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metadata.integration; +package org.apache.dubbo.metadata.store; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; +import org.apache.dubbo.metadata.WritableMetadataService; import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; -import org.apache.dubbo.metadata.store.test.JTestMetadataReport4Test; +import org.apache.dubbo.metadata.test.JTestMetadataReport4Test; import com.google.gson.Gson; import org.junit.jupiter.api.Assertions; @@ -27,31 +28,27 @@ import org.junit.jupiter.api.Test; import java.util.Map; -import java.util.function.Supplier; + +import static org.apache.dubbo.common.constants.CommonConstants.METADATA_REMOTE; /** * 2018/9/14 */ -public class MetadataReportServiceTest { +public class RemoteWritableMeatadataServiceTest { URL url = URL.valueOf("JTest://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic"); RemoteWritableMetadataService metadataReportService1; @BeforeEach public void before() { - metadataReportService1 = RemoteWritableMetadataService.instance(() -> url); + metadataReportService1 = (RemoteWritableMetadataService) WritableMetadataService.getExtension(METADATA_REMOTE); + metadataReportService1.initMetadataReport(url); } @Test public void testInstance() { - RemoteWritableMetadataService metadataReportService2 = RemoteWritableMetadataService.instance(new Supplier() { - @Override - public URL get() { - return url; - } - }); + RemoteWritableMetadataService metadataReportService2 = (RemoteWritableMetadataService) WritableMetadataService.getExtension(METADATA_REMOTE); Assertions.assertSame(metadataReportService1, metadataReportService2); - Assertions.assertEquals(metadataReportService1.metadataReportUrl, url); } @Test @@ -61,9 +58,9 @@ public void testPublishProviderNoInterfaceName() { URL publishUrl = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vicpubprovder&side=provider"); metadataReportService1.publishProvider(publishUrl); - Assertions.assertTrue(metadataReportService1.metadataReport instanceof JTestMetadataReport4Test); + Assertions.assertTrue(metadataReportService1.getMetadataReport() instanceof JTestMetadataReport4Test); - JTestMetadataReport4Test jTestMetadataReport4Test = (JTestMetadataReport4Test) metadataReportService1.metadataReport; + JTestMetadataReport4Test jTestMetadataReport4Test = (JTestMetadataReport4Test) metadataReportService1.getMetadataReport(); Assertions.assertTrue(!jTestMetadataReport4Test.store.containsKey(JTestMetadataReport4Test.getProviderKey(publishUrl))); } @@ -74,9 +71,9 @@ public void testPublishProviderWrongInterface() { URL publishUrl = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vicpu&interface=ccc&side=provider"); metadataReportService1.publishProvider(publishUrl); - Assertions.assertTrue(metadataReportService1.metadataReport instanceof JTestMetadataReport4Test); + Assertions.assertTrue(metadataReportService1.getMetadataReport() instanceof JTestMetadataReport4Test); - JTestMetadataReport4Test jTestMetadataReport4Test = (JTestMetadataReport4Test) metadataReportService1.metadataReport; + JTestMetadataReport4Test jTestMetadataReport4Test = (JTestMetadataReport4Test) metadataReportService1.getMetadataReport(); Assertions.assertTrue(!jTestMetadataReport4Test.store.containsKey(JTestMetadataReport4Test.getProviderKey(publishUrl))); } @@ -88,9 +85,9 @@ public void testPublishProviderContainInterface() throws InterruptedException { metadataReportService1.publishProvider(publishUrl); Thread.sleep(300); - Assertions.assertTrue(metadataReportService1.metadataReport instanceof JTestMetadataReport4Test); + Assertions.assertTrue(metadataReportService1.getMetadataReport() instanceof JTestMetadataReport4Test); - JTestMetadataReport4Test jTestMetadataReport4Test = (JTestMetadataReport4Test) metadataReportService1.metadataReport; + JTestMetadataReport4Test jTestMetadataReport4Test = (JTestMetadataReport4Test) metadataReportService1.getMetadataReport(); Assertions.assertTrue(jTestMetadataReport4Test.store.containsKey(JTestMetadataReport4Test.getProviderKey(publishUrl))); String value = jTestMetadataReport4Test.store.get(JTestMetadataReport4Test.getProviderKey(publishUrl)); @@ -108,9 +105,9 @@ public void testPublishConsumer() throws InterruptedException { metadataReportService1.publishConsumer(publishUrl); Thread.sleep(300); - Assertions.assertTrue(metadataReportService1.metadataReport instanceof JTestMetadataReport4Test); + Assertions.assertTrue(metadataReportService1.getMetadataReport() instanceof JTestMetadataReport4Test); - JTestMetadataReport4Test jTestMetadataReport4Test = (JTestMetadataReport4Test) metadataReportService1.metadataReport; + JTestMetadataReport4Test jTestMetadataReport4Test = (JTestMetadataReport4Test) metadataReportService1.getMetadataReport(); Assertions.assertTrue(jTestMetadataReport4Test.store.containsKey(JTestMetadataReport4Test.getConsumerKey(publishUrl))); String value = jTestMetadataReport4Test.store.get(JTestMetadataReport4Test.getConsumerKey(publishUrl)); diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/RetryTestService.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/RetryTestService.java similarity index 95% rename from dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/RetryTestService.java rename to dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/RetryTestService.java index 43f0bbd12d8..9133d25ed75 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/integration/RetryTestService.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/RetryTestService.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metadata.integration; +package org.apache.dubbo.metadata.store; /** * 2018/10/26 diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReport4Test.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/test/JTestMetadataReport4Test.java similarity index 91% rename from dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReport4Test.java rename to dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/test/JTestMetadataReport4Test.java index 2b474152dad..603a27f5161 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReport4Test.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/test/JTestMetadataReport4Test.java @@ -14,13 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metadata.store.test; +package org.apache.dubbo.metadata.test; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.metadata.identifier.MetadataIdentifier; -import org.apache.dubbo.metadata.support.AbstractMetadataReport; +import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; +import org.apache.dubbo.metadata.report.support.AbstractMetadataReport; import java.util.List; import java.util.Map; @@ -87,4 +87,8 @@ public static String getConsumerKey(URL url) { return new MetadataIdentifier(url).getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY); } + @Override + public String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier) { + return null; + } } diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReportFactory4Test.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/test/JTestMetadataReportFactory4Test.java similarity index 86% rename from dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReportFactory4Test.java rename to dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/test/JTestMetadataReportFactory4Test.java index 4e50a073fe1..6e264083008 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/java/org/apache/dubbo/metadata/store/test/JTestMetadataReportFactory4Test.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/test/JTestMetadataReportFactory4Test.java @@ -14,11 +14,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.dubbo.metadata.store.test; +package org.apache.dubbo.metadata.test; import org.apache.dubbo.common.URL; -import org.apache.dubbo.metadata.store.MetadataReport; -import org.apache.dubbo.metadata.support.AbstractMetadataReportFactory; +import org.apache.dubbo.metadata.report.MetadataReport; +import org.apache.dubbo.metadata.report.support.AbstractMetadataReportFactory; /** * ZookeeperRegistryFactory. diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/pom.xml b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/pom.xml deleted file mode 100644 index bcdde95afaf..00000000000 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/pom.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - dubbo-metadata-report - org.apache.dubbo - ${revision} - - 4.0.0 - - dubbo-metadata-report-api - jar - - - false - - - - org.apache.dubbo - dubbo-cluster - ${project.parent.version} - - - org.apache.dubbo - dubbo-metadata-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - org.apache.dubbo - dubbo-container-api - ${project.parent.version} - - - org.mortbay.jetty - jetty - - - - - - org.apache.dubbo - dubbo-remoting-zookeeper - ${project.parent.version} - test - - - com.google.code.gson - gson - - - diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.WritableMetadataService b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.WritableMetadataService deleted file mode 100644 index 44f58de8ae0..00000000000 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.WritableMetadataService +++ /dev/null @@ -1 +0,0 @@ -remote=org.apache.dubbo.metadata.integration.RemoteWritableMetadataService \ No newline at end of file diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory deleted file mode 100644 index bf840236d34..00000000000 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-api/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory +++ /dev/null @@ -1 +0,0 @@ -JTest=org.apache.dubbo.metadata.store.test.JTestMetadataReportFactory4Test diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/pom.xml b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/pom.xml index ad3eb4946e7..fdf0527a83f 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/pom.xml +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/pom.xml @@ -29,7 +29,7 @@ org.apache.dubbo - dubbo-metadata-report-api + dubbo-metadata-api ${project.parent.version} diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java index a00b30aaf9c..89227e52db2 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java @@ -20,8 +20,8 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.metadata.identifier.MetadataIdentifier; -import org.apache.dubbo.metadata.support.AbstractMetadataReport; +import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; +import org.apache.dubbo.metadata.report.support.AbstractMetadataReport; import org.apache.dubbo.rpc.RpcException; import com.ecwid.consul.v1.ConsulClient; @@ -83,4 +83,9 @@ private void storeMetadata(MetadataIdentifier identifier, String v) { throw new RpcException("Failed to put " + identifier + " to consul " + v + ", cause: " + t.getMessage(), t); } } + + @Override + public String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier) { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } } diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReportFactory.java index 66d7b5e5e45..1d1f5bbd409 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReportFactory.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReportFactory.java @@ -18,8 +18,8 @@ package org.apache.dubbo.metadata.store.consul; import org.apache.dubbo.common.URL; -import org.apache.dubbo.metadata.store.MetadataReport; -import org.apache.dubbo.metadata.support.AbstractMetadataReportFactory; +import org.apache.dubbo.metadata.report.MetadataReport; +import org.apache.dubbo.metadata.report.support.AbstractMetadataReportFactory; /** * metadata report factory impl for consul diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory similarity index 100% rename from dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/pom.xml b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/pom.xml index 45a1413e464..56e4a38f1a5 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/pom.xml +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/pom.xml @@ -31,7 +31,7 @@ org.apache.dubbo - dubbo-metadata-report-api + dubbo-metadata-api ${project.parent.version} diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java index 9577da80550..d01e02d12b5 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java @@ -36,8 +36,8 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.metadata.identifier.MetadataIdentifier; -import org.apache.dubbo.metadata.support.AbstractMetadataReport; +import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; +import org.apache.dubbo.metadata.report.support.AbstractMetadataReport; import org.apache.dubbo.remoting.etcd.jetcd.JEtcdClient; import java.util.List; @@ -102,6 +102,11 @@ protected List doGetSubscribedURLs() { throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); } + @Override + public String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier) { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + private void storeMetadata(MetadataIdentifier identifier, String v) { String key = getNodeKey(identifier); if (!etcdClient.put(key, v)) { diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportFactory.java index f0572b64482..3bb9e92d3ef 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportFactory.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportFactory.java @@ -34,8 +34,8 @@ package org.apache.dubbo.metadata.store.etcd; import org.apache.dubbo.common.URL; -import org.apache.dubbo.metadata.store.MetadataReport; -import org.apache.dubbo.metadata.support.AbstractMetadataReportFactory; +import org.apache.dubbo.metadata.report.MetadataReport; +import org.apache.dubbo.metadata.report.support.AbstractMetadataReportFactory; /** * MetadataReportFactory to create an Etcd based {@link MetadataReport}. diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory similarity index 100% rename from dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java index 770b058e070..6ae18ca7871 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java @@ -21,7 +21,7 @@ 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.identifier.MetadataIdentifier; +import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; import com.google.gson.Gson; import io.etcd.jetcd.ByteSequence; diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/pom.xml b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/pom.xml index d324d5c49c1..95fcf158f62 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/pom.xml +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/pom.xml @@ -29,7 +29,7 @@ org.apache.dubbo - dubbo-metadata-report-api + dubbo-metadata-api ${project.parent.version} diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java index 78e8189a914..846bc74e391 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java @@ -21,8 +21,8 @@ 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.identifier.MetadataIdentifier; -import org.apache.dubbo.metadata.support.AbstractMetadataReport; +import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; +import org.apache.dubbo.metadata.report.support.AbstractMetadataReport; import org.apache.dubbo.rpc.RpcException; import com.alibaba.nacos.api.NacosFactory; @@ -133,6 +133,11 @@ protected List doGetSubscribedURLs() { throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); } + @Override + public String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier) { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + private void storeMetadata(MetadataIdentifier identifier, String value) { try { boolean publishResult = configService.publishConfig(identifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY), identifier.getGroup(), value); diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java index b882042281c..2cff74c9a1b 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java @@ -18,8 +18,8 @@ package org.apache.dubbo.metadata.store.nacos; import org.apache.dubbo.common.URL; -import org.apache.dubbo.metadata.store.MetadataReport; -import org.apache.dubbo.metadata.support.AbstractMetadataReportFactory; +import org.apache.dubbo.metadata.report.MetadataReport; +import org.apache.dubbo.metadata.report.support.AbstractMetadataReportFactory; /** * metadata report factory impl for nacos diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory similarity index 100% rename from dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java index 07d6f8b839a..909244ccf97 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportTest.java @@ -20,7 +20,7 @@ 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.identifier.MetadataIdentifier; +import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; import com.alibaba.nacos.api.config.ConfigService; import com.google.gson.Gson; diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/pom.xml b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/pom.xml index 419c77f8839..da07d277447 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/pom.xml +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/pom.xml @@ -30,7 +30,7 @@ org.apache.dubbo - dubbo-metadata-report-api + dubbo-metadata-api ${project.parent.version} diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java index 69ae2ec9a7f..bc2b2eb2889 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java @@ -19,8 +19,8 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.metadata.identifier.MetadataIdentifier; -import org.apache.dubbo.metadata.support.AbstractMetadataReport; +import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; +import org.apache.dubbo.metadata.report.support.AbstractMetadataReport; import org.apache.dubbo.rpc.RpcException; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; @@ -37,7 +37,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; -import static org.apache.dubbo.metadata.identifier.MetadataIdentifier.META_DATA_STORE_TAG; +import static org.apache.dubbo.metadata.report.identifier.MetadataIdentifier.META_DATA_STORE_TAG; /** * RedisMetadataReport @@ -96,6 +96,11 @@ protected List doGetSubscribedURLs() { return null; } + @Override + public String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier) { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + private void storeMetadata(MetadataIdentifier metadataIdentifier, String v) { if (pool != null) { storeMetadataStandalone(metadataIdentifier, v); diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportFactory.java index b507dbec21d..bd0887753fa 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportFactory.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportFactory.java @@ -17,8 +17,8 @@ package org.apache.dubbo.metadata.store.redis; import org.apache.dubbo.common.URL; -import org.apache.dubbo.metadata.store.MetadataReport; -import org.apache.dubbo.metadata.support.AbstractMetadataReportFactory; +import org.apache.dubbo.metadata.report.MetadataReport; +import org.apache.dubbo.metadata.report.support.AbstractMetadataReportFactory; /** * RedisMetadataReportFactory. diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory similarity index 100% rename from dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java index 63a2a39514a..88105e276b9 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java @@ -20,7 +20,7 @@ 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.identifier.MetadataIdentifier; +import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; import org.apache.dubbo.rpc.RpcException; import com.google.gson.Gson; @@ -40,7 +40,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; -import static org.apache.dubbo.metadata.support.Constants.SYNC_REPORT_KEY; +import static org.apache.dubbo.metadata.report.support.Constants.SYNC_REPORT_KEY; /** * 2018/10/9 diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/pom.xml b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/pom.xml index a276f83b3bf..b84bd10c6d6 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/pom.xml +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/pom.xml @@ -27,7 +27,7 @@ org.apache.dubbo - dubbo-metadata-report-api + dubbo-metadata-api ${project.parent.version} diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java index 7f5c4bca20e..56499336027 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java @@ -19,8 +19,8 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.metadata.identifier.MetadataIdentifier; -import org.apache.dubbo.metadata.support.AbstractMetadataReport; +import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; +import org.apache.dubbo.metadata.report.support.AbstractMetadataReport; import org.apache.dubbo.remoting.zookeeper.ZookeeperClient; import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter; @@ -90,6 +90,11 @@ protected List doGetSubscribedURLs() { return null; } + @Override + public String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier) { + throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + } + private void storeMetadata(MetadataIdentifier metadataIdentifier, String v) { zkClient.create(getNodePath(metadataIdentifier), v, false); } diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportFactory.java index cf26d4af7a0..0ffed8db8e9 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportFactory.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportFactory.java @@ -17,8 +17,8 @@ package org.apache.dubbo.metadata.store.zookeeper; import org.apache.dubbo.common.URL; -import org.apache.dubbo.metadata.store.MetadataReport; -import org.apache.dubbo.metadata.support.AbstractMetadataReportFactory; +import org.apache.dubbo.metadata.report.MetadataReport; +import org.apache.dubbo.metadata.report.support.AbstractMetadataReportFactory; import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter; /** diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory similarity index 100% rename from dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory rename to dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory diff --git a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportTest.java b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportTest.java index 799a1bb04f4..55912f0e352 100644 --- a/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportTest.java +++ b/dubbo-metadata/dubbo-metadata-report/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportTest.java @@ -20,7 +20,7 @@ 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.identifier.MetadataIdentifier; +import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; import org.apache.dubbo.remoting.zookeeper.curator.CuratorZookeeperTransporter; import com.google.gson.Gson; diff --git a/dubbo-metadata/dubbo-metadata-report/pom.xml b/dubbo-metadata/dubbo-metadata-report/pom.xml index 02496c38e11..3c2fa6019a8 100644 --- a/dubbo-metadata/dubbo-metadata-report/pom.xml +++ b/dubbo-metadata/dubbo-metadata-report/pom.xml @@ -25,7 +25,6 @@ dubbo-metadata-report pom - dubbo-metadata-report-api dubbo-metadata-report-zookeeper dubbo-metadata-report-redis dubbo-metadata-report-consul diff --git a/dubbo-metadata/pom.xml b/dubbo-metadata/pom.xml deleted file mode 100644 index 2115c452c67..00000000000 --- a/dubbo-metadata/pom.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - org.apache.dubbo - dubbo-parent - ${revision} - ../pom.xml - - 4.0.0 - - dubbo-metadata - pom - - dubbo-metadata-api - dubbo-metadata-report - - - \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/proxy/RemoteMetadataServiceProxyFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/proxy/RemoteMetadataServiceProxyFactory.java index f8303f18500..3544294fe58 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/proxy/RemoteMetadataServiceProxyFactory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/proxy/RemoteMetadataServiceProxyFactory.java @@ -17,9 +17,11 @@ package org.apache.dubbo.registry.client.metadata.proxy; import org.apache.dubbo.metadata.MetadataService; -import org.apache.dubbo.metadata.integration.RemoteWritableMetadataService; +import org.apache.dubbo.metadata.WritableMetadataService; import org.apache.dubbo.registry.client.ServiceInstance; +import static org.apache.dubbo.common.constants.CommonConstants.METADATA_REMOTE; + /** * */ @@ -27,7 +29,7 @@ public class RemoteMetadataServiceProxyFactory implements MetadataServiceProxyFa @Override public MetadataService getProxy(ServiceInstance serviceInstance) { - return RemoteWritableMetadataService.instance(); + return WritableMetadataService.getExtension(METADATA_REMOTE); } } From e828be77a5175139548c0d32e0b29fe2566fa9b3 Mon Sep 17 00:00:00 2001 From: "ken.lj" Date: Thu, 20 Jun 2019 17:17:53 +0800 Subject: [PATCH 44/46] add missed files --- .../identifier/MetadataIdentifierTest.java | 50 +++++++++++++++++++ dubbo-metadata/pom.xml | 35 +++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/MetadataIdentifierTest.java create mode 100644 dubbo-metadata/pom.xml diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/MetadataIdentifierTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/MetadataIdentifierTest.java new file mode 100644 index 00000000000..c85ee486a4f --- /dev/null +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/MetadataIdentifierTest.java @@ -0,0 +1,50 @@ +/* + * 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.identifier; + +import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; + +/** + * 2019/1/7 + */ +public class MetadataIdentifierTest { + + @Test + public void testGetUniqueKey() { + String interfaceName = "org.apache.dubbo.metadata.integration.InterfaceNameTestService"; + String version = "1.0.0.zk.md"; + String group = null; + String application = "vic.zk.md"; + MetadataIdentifier providerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application); + Assertions.assertEquals(providerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.PATH), + "metadata" + PATH_SEPARATOR + interfaceName + PATH_SEPARATOR + + (version == null ? "" : (version + PATH_SEPARATOR)) + + (group == null ? "" : (group + PATH_SEPARATOR)) + PROVIDER_SIDE + + PATH_SEPARATOR + application); + Assertions.assertEquals(providerMetadataIdentifier.getUniqueKey(MetadataIdentifier.KeyTypeEnum.UNIQUE_KEY), + interfaceName + MetadataIdentifier.SEPARATOR + + (version == null ? "" : version + MetadataIdentifier.SEPARATOR) + + (group == null ? "" : group + MetadataIdentifier.SEPARATOR) + + PROVIDER_SIDE + MetadataIdentifier.SEPARATOR + application); + } +} diff --git a/dubbo-metadata/pom.xml b/dubbo-metadata/pom.xml new file mode 100644 index 00000000000..2115c452c67 --- /dev/null +++ b/dubbo-metadata/pom.xml @@ -0,0 +1,35 @@ + + + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + + 4.0.0 + + dubbo-metadata + pom + + dubbo-metadata-api + dubbo-metadata-report + + + \ No newline at end of file From 633c0705798d22c4f869d7e9be3168397e833ffc Mon Sep 17 00:00:00 2001 From: "ken.lj" Date: Thu, 20 Jun 2019 17:38:38 +0800 Subject: [PATCH 45/46] remove duplicated files --- ...ynamicConfigurationServiceNameMapping.java | 103 ---------- .../InMemoryLocalMetadataService.java | 192 ------------------ .../dubbo/metadata/LocalMetadataService.java | 88 -------- .../dubbo/metadata/MetadataService.java | 151 -------------- .../metadata/MetadataServiceExporter.java | 44 ---- .../dubbo/metadata/ServiceNameMapping.java | 64 ------ ...apache.dubbo.metadata.LocalMetadataService | 1 - ...g.apache.dubbo.metadata.ServiceNameMapping | 1 - ...icConfigurationServiceNameMappingTest.java | 114 ----------- .../InMemoryLocalMetadataServiceTest.java | 140 ------------- .../metadata/LocalMetadataServiceTest.java | 34 ---- 11 files changed, 932 deletions(-) delete mode 100644 dubbo-metadata/src/main/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMapping.java delete mode 100644 dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java delete mode 100644 dubbo-metadata/src/main/java/org/apache/dubbo/metadata/LocalMetadataService.java delete mode 100644 dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataService.java delete mode 100644 dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceExporter.java delete mode 100644 dubbo-metadata/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java delete mode 100644 dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.LocalMetadataService delete mode 100644 dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.ServiceNameMapping delete mode 100644 dubbo-metadata/src/test/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMappingTest.java delete mode 100644 dubbo-metadata/src/test/java/org/apache/dubbo/metadata/InMemoryLocalMetadataServiceTest.java delete mode 100644 dubbo-metadata/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMapping.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMapping.java deleted file mode 100644 index f535a517dad..00000000000 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMapping.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.metadata; - -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.configcenter.DynamicConfiguration; -import org.apache.dubbo.rpc.model.ApplicationModel; - -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; - -import static java.util.Arrays.asList; -import static org.apache.dubbo.common.utils.StringUtils.isBlank; - -/** - * The {@link ServiceNameMapping} implementation based on {@link DynamicConfiguration} - */ -public class DynamicConfigurationServiceNameMapping implements ServiceNameMapping { - - private static final List IGNORED_SERVICE_INTERFACES = asList(MetadataService.class.getName()); - - private static final String SEPARATOR = ":"; - - private static final String EMPTY = ""; - - private final Logger logger = LoggerFactory.getLogger(getClass()); - - @Override - public void map(String serviceInterface, String group, String version, String protocol) { - - if (IGNORED_SERVICE_INTERFACES.contains(serviceInterface)) { - return; - } - - DynamicConfiguration dynamicConfiguration = DynamicConfiguration.getDynamicConfiguration(); - - // the Dubbo Service Key as group - // the service(application) name as key - // It does matter whatever the content is, we just need a record - String key = ApplicationModel.getApplication(); - String content = String.valueOf(System.currentTimeMillis()); - execute(() -> { - dynamicConfiguration.publishConfig(key, buildGroup(serviceInterface, group, version, protocol), content); - if (logger.isInfoEnabled()) { - logger.info(String.format("The Dubbo service key[%s] mapped to service name[%s] with content : %s", - key, group, content)); - } - }); - } - - @Override - public Set get(String serviceInterface, String group, String version, String protocol) { - - DynamicConfiguration dynamicConfiguration = DynamicConfiguration.getDynamicConfiguration(); - - String key = ApplicationModel.getApplication(); - Set serviceNames = new LinkedHashSet<>(); - execute(() -> { - Set keys = dynamicConfiguration.getConfigKeys(buildGroup(serviceInterface, group, version, protocol)); - serviceNames.addAll(keys); - }); - return Collections.unmodifiableSet(serviceNames); - } - - protected static String buildGroup(String serviceInterface, String group, String version, String protocol) { - StringBuilder groupBuilder = new StringBuilder(serviceInterface) - .append(SEPARATOR).append(defaultString(group)) - .append(SEPARATOR).append(defaultString(version)) - .append(SEPARATOR).append(defaultString(protocol)); - return groupBuilder.toString(); - } - - private static String defaultString(String value) { - return isBlank(value) ? EMPTY : value; - } - - private void execute(Runnable runnable) { - try { - runnable.run(); - } catch (Throwable e) { - if (logger.isWarnEnabled()) { - logger.warn(e.getMessage(), e); - } - } - } -} diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java deleted file mode 100644 index 947a9fbd284..00000000000 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/InMemoryLocalMetadataService.java +++ /dev/null @@ -1,192 +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; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; - -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; -import java.util.stream.Collectors; - -import static java.util.Collections.emptyList; -import static java.util.Collections.unmodifiableList; -import static org.apache.dubbo.common.URL.buildKey; -import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; -import static org.apache.dubbo.common.utils.CollectionUtils.isEmpty; - -/** - * The {@link LocalMetadataService} implementation stores the metadata of Dubbo services in memory locally when they - * exported. - * - * @see MetadataService - * @see LocalMetadataService - * @since 2.7.3 - */ -public class InMemoryLocalMetadataService implements LocalMetadataService { - - /** - * The class name of {@link MetadataService} - */ - static final String METADATA_SERVICE_CLASS_NAME = MetadataService.class.getName(); - - private final Logger logger = LoggerFactory.getLogger(getClass()); - - private final Lock lock = new ReentrantLock(); - - // =================================== Registration =================================== // - - /** - * All exported {@link URL urls} {@link Map} whose key is the return value of {@link URL#getServiceKey()} method - * and value is the {@link List} of the {@link URL URLs} - */ - private ConcurrentMap> exportedServiceURLs = new ConcurrentHashMap<>(); - - // ==================================================================================== // - - // =================================== Subscription =================================== // - - /** - * The subscribed {@link URL urls} {@link Map} of {@link MetadataService}, - * whose key is the return value of {@link URL#getServiceKey()} method and value is the {@link List} of - * the {@link URL URLs} - */ - private final ConcurrentMap> subscribedServiceURLs = new ConcurrentHashMap<>(); - - // ==================================================================================== // - - @Override - public List getSubscribedURLs() { - return getAllUnmodifiableServiceURLs(subscribedServiceURLs); - } - - @Override - public List getExportedURLs(String serviceInterface, String group, String version, String protocol) { - if (ALL_SERVICE_INTERFACES.equals(serviceInterface)) { - return getAllUnmodifiableServiceURLs(exportedServiceURLs); - } - String serviceKey = buildKey(serviceInterface, group, version); - return unmodifiableList(getServiceURLs(exportedServiceURLs, serviceKey, protocol)); - } - - @Override - public boolean exportURL(URL url) { -// if (isMetadataServiceURL(url)) { // ignore MetadataService in the export phase -// return true; -// } - return addURL(exportedServiceURLs, url); - } - - @Override - public boolean unexportURL(URL url) { -// if (isMetadataServiceURL(url)) { // ignore MetadataService in the export phase -// return true; -// } - return removeURL(exportedServiceURLs, url); - } - - @Override - public boolean subscribeURL(URL url) { - return addURL(subscribedServiceURLs, url); - } - - @Override - public boolean unsubscribeURL(URL url) { - return removeURL(subscribedServiceURLs, url); - } - - private boolean addURL(Map> serviceURLs, URL url) { - return executeMutually(() -> { - List urls = serviceURLs.computeIfAbsent(url.getServiceKey(), s -> new LinkedList()); - if (!urls.contains(url)) { - return urls.add(url); - } - return false; - }); - } - - private boolean removeURL(Map> serviceURLs, URL url) { - return executeMutually(() -> { - List urls = serviceURLs.get(url.getServiceKey()); - if (isEmpty(urls)) { - return false; - } - return urls.remove(url); - }); - } - - private boolean executeMutually(Callable callable) { - boolean success = false; - try { - lock.lock(); - try { - success = callable.call(); - } catch (Exception e) { - if (logger.isErrorEnabled()) { - logger.error(e); - } - } - } finally { - lock.unlock(); - } - return success; - } - - private static List getServiceURLs(Map> exportedServiceURLs, String serviceKey, - String protocol) { - List serviceURLs = exportedServiceURLs.get(serviceKey); - - if (isEmpty(serviceURLs)) { - return emptyList(); - } - - return serviceURLs - .stream() - .filter(url -> isAcceptableProtocol(protocol, url)) - .map(URL::toFullString) - .collect(Collectors.toList()); - } - - private static boolean isAcceptableProtocol(String protocol, URL url) { - return protocol == null - || protocol.equals(url.getParameter(PROTOCOL_KEY)) - || protocol.equals(url.getProtocol()); - } - -// private static boolean isMetadataServiceURL(URL url) { -// String serviceInterface = url.getServiceInterface(); -// return METADATA_SERVICE_CLASS_NAME.equals(serviceInterface); -// } - - private static List getAllUnmodifiableServiceURLs(Map> serviceURLs) { - return unmodifiableList( - serviceURLs - .values() - .stream() - .flatMap(Collection::stream) - .map(URL::toFullString) - .collect(Collectors.toList())); - } -} diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/LocalMetadataService.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/LocalMetadataService.java deleted file mode 100644 index 172409524ec..00000000000 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/LocalMetadataService.java +++ /dev/null @@ -1,88 +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; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.extension.SPI; -import org.apache.dubbo.rpc.model.ApplicationModel; - -import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; - -/** - * Local {@link MetadataService} that extends {@link MetadataService} and provides the modification, which is used for - * Dubbo's consumers and providers. - * - * @since 2.7.3 - */ -@SPI("default") -public interface LocalMetadataService extends MetadataService { - - /** - * Gets the current Dubbo Service name - * - * @return non-null - */ - @Override - default String serviceName() { - return ApplicationModel.getApplication(); - } - - /** - * Exports a {@link URL} - * - * @param url a {@link URL} - * @return If success , return true - */ - boolean exportURL(URL url); - - /** - * Unexports a {@link URL} - * - * @param url a {@link URL} - * @return If success , return true - */ - boolean unexportURL(URL url); - - /** - * Subscribes a {@link URL} - * - * @param url a {@link URL} - * @return If success , return true - */ - boolean subscribeURL(URL url); - - /** - * Unsubscribes a {@link URL} - * - * @param url a {@link URL} - * @return If success , return true - */ - boolean unsubscribeURL(URL url); - - - /** - * Get {@link ExtensionLoader#getDefaultExtension() the defautl extension} of {@link LocalMetadataService} - * - * @return non-null - * @see InMemoryLocalMetadataService - */ - public static LocalMetadataService getDefaultExtension() { - return getExtensionLoader(LocalMetadataService.class).getDefaultExtension(); - } - -} diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataService.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataService.java deleted file mode 100644 index f73d5f6e8cb..00000000000 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataService.java +++ /dev/null @@ -1,151 +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; - -import org.apache.dubbo.common.URL; - -import java.util.List; -import java.util.stream.Collectors; - -import static java.util.stream.StreamSupport.stream; - -/** - * A framework interface of Dubbo Metadata Service defines the contract of Dubbo Services registartion and subscription - * between Dubbo service providers and its consumers. The implementationwill be exported as a normal Dubbo service that - * the clients would subscribe, whose version comes from the {@link #version()} method and group gets from - * {@link #serviceName()}, that means, The different Dubbo service(application) will export the different - * {@link MetadataService} that persists all the exported and subscribed metadata, they are present by - * {@link #getExportedURLs()} and {@link #getSubscribedURLs()} respectively. What's more, {@link MetadataService} - * also providers the fine-grain methods for the precise queries. - * - * @see LocalMetadataService - * @since 2.7.3 - */ -public interface MetadataService { - - /** - * The value of all service names - */ - String ALL_SERVICE_NAMES = "*"; - - /** - * The value of All service instances - */ - String ALL_SERVICE_INTERFACES = "*"; - - /** - * The contract version of {@link MetadataService}, the future update must make sure compatible. - */ - String VERSION = "1.0.0"; - - /** - * Gets the current Dubbo Service name - * - * @return non-null - */ - String serviceName(); - - /** - * Gets the version of {@link MetadataService} that always equals {@link #VERSION} - * - * @return non-null - * @see #VERSION - */ - default String version() { - return VERSION; - } - - /** - * the list of String that presents all Dubbo subscribed {@link URL urls} - * - * @return non-null read-only {@link List} - */ - List getSubscribedURLs(); - - /** - * Get the list of String that presents all Dubbo exported {@link URL urls} - * - * @return non-null read-only {@link List} - */ - default List getExportedURLs() { - return getExportedURLs(ALL_SERVICE_INTERFACES); - } - - /** - * Get the list of String that presents the specified Dubbo exported {@link URL urls} by the serviceInterface - * - * @param serviceInterface The class name of Dubbo service interface - * @return non-null read-only {@link List} - * @see URL - */ - default List getExportedURLs(String serviceInterface) { - return getExportedURLs(serviceInterface, null); - } - - /** - * Get the list of String that presents the specified Dubbo exported {@link URL urls} by the - * serviceInterface and group - * - * @param serviceInterface The class name of Dubbo service interface - * @param group the Dubbo Service Group (optional) - * @return non-null read-only {@link List} - * @see URL - */ - default List getExportedURLs(String serviceInterface, String group) { - return getExportedURLs(serviceInterface, group, null); - } - - /** - * Get the list of String that presents the specified Dubbo exported {@link URL urls} by the - * serviceInterface, group and version - * - * @param serviceInterface The class name of Dubbo service interface - * @param group the Dubbo Service Group (optional) - * @param version the Dubbo Service Version (optional) - * @return non-null read-only {@link List} - * @see URL - */ - default List getExportedURLs(String serviceInterface, String group, String version) { - return getExportedURLs(serviceInterface, group, version, null); - } - - /** - * Get the list of String that presents the specified Dubbo exported {@link URL urls} by the - * serviceInterface, group, version and protocol - * - * @param serviceInterface The class name of Dubbo service interface - * @param group the Dubbo Service Group (optional) - * @param version the Dubbo Service Version (optional) - * @param protocol the Dubbo Service Protocol (optional) - * @return non-null read-only {@link List} - * @see URL - */ - List getExportedURLs(String serviceInterface, String group, String version, String protocol); - - - /** - * Convert the multiple {@link URL urls} to a {@link List list} of {@link URL urls} - * - * @param urls the strings presents the {@link URL Dubbo URLs} - * @return non-null - */ - static List toURLs(Iterable urls) { - return stream(urls.spliterator(), false) - .map(URL::valueOf) - .collect(Collectors.toList()); - } -} diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceExporter.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceExporter.java deleted file mode 100644 index 8bbe53c6d2c..00000000000 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/MetadataServiceExporter.java +++ /dev/null @@ -1,44 +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; - -import org.apache.dubbo.common.URL; - -import java.util.List; - -/** - * The exporter of {@link MetadataService} - * - * @see MetadataService - * @see #export() - * @see #unexport() - * @since 2.7.3 - */ -public interface MetadataServiceExporter { - - /** - * Exports the {@link MetadataService} as a Dubbo service - * - * @return the exported {@link URL URLs} - */ - List export(); - - /** - * Unexports the {@link MetadataService} - */ - void unexport(); -} diff --git a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java b/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java deleted file mode 100644 index a642f3d2a92..00000000000 --- a/dubbo-metadata/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java +++ /dev/null @@ -1,64 +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; - -import org.apache.dubbo.common.extension.SPI; - -import java.util.Set; - -import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; - -/** - * The interface for Dubbo service name Mapping - * - * @since 2.7.3 - */ -@SPI("default") -public interface ServiceNameMapping { - - /** - * Map the specified Dubbo service interface, group, version and protocol to current Dubbo service name - * - * @param serviceInterface the class name of Dubbo service interface - * @param group the group of Dubbo service interface (optional) - * @param version the version of Dubbo service interface version (optional) - * @param protocol the protocol of Dubbo service interface exported (optional) - */ - void map(String serviceInterface, String group, String version, String protocol); - - /** - * Get the service names from the specified Dubbo service interface, group, version and protocol - * - * @param serviceInterface the class name of Dubbo service interface - * @param group the group of Dubbo service interface (optional) - * @param version the version of Dubbo service interface version (optional) - * @param protocol the protocol of Dubbo service interface exported (optional) - * @return - */ - Set get(String serviceInterface, String group, String version, String protocol); - - - /** - * Get the default extension of {@link ServiceNameMapping} - * - * @return non-null {@link ServiceNameMapping} - * @see DynamicConfigurationServiceNameMapping - */ - static ServiceNameMapping getDefaultExtension() { - return getExtensionLoader(ServiceNameMapping.class).getDefaultExtension(); - } -} diff --git a/dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.LocalMetadataService b/dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.LocalMetadataService deleted file mode 100644 index 2af06fde611..00000000000 --- a/dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.LocalMetadataService +++ /dev/null @@ -1 +0,0 @@ -default=org.apache.dubbo.metadata.InMemoryLocalMetadataService \ No newline at end of file diff --git a/dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.ServiceNameMapping b/dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.ServiceNameMapping deleted file mode 100644 index 3975068fc93..00000000000 --- a/dubbo-metadata/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.ServiceNameMapping +++ /dev/null @@ -1 +0,0 @@ -default=org.apache.dubbo.metadata.DynamicConfigurationServiceNameMapping \ No newline at end of file diff --git a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMappingTest.java b/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMappingTest.java deleted file mode 100644 index 95e7a1689ad..00000000000 --- a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/DynamicConfigurationServiceNameMappingTest.java +++ /dev/null @@ -1,114 +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; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.config.Environment; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.configcenter.DynamicConfiguration; -import org.apache.dubbo.configcenter.DynamicConfigurationFactory; -import org.apache.dubbo.rpc.model.ApplicationModel; - -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.ExponentialBackoffRetry; -import org.apache.curator.test.TestingServer; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import java.util.Set; -import java.util.TreeSet; - -import static java.util.Arrays.asList; -import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; -import static org.apache.dubbo.metadata.DynamicConfigurationServiceNameMapping.buildGroup; -import static org.apache.dubbo.metadata.ServiceNameMapping.getDefaultExtension; -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * {@link DynamicConfigurationServiceNameMapping} Test - * - * @since 2.7.3 - */ -public class DynamicConfigurationServiceNameMappingTest { - - private static CuratorFramework client; - - private static URL configUrl; - private static int zkServerPort = NetUtils.getAvailablePort(); - private static TestingServer zkServer; - - private final ServiceNameMapping serviceNameMapping = getDefaultExtension(); - - @BeforeAll - public static void setUp() throws Exception { - - zkServer = new TestingServer(zkServerPort, true); - - client = CuratorFrameworkFactory.newClient("localhost:" + zkServerPort, 60 * 1000, 60 * 1000, - new ExponentialBackoffRetry(1000, 3)); - - client.start(); - - configUrl = URL.valueOf("zookeeper://localhost:" + zkServerPort); - - DynamicConfiguration configuration = getExtensionLoader(DynamicConfigurationFactory.class) - .getExtension(configUrl.getProtocol()) - .getDynamicConfiguration(configUrl); - - Environment.getInstance().setDynamicConfiguration(configuration); - } - - @AfterAll - public static void tearDown() throws Exception { - zkServer.stop(); - } - - @Test - public void testBuildGroup() { - assertEquals("test:::", buildGroup("test", null, null, null)); - assertEquals("test:default::", buildGroup("test", "default", null, null)); - assertEquals("test:default:1.0.0:", buildGroup("test", "default", "1.0.0", null)); - assertEquals("test:default:1.0.0:dubbo", buildGroup("test", "default", "1.0.0", "dubbo")); - } - - @Test - public void testMapAndGet() { - - String serviceName = "test"; - String serviceName2 = "test2"; - - ApplicationModel.setApplication(serviceName); - - String serviceInterface = "org.apache.dubbo.service.UserService"; - String group = null; - String version = null; - String protocol = null; - - serviceNameMapping.map(serviceInterface, group, version, protocol); - - ApplicationModel.setApplication(serviceName2); - - serviceNameMapping.map(serviceInterface, group, version, protocol); - - Set serviceNames = serviceNameMapping.get(serviceInterface, group, version, protocol); - - assertEquals(new TreeSet(asList(serviceName, serviceName2)), serviceNames); - - } -} diff --git a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/InMemoryLocalMetadataServiceTest.java b/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/InMemoryLocalMetadataServiceTest.java deleted file mode 100644 index 406e4aeb98e..00000000000 --- a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/InMemoryLocalMetadataServiceTest.java +++ /dev/null @@ -1,140 +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; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.rpc.model.ApplicationModel; - -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import java.util.List; - -import static java.util.Arrays.asList; -import static org.apache.dubbo.common.URL.valueOf; -import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * {@link InMemoryLocalMetadataService} Test - * - * @since 2.7.3 - */ -public class InMemoryLocalMetadataServiceTest { - - private LocalMetadataService metadataService = new InMemoryLocalMetadataService(); - - private static final String TEST_SERVICE = "org.apache.dubbo.test.TestService"; - - private static final URL BASE_URL = valueOf("dubbo://127.0.0.1:20880/" + TEST_SERVICE); - private static final URL REST_BASE_URL = valueOf("rest://127.0.0.1:20880/" + TEST_SERVICE); - private static final URL BASE_URL_GROUP = BASE_URL.addParameter(GROUP_KEY, "test"); - private static final URL BASE_URL_GROUP_AND_VERSION = BASE_URL_GROUP.addParameter(VERSION_KEY, "1.0.0"); - private static final URL BASE_URL_GROUP_AND_VERSION_AND_PROTOCOL = BASE_URL_GROUP_AND_VERSION.addParameter(PROTOCOL_KEY, "rest"); - - @BeforeAll - public static void init() { - ApplicationModel.setApplication("test"); - } - - @Test - public void testServiceName() { - assertEquals("test", metadataService.serviceName()); - } - - @Test - public void testVersion() { - assertEquals("1.0.0", MetadataService.VERSION); - assertEquals("1.0.0", metadataService.version()); - } - - @Test - public void testGetExportedURLs() { - - assertTrue(metadataService.exportURL(BASE_URL)); - List exportedURLs = metadataService.getExportedURLs(TEST_SERVICE); - assertEquals(1, exportedURLs.size()); - assertEquals(asList(BASE_URL.toFullString()), exportedURLs); - assertTrue(metadataService.unexportURL(BASE_URL)); - - assertTrue(metadataService.exportURL(BASE_URL)); - assertFalse(metadataService.exportURL(BASE_URL)); - - assertTrue(metadataService.exportURL(BASE_URL_GROUP)); - assertTrue(metadataService.exportURL(BASE_URL_GROUP_AND_VERSION)); - - exportedURLs = metadataService.getExportedURLs(TEST_SERVICE); - assertEquals(asList(BASE_URL.toFullString()), exportedURLs); - assertEquals(asList( - BASE_URL.toFullString(), - BASE_URL_GROUP.toFullString(), - BASE_URL_GROUP_AND_VERSION.toFullString()), metadataService.getExportedURLs()); - - assertTrue(metadataService.exportURL(REST_BASE_URL)); - exportedURLs = metadataService.getExportedURLs(TEST_SERVICE); - assertEquals(asList(BASE_URL.toFullString(), REST_BASE_URL.toFullString()), exportedURLs); - - metadataService.exportURL(BASE_URL_GROUP_AND_VERSION_AND_PROTOCOL); - - exportedURLs = metadataService.getExportedURLs(TEST_SERVICE, "test", "1.0.0", "rest"); - - assertEquals(asList(BASE_URL_GROUP_AND_VERSION_AND_PROTOCOL.toFullString()), exportedURLs); - } - - @Test - public void testGetSubscribedURLs() { - assertTrue(metadataService.subscribeURL(BASE_URL)); - assertFalse(metadataService.subscribeURL(BASE_URL)); - - assertTrue(metadataService.subscribeURL(BASE_URL_GROUP)); - assertTrue(metadataService.subscribeURL(BASE_URL_GROUP_AND_VERSION)); - assertTrue(metadataService.subscribeURL(REST_BASE_URL)); - - List subscribedURLs = metadataService.getSubscribedURLs(); - assertEquals(4, subscribedURLs.size()); - assertEquals(asList( - BASE_URL.toFullString(), - REST_BASE_URL.toFullString(), - BASE_URL_GROUP.toFullString(), - BASE_URL_GROUP_AND_VERSION.toFullString()), subscribedURLs); - - assertTrue(metadataService.unsubscribeURL(REST_BASE_URL)); - subscribedURLs = metadataService.getSubscribedURLs(); - assertEquals(3, subscribedURLs.size()); - assertEquals(asList( - BASE_URL.toFullString(), - BASE_URL_GROUP.toFullString(), - BASE_URL_GROUP_AND_VERSION.toFullString()), subscribedURLs); - - assertTrue(metadataService.unsubscribeURL(BASE_URL_GROUP)); - subscribedURLs = metadataService.getSubscribedURLs(); - assertEquals(2, subscribedURLs.size()); - assertEquals(asList( - BASE_URL.toFullString(), - BASE_URL_GROUP_AND_VERSION.toFullString()), subscribedURLs); - - assertTrue(metadataService.unsubscribeURL(BASE_URL_GROUP_AND_VERSION)); - subscribedURLs = metadataService.getSubscribedURLs(); - assertEquals(1, subscribedURLs.size()); - assertEquals(asList( - BASE_URL.toFullString()), subscribedURLs); - } -} \ No newline at end of file diff --git a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java b/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java deleted file mode 100644 index 508a9598738..00000000000 --- a/dubbo-metadata/src/test/java/org/apache/dubbo/metadata/LocalMetadataServiceTest.java +++ /dev/null @@ -1,34 +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; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * {@link LocalMetadataService} Test - * - * @since 2.7.3 - */ -public class LocalMetadataServiceTest { - - @Test - public void testDefaultExtension() { - assertEquals(InMemoryLocalMetadataService.class, LocalMetadataService.getDefaultExtension().getClass()); - } -} From f66226d2fd5bdcbd8438d40c01c6a5cbbd0ef344 Mon Sep 17 00:00:00 2001 From: "ken.lj" Date: Thu, 20 Jun 2019 17:48:59 +0800 Subject: [PATCH 46/46] add new SPIs and modules to dubbo-all pom. --- dubbo-all/pom.xml | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/dubbo-all/pom.xml b/dubbo-all/pom.xml index b47d580e0ab..8b9a4c53c9d 100644 --- a/dubbo-all/pom.xml +++ b/dubbo-all/pom.xml @@ -464,13 +464,6 @@ compile true - - org.apache.dubbo - dubbo-metadata-report-api - ${project.version} - compile - true - org.apache.dubbo dubbo-metadata-report-zookeeper @@ -639,8 +632,6 @@ org.apache.dubbo:dubbo-configcenter-etcd org.apache.dubbo:dubbo-configcenter-nacos org.apache.dubbo:dubbo-metadata-api - org.apache.dubbo:dubbo-metadata-report-api - org.apache.dubbo:dubbo-metadata-definition org.apache.dubbo:dubbo-metadata-report-redis org.apache.dubbo:dubbo-metadata-report-zookeeper org.apache.dubbo:dubbo-metadata-report-consul @@ -648,10 +639,7 @@ org.apache.dubbo:dubbo-metadata-report-nacos org.apache.dubbo:dubbo-serialization-native-hession org.apache.dubbo:dubbo-rpc-native-thrift - - org.apache.dubbo:dubbo-event - org.apache.dubbo:dubbo-metadata @@ -774,7 +762,7 @@ - META-INF/dubbo/internal/org.apache.dubbo.metadata.store.MetadataReportFactory + META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory @@ -787,7 +775,19 @@ - META-INF/dubbo/internal/org.apache.dubbo.metadata.LocalMetadataService + 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.MetadataServiceProxyFactory + + + + META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscoveryFactory