You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@dubbo.apache.org by al...@apache.org on 2022/12/30 08:00:38 UTC

[dubbo-samples] branch master updated: feat: Add README.md file , Integrate EmbeddedZooKeeper , More intuition startup by copy provider and config xml (#694)

This is an automated email from the ASF dual-hosted git repository.

albumenj pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/dubbo-samples.git


The following commit(s) were added to refs/heads/master by this push:
     new f1386e52 feat: Add README.md file , Integrate EmbeddedZooKeeper , More intuition startup by copy provider and config xml (#694)
f1386e52 is described below

commit f1386e524bbea83706c1c6711ea09f739b073ffa
Author: Yao Zhou <zh...@users.noreply.github.com>
AuthorDate: Fri Dec 30 16:00:31 2022 +0800

    feat: Add README.md file , Integrate EmbeddedZooKeeper , More intuition startup by copy provider and config xml (#694)
---
 4-governance/dubbo-samples-tagrouter/README.md     |  27 +++
 .../dubbo/samples/governance/BasicProvider.java    |   4 +-
 ...icProvider.java => BasicProviderOtherPort.java} |   4 +-
 .../samples/governance/EmbeddedZooKeeper.java      | 250 +++++++++++++++++++++
 ...-provider.xml => dubbo-demo-provider-20880.xml} |   2 +-
 ...-provider.xml => dubbo-demo-provider-20881.xml} |   2 +-
 6 files changed, 284 insertions(+), 5 deletions(-)

