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

earthchen 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 3dddede58 opt triple backpress test (#1283)
3dddede58 is described below

commit 3dddede58a090a5ee63b5670d7be26e397ce9707
Author: earthchen <[email protected]>
AuthorDate: Tue Jan 13 16:03:44 2026 +0800

    opt triple backpress test (#1283)
    
    * opt triple backpress test
    
    * fix
---
 .../samples/backpressure/BackpressureProvider.java |  10 +-
 .../samples/backpressure/EmbeddedZooKeeper.java    | 278 +++++++++++++++++++++
 .../dubbo/samples/backpressure/BackpressureIT.java |  17 +-
 3 files changed, 288 insertions(+), 17 deletions(-)

diff --git 
a/2-advanced/dubbo-samples-triple-backpressure/src/main/java/org/apache/dubbo/samples/backpressure/BackpressureProvider.java
 
b/2-advanced/dubbo-samples-triple-backpressure/src/main/java/org/apache/dubbo/samples/backpressure/BackpressureProvider.java
index a4f214a8f..1a8bd504c 100644
--- 
a/2-advanced/dubbo-samples-triple-backpressure/src/main/java/org/apache/dubbo/samples/backpressure/BackpressureProvider.java
+++ 
b/2-advanced/dubbo-samples-triple-backpressure/src/main/java/org/apache/dubbo/samples/backpressure/BackpressureProvider.java
@@ -35,17 +35,21 @@ public class BackpressureProvider {
     private static final String ZOOKEEPER_HOST = 
System.getProperty("zookeeper.address", "127.0.0.1");
     private static final String ZOOKEEPER_PORT = 
System.getProperty("zookeeper.port", "2181");
 
+    public static final String ZK_ADDRESS = "zookeeper://" + ZOOKEEPER_HOST + 
":" + ZOOKEEPER_PORT;
+
     public static void main(String[] args) {
+
+        new EmbeddedZooKeeper(Integer.parseInt(ZOOKEEPER_PORT), false).start();
+
         ServiceConfig<BackpressureService> service = new ServiceConfig<>();
         service.setInterface(BackpressureService.class);
         service.setRef(new BackpressureServiceImpl());
 
-        String zkAddress = "zookeeper://" + ZOOKEEPER_HOST + ":" + 
ZOOKEEPER_PORT;
-        LOGGER.info("Using ZooKeeper: {}", zkAddress);
+        LOGGER.info("Using ZooKeeper: {}", ZK_ADDRESS);
 
         DubboBootstrap bootstrap = DubboBootstrap.getInstance();
         bootstrap.application(new ApplicationConfig("backpressure-provider"))
-                .registry(new RegistryConfig(zkAddress))
+                .registry(new RegistryConfig(ZK_ADDRESS))
                 .protocol(new ProtocolConfig(CommonConstants.TRIPLE, 50051))
                 .service(service)
                 .start();
diff --git 
a/2-advanced/dubbo-samples-triple-backpressure/src/main/java/org/apache/dubbo/samples/backpressure/EmbeddedZooKeeper.java
 
b/2-advanced/dubbo-samples-triple-backpressure/src/main/java/org/apache/dubbo/samples/backpressure/EmbeddedZooKeeper.java
new file mode 100644
index 000000000..a0406ecd9
--- /dev/null
+++ 
b/2-advanced/dubbo-samples-triple-backpressure/src/main/java/org/apache/dubbo/samples/backpressure/EmbeddedZooKeeper.java
@@ -0,0 +1,278 @@
+
+/*
+ * 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.backpressure;
+
+import java.io.File;
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.net.ServerSocket;
+import java.util.List;
+import java.util.Properties;
+import java.util.Random;
+import java.util.UUID;
+import java.util.stream.Collectors;
+
+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;
+
+/**
+ * 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}
+ */
+public class EmbeddedZooKeeper {
+
+    private static final Random RANDOM = new Random();
+
+    /**
+     * 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;
+
+    private boolean daemon = true;
+
+    /**
+     * Construct an EmbeddedZooKeeper with a random port.
+     */
+    public EmbeddedZooKeeper() {
+        clientPort = findRandomPort(30000, 65535);
+    }
+
+    /**
+     * 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}
+     */
+    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}
+     */
+    public int getPhase() {
+        return this.phase;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    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.
+     */
+    public synchronized void start() {
+        if (zkServerThread == null) {
+            zkServerThread = new Thread(new ServerRunnable(), "ZooKeeper 
Server Starter");
+            zkServerThread.setDaemon(daemon);
+            zkServerThread.start();
+        }
+    }
+
+    /**
+     * Shutdown the ZooKeeper server.
+     */
+    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.
+     */
+    public void stop(Runnable callback) {
+        stop();
+        callback.run();
+    }
+
+
+    /**
+     * 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);
+
+                System.setProperty("zookeeper.admin.enableServer", "false");
+
+                zkServer.runFromConfig(configuration);
+            } catch (Exception e) {
+                logger.error("Exception running embedded ZooKeeper", e);
+            }
+        }
+    }
+
+    /**
+     * Workaround for SocketUtils.findRandomPort() deprecation.
+     *
+     * @param min min port
+     * @param max max port
+     * @return a random generated available port
+     */
+    private static int findRandomPort(int min, int max) {
+        if (min < 1024) {
+            throw new IllegalArgumentException("Max port shouldn't be less 
than 1024.");
+        }
+
+        if (max > 65535) {
+            throw new IllegalArgumentException("Max port shouldn't be greater 
than 65535.");
+        }
+
+        if (min > max) {
+            throw new IllegalArgumentException("Min port shouldn't be greater 
than max port.");
+        }
+
+        int port = 0;
+        int counter = 0;
+
+        // Workaround for legacy JDK doesn't support Random.nextInt(min, max).
+        List<Integer> randomInts = RANDOM.ints(min, max + 1)
+                .limit(max - min)
+                .mapToObj(Integer::valueOf)
+                .collect(Collectors.toList());
+
+        do {
+            if (counter > max - min) {
+                throw new IllegalStateException("Unable to find a port between 
" + min + "-" + max);
+            }
+
+            port = randomInts.get(counter);
+            counter++;
+        } while (isPortInUse(port));
+
+        return port;
+    }
+
+    private static boolean isPortInUse(int port) {
+        try (ServerSocket ignored = new ServerSocket(port)) {
+            return false;
+        } catch (IOException e) {
+            // continue
+        }
+        return true;
+    }
+}
diff --git 
a/2-advanced/dubbo-samples-triple-backpressure/src/test/java/org/apache/dubbo/samples/backpressure/BackpressureIT.java
 
b/2-advanced/dubbo-samples-triple-backpressure/src/test/java/org/apache/dubbo/samples/backpressure/BackpressureIT.java
index 752e61415..6be523671 100644
--- 
a/2-advanced/dubbo-samples-triple-backpressure/src/test/java/org/apache/dubbo/samples/backpressure/BackpressureIT.java
+++ 
b/2-advanced/dubbo-samples-triple-backpressure/src/test/java/org/apache/dubbo/samples/backpressure/BackpressureIT.java
@@ -16,6 +16,7 @@
  */
 package org.apache.dubbo.samples.backpressure;
 
+import org.apache.dubbo.common.constants.CommonConstants;
 import org.apache.dubbo.common.stream.ClientCallStreamObserver;
 import org.apache.dubbo.common.stream.ClientResponseObserver;
 import org.apache.dubbo.common.stream.StreamObserver;
@@ -78,37 +79,25 @@ public class BackpressureIT {
 
     private static final Logger LOGGER = 
LoggerFactory.getLogger(BackpressureIT.class);
 
-    // Use random port to avoid conflicts between consecutive test runs
-    private static final int PORT = 50052 + (int)(Math.random() * 1000);
-
     private static BackpressureService service;
     private static DubboBootstrap bootstrap;
 
     @BeforeClass
     public static void setup() {
-        // Provider config
-        ServiceConfig<BackpressureService> serviceConfig = new 
ServiceConfig<>();
-        serviceConfig.setInterface(BackpressureService.class);
-        serviceConfig.setRef(new BackpressureServiceImpl());
-
         // Consumer config with direct connection (no registry needed)
         ReferenceConfig<BackpressureService> reference = new 
ReferenceConfig<>();
         reference.setInterface(BackpressureService.class);
-        reference.setUrl("tri://127.0.0.1:" + PORT);
+        reference.setProtocol(CommonConstants.TRIPLE);
         reference.setTimeout(60000);
 
         // Start both provider and consumer using newInstance to avoid 
singleton pollution
         bootstrap = DubboBootstrap.getInstance();
         bootstrap.application(new ApplicationConfig("backpressure-test"))
-                .registry(new RegistryConfig("N/A"))  // No registry needed
-                .protocol(new ProtocolConfig("tri", PORT))
-                .service(serviceConfig)
+                .registry(new RegistryConfig(BackpressureProvider.ZK_ADDRESS)) 
 // No registry needed
                 .reference(reference)
                 .start();
 
         service = reference.get();
-        LOGGER.info("Provider and Consumer started on port {}", PORT);
-
         // Warm up the connection to ensure resources are properly initialized
         // This prevents timing issues when running individual tests
         try {


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to