diff --git a/4-governance/dubbo-samples-tagrouter/README.md b/4-governance/dubbo-samples-tagrouter/README.md
new file mode 100644
index 00000000..17112211
--- /dev/null
+++ b/4-governance/dubbo-samples-tagrouter/README.md
@@ -0,0 +1,27 @@
+# governance dubbo using tag router
+1. step1 run `BasicProvider.java`
+
+> it will start an zookeeper and register two service with dubbo port 20880
+2. step2 run `BasicProviderOtherPort.java`
+> it will register another two service with dubbo port 20881
+3. step3 run `RuleUtil.java`,
+>  it will read the route rule defined by [dubbo-routers-tag.yml](src%2Fmain%2Fresources%2Fdubbo-routers-tag.yml)
+```yaml
+---
+force: false
+runtime: true
+enabled: true
+priority: 1
+key: governance-tagrouter-provider
+tags:
+- name: tag1
+  addresses: ["*.*.*.*:20881"]
+- name: tag2
+  addresses: ["*.*.*.*:20880"]
+...
+```
+
+6. step4 run `BasicConsumer.java`
+>  it will consume service by rule defined by yml file
+> * All consumer taged by `tag1` come from provider in port 20881
+> * All consumer taged by `tag2` come from provider in port 20880
\ No newline at end of file
diff --git a/4-governance/dubbo-samples-tagrouter/src/main/java/org/apache/dubbo/samples/governance/BasicProvider.java b/4-governance/dubbo-samples-tagrouter/src/main/java/org/apache/dubbo/samples/governance/BasicProvider.java
index 033bf625..bf3a4a32 100644
--- a/4-governance/dubbo-samples-tagrouter/src/main/java/org/apache/dubbo/samples/governance/BasicProvider.java
+++ b/4-governance/dubbo-samples-tagrouter/src/main/java/org/apache/dubbo/samples/governance/BasicProvider.java
@@ -26,7 +26,9 @@ import java.util.concurrent.CountDownLatch;
 public class BasicProvider {
 
     public static void main(String[] args) throws Exception {
-        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/dubbo-demo-provider.xml");
+        new EmbeddedZooKeeper(2181, false).start();
+
+        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/dubbo-demo-provider-20880.xml");
         context.start();
 
         System.out.println("dubbo service started");
diff --git a/4-governance/dubbo-samples-tagrouter/src/main/java/org/apache/dubbo/samples/governance/BasicProvider.java b/4-governance/dubbo-samples-tagrouter/src/main/java/org/apache/dubbo/samples/governance/BasicProviderOtherPort.java
similarity index 92%
copy from 4-governance/dubbo-samples-tagrouter/src/main/java/org/apache/dubbo/samples/governance/BasicProvider.java
copy to 4-governance/dubbo-samples-tagrouter/src/main/java/org/apache/dubbo/samples/governance/BasicProviderOtherPort.java
index 033bf625..b80e003e 100644
--- a/4-governance/dubbo-samples-tagrouter/src/main/java/org/apache/dubbo/samples/governance/BasicProvider.java
+++ b/4-governance/dubbo-samples-tagrouter/src/main/java/org/apache/dubbo/samples/governance/BasicProviderOtherPort.java
@@ -23,10 +23,10 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
 
 import java.util.concurrent.CountDownLatch;
 
-public class BasicProvider {
+public class BasicProviderOtherPort {
 
     public static void main(String[] args) throws Exception {
-        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/dubbo-demo-provider.xml");
+        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/dubbo-demo-provider-20881.xml");
         context.start();
 
         System.out.println("dubbo service started");
diff --git a/4-governance/dubbo-samples-tagrouter/src/main/java/org/apache/dubbo/samples/governance/EmbeddedZooKeeper.java b/4-governance/dubbo-samples-tagrouter/src/main/java/org/apache/dubbo/samples/governance/EmbeddedZooKeeper.java
new file mode 100644
index 00000000..c4ed0399
--- /dev/null
+++ b/4-governance/dubbo-samples-tagrouter/src/main/java/org/apache/dubbo/samples/governance/EmbeddedZooKeeper.java
@@ -0,0 +1,250 @@
+/*
+ * Copyright 2014 the original author or authors.
+ *
+ * Licensed 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.samples.governance;
+
+import org.apache.zookeeper.server.ServerConfig;
+import org.apache.zookeeper.server.ZooKeeperServerMain;
+import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.context.SmartLifecycle;
+import org.springframework.util.ErrorHandler;
+import org.springframework.util.SocketUtils;
+
+import java.io.File;
+import java.lang.reflect.Method;
+import java.util.Properties;
+import java.util.UUID;
+
+/**
+ * from: https://github.com/spring-projects/spring-xd/blob/v1.3.1.RELEASE/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/zookeeper/ZooKeeperUtils.java
+ * <p>
+ * Helper class to start an embedded instance of standalone (non clustered) ZooKeeper.
+ * <p>
+ * NOTE: at least an external standalone server (if not an ensemble) are recommended, even for
+ * {@link org.springframework.xd.dirt.server.singlenode.SingleNodeApplication}
+ *
+ * @author Patrick Peralta
+ * @author Mark Fisher
+ * @author David Turanski
+ */
+public class EmbeddedZooKeeper implements SmartLifecycle {
+
+    /**
+     * Logger.
+     */
+    private static final Logger logger = LoggerFactory.getLogger(EmbeddedZooKeeper.class);
+
+    /**
+     * ZooKeeper client port. This will be determined dynamically upon startup.
+     */
+    private final int clientPort;
+
+    /**
+     * Whether to auto-start. Default is true.
+     */
+    private boolean autoStartup = true;
+
+    /**
+     * Lifecycle phase. Default is 0.
+     */
+    private int phase = 0;
+
+    /**
+     * Thread for running the ZooKeeper server.
+     */
+    private volatile Thread zkServerThread;
+
+    /**
+     * ZooKeeper server.
+     */
+    private volatile ZooKeeperServerMain zkServer;
+
+    /**
+     * {@link ErrorHandler} to be invoked if an Exception is thrown from the ZooKeeper server thread.
+     */
+    private ErrorHandler errorHandler;
+
+    private boolean daemon = true;
+
+    /**
+     * Construct an EmbeddedZooKeeper with a random port.
+     */
+    public EmbeddedZooKeeper() {
+        clientPort = SocketUtils.findAvailableTcpPort();
+    }
+
+    /**
+     * Construct an EmbeddedZooKeeper with the provided port.
+     *
+     * @param clientPort port for ZooKeeper server to bind to
+     */
+    public EmbeddedZooKeeper(int clientPort, boolean daemon) {
+        this.clientPort = clientPort;
+        this.daemon = daemon;
+    }
+
+    /**
+     * Returns the port that clients should use to connect to this embedded server.
+     *
+     * @return dynamically determined client port
+     */
+    public int getClientPort() {
+        return this.clientPort;
+    }
+
+    /**
+     * Specify whether to start automatically. Default is true.
+     *
+     * @param autoStartup whether to start automatically
+     */
+    public void setAutoStartup(boolean autoStartup) {
+        this.autoStartup = autoStartup;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public boolean isAutoStartup() {
+        return this.autoStartup;
+    }
+
+    /**
+     * Specify the lifecycle phase for the embedded server.
+     *
+     * @param phase the lifecycle phase
+     */
+    public void setPhase(int phase) {
+        this.phase = phase;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public int getPhase() {
+        return this.phase;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public boolean isRunning() {
+        return (zkServerThread != null);
+    }
+
+    /**
+     * Start the ZooKeeper server in a background thread.
+     * <p>
+     * Register an error handler via {@link #setErrorHandler} in order to handle
+     * any exceptions thrown during startup or execution.
+     */
+    @Override
+    public synchronized void start() {
+        if (zkServerThread == null) {
+            zkServerThread = new Thread(new ServerRunnable(), "ZooKeeper Server Starter");
+            zkServerThread.setDaemon(daemon);
+            zkServerThread.start();
+        }
+    }
+
+    /**
+     * Shutdown the ZooKeeper server.
+     */
+    @Override
+    public synchronized void stop() {
+        if (zkServerThread != null) {
+            // The shutdown method is protected...thus this hack to invoke it.
+            // This will log an exception on shutdown; see
+            // https://issues.apache.org/jira/browse/ZOOKEEPER-1873 for details.
+            try {
+                Method shutdown = ZooKeeperServerMain.class.getDeclaredMethod("shutdown");
+                shutdown.setAccessible(true);
+                shutdown.invoke(zkServer);
+            } catch (Exception e) {
+                throw new RuntimeException(e);
+            }
+
+            // It is expected that the thread will exit after
+            // the server is shutdown; this will block until
+            // the shutdown is complete.
+            try {
+                zkServerThread.join(5000);
+                zkServerThread = null;
+            } catch (InterruptedException e) {
+                Thread.currentThread().interrupt();
+                logger.warn("Interrupted while waiting for embedded ZooKeeper to exit");
+                // abandoning zk thread
+                zkServerThread = null;
+            }
+        }
+    }
+
+    /**
+     * Stop the server if running and invoke the callback when complete.
+     */
+    @Override
+    public void stop(Runnable callback) {
+        stop();
+        callback.run();
+    }
+
+    /**
+     * Provide an {@link ErrorHandler} to be invoked if an Exception is thrown from the ZooKeeper server thread. If none
+     * is provided, only error-level logging will occur.
+     *
+     * @param errorHandler the {@link ErrorHandler} to be invoked
+     */
+    public void setErrorHandler(ErrorHandler errorHandler) {
+        this.errorHandler = errorHandler;
+    }
+
+    /**
+     * Runnable implementation that starts the ZooKeeper server.
+     */
+    private class ServerRunnable implements Runnable {
+
+        @Override
+        public void run() {
+            try {
+                Properties properties = new Properties();
+                File file = new File(System.getProperty("java.io.tmpdir")
+                        + File.separator + UUID.randomUUID());
+                file.deleteOnExit();
+                properties.setProperty("dataDir", file.getAbsolutePath());
+                properties.setProperty("clientPort", String.valueOf(clientPort));
+
+                QuorumPeerConfig quorumPeerConfig = new QuorumPeerConfig();
+                quorumPeerConfig.parseProperties(properties);
+
+                zkServer = new ZooKeeperServerMain();
+                ServerConfig configuration = new ServerConfig();
+                configuration.readFrom(quorumPeerConfig);
+
+                zkServer.runFromConfig(configuration);
+            } catch (Exception e) {
+                if (errorHandler != null) {
+                    errorHandler.handleError(e);
+                } else {
+                    logger.error("Exception running embedded ZooKeeper", e);
+                }
+            }
+        }
+    }
+
+}
diff --git a/4-governance/dubbo-samples-tagrouter/src/main/resources/spring/dubbo-demo-provider.xml b/4-governance/dubbo-samples-tagrouter/src/main/resources/spring/dubbo-demo-provider-20880.xml
similarity index 96%
copy from 4-governance/dubbo-samples-tagrouter/src/main/resources/spring/dubbo-demo-provider.xml
copy to 4-governance/dubbo-samples-tagrouter/src/main/resources/spring/dubbo-demo-provider-20880.xml
index 1a772546..8f01b7fb 100644
--- a/4-governance/dubbo-samples-tagrouter/src/main/resources/spring/dubbo-demo-provider.xml
+++ b/4-governance/dubbo-samples-tagrouter/src/main/resources/spring/dubbo-demo-provider-20880.xml
@@ -31,7 +31,7 @@
 
     <dubbo:provider token="true"/>
 
-    <dubbo:protocol name="dubbo" port="${dubbo.port:-1}" heartbeat="10000"/>
+    <dubbo:protocol name="dubbo" port="${dubbo.port:20880}" heartbeat="10000"/>
 
     <dubbo:config-center highest-priority="false" address="zookeeper://${zookeeper.address:127.0.0.1}:2181"/>
 
diff --git a/4-governance/dubbo-samples-tagrouter/src/main/resources/spring/dubbo-demo-provider.xml b/4-governance/dubbo-samples-tagrouter/src/main/resources/spring/dubbo-demo-provider-20881.xml
similarity index 96%
rename from 4-governance/dubbo-samples-tagrouter/src/main/resources/spring/dubbo-demo-provider.xml
rename to 4-governance/dubbo-samples-tagrouter/src/main/resources/spring/dubbo-demo-provider-20881.xml
index 1a772546..fbe332c6 100644
--- a/4-governance/dubbo-samples-tagrouter/src/main/resources/spring/dubbo-demo-provider.xml
+++ b/4-governance/dubbo-samples-tagrouter/src/main/resources/spring/dubbo-demo-provider-20881.xml
@@ -31,7 +31,7 @@
 
     <dubbo:provider token="true"/>
 
-    <dubbo:protocol name="dubbo" port="${dubbo.port:-1}" heartbeat="10000"/>
+    <dubbo:protocol name="dubbo" port="${dubbo.port:20881}" heartbeat="10000"/>
 
     <dubbo:config-center highest-priority="false" address="zookeeper://${zookeeper.address:127.0.0.1}:2181"/>
 


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@dubbo.apache.org
For additional commands, e-mail: notifications-help@dubbo.apache.org