You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@servicecomb.apache.org by li...@apache.org on 2020/06/16 09:03:59 UTC

[servicecomb-java-chassis] 06/06: [SCB-2000]make Completable future code more simpler

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

liubao pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/servicecomb-java-chassis.git

commit 2c7aa7cbbbaba69388272b4805bb327b9f5602ae
Author: liubao <bi...@qq.com>
AuthorDate: Mon Jun 15 20:54:06 2020 +0800

    [SCB-2000]make Completable future code more simpler
---
 .../org/apache/servicecomb/core/SCBEngine.java     | 23 +++-------
 .../demo/zeroconfig/tests/ServerTest.java          |  1 +
 .../servicecomb/edge/core/EdgeInvocation.java      | 31 ++++++-------
 foundations/foundation-registry/pom.xml            |  4 ++
 .../registry/consumer/MicroserviceManager.java     | 22 +++------
 .../vertx/executor/SinglePoolBlockingExecutor.java | 53 ++++++++++++++++++++++
 .../vertx/executor/VertxContextExecutor.java       | 45 ++++++++++++++++++
 7 files changed, 130 insertions(+), 49 deletions(-)

diff --git a/core/src/main/java/org/apache/servicecomb/core/SCBEngine.java b/core/src/main/java/org/apache/servicecomb/core/SCBEngine.java
index b62537a..ef764c0 100644
--- a/core/src/main/java/org/apache/servicecomb/core/SCBEngine.java
+++ b/core/src/main/java/org/apache/servicecomb/core/SCBEngine.java
@@ -508,22 +508,13 @@ public class SCBEngine {
    */
   public CompletableFuture<MicroserviceReferenceConfig> createMicroserviceReferenceConfigAsync(String microserviceName,
       String versionRule) {
-    CompletableFuture<MicroserviceReferenceConfig> result = new CompletableFuture<>();
-
-    CompletableFuture<MicroserviceVersions> microserviceVersions = DiscoveryManager.INSTANCE
-        .getOrCreateMicroserviceVersionsAsync(parseAppId(microserviceName), microserviceName);
-
-    microserviceVersions.whenComplete((r, e) -> {
-      if (e != null) {
-        result.completeExceptionally(e);
-      } else {
-        ConsumerMicroserviceVersionsMeta microserviceVersionsMeta = CoreMetaUtils
-            .getMicroserviceVersionsMeta(r);
-        result.complete(new MicroserviceReferenceConfig(microserviceVersionsMeta, versionRule));
-      }
-    });
-
-    return result;
+    return DiscoveryManager.INSTANCE
+        .getOrCreateMicroserviceVersionsAsync(parseAppId(microserviceName), microserviceName)
+        .thenApply(versions -> {
+          ConsumerMicroserviceVersionsMeta microserviceVersionsMeta = CoreMetaUtils
+              .getMicroserviceVersionsMeta(versions);
+          return new MicroserviceReferenceConfig(microserviceVersionsMeta, versionRule);
+        });
   }
 
   /**
diff --git a/demo/demo-zeroconfig-schemadiscovery-registry/demo-zeroconfig-schemadiscovery-registry-tests/src/main/java/org/apache/servicecomb/demo/zeroconfig/tests/ServerTest.java b/demo/demo-zeroconfig-schemadiscovery-registry/demo-zeroconfig-schemadiscovery-registry-tests/src/main/java/org/apache/servicecomb/demo/zeroconfig/tests/ServerTest.java
index 23ab351..1d906f5 100644
--- a/demo/demo-zeroconfig-schemadiscovery-registry/demo-zeroconfig-schemadiscovery-registry-tests/src/main/java/org/apache/servicecomb/demo/zeroconfig/tests/ServerTest.java
+++ b/demo/demo-zeroconfig-schemadiscovery-registry/demo-zeroconfig-schemadiscovery-registry-tests/src/main/java/org/apache/servicecomb/demo/zeroconfig/tests/ServerTest.java
@@ -44,6 +44,7 @@ public class ServerTest implements CategorizedTestCase {
             "cse://demo-zeroconfig-schemadiscovery-registry-client/register/url/prefix/getName?name=world",
             String.class));
     // invoke demo-zeroconfig-schemadiscovery-registry-edge
+    // create many threads to test event-loop not blocking
     int thread = 32;
     CountDownLatch latch = new CountDownLatch(thread);
     for (int i = 0; i < thread; i++) {
diff --git a/edge/edge-core/src/main/java/org/apache/servicecomb/edge/core/EdgeInvocation.java b/edge/edge-core/src/main/java/org/apache/servicecomb/edge/core/EdgeInvocation.java
index 445522f..9c502fb 100644
--- a/edge/edge-core/src/main/java/org/apache/servicecomb/edge/core/EdgeInvocation.java
+++ b/edge/edge-core/src/main/java/org/apache/servicecomb/edge/core/EdgeInvocation.java
@@ -30,10 +30,10 @@ import org.apache.servicecomb.core.invocation.InvocationFactory;
 import org.apache.servicecomb.core.provider.consumer.MicroserviceReferenceConfig;
 import org.apache.servicecomb.core.provider.consumer.ReactiveResponseExecutor;
 import org.apache.servicecomb.core.provider.consumer.ReferenceConfig;
+import org.apache.servicecomb.foundation.vertx.executor.VertxContextExecutor;
 import org.apache.servicecomb.foundation.vertx.http.VertxServerRequestToHttpServletRequest;
 import org.apache.servicecomb.foundation.vertx.http.VertxServerResponseToHttpServletResponse;
 
-import io.vertx.core.Context;
 import io.vertx.core.Vertx;
 import io.vertx.ext.web.RoutingContext;
 
@@ -61,24 +61,19 @@ public class EdgeInvocation extends AbstractRestInvocation {
   }
 
   public void edgeInvoke() {
-    Context currentContext = Vertx.currentContext();
-    findMicroserviceVersionMeta().whenComplete((r, e) -> {
-          // get back to the context so that registered handlers can work properly
-          currentContext.runOnContext((event) -> {
-            if (e != null) {
-              sendFailResponse(e);
-            } else {
-              try {
-                microserviceReferenceConfig = r;
-                findRestOperation(microserviceReferenceConfig.getLatestMicroserviceMeta());
-                scheduleInvocation();
-              } catch (Throwable error) {
-                sendFailResponse(error);
-              }
-            }
-          });
+    findMicroserviceVersionMeta().whenCompleteAsync((r, e) -> {
+      if (e != null) {
+        sendFailResponse(e);
+      } else {
+        try {
+          microserviceReferenceConfig = r;
+          findRestOperation(microserviceReferenceConfig.getLatestMicroserviceMeta());
+          scheduleInvocation();
+        } catch (Throwable error) {
+          sendFailResponse(error);
         }
-    );
+      }
+    }, VertxContextExecutor.create(Vertx.currentContext()));
   }
 
   protected CompletableFuture<MicroserviceReferenceConfig> findMicroserviceVersionMeta() {
diff --git a/foundations/foundation-registry/pom.xml b/foundations/foundation-registry/pom.xml
index 044545d..5e6b939 100644
--- a/foundations/foundation-registry/pom.xml
+++ b/foundations/foundation-registry/pom.xml
@@ -37,6 +37,10 @@
     </dependency>
     <dependency>
       <groupId>org.apache.servicecomb</groupId>
+      <artifactId>foundation-vertx</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.servicecomb</groupId>
       <artifactId>swagger-invocation-core</artifactId>
     </dependency>
     <dependency>
diff --git a/foundations/foundation-registry/src/main/java/org/apache/servicecomb/registry/consumer/MicroserviceManager.java b/foundations/foundation-registry/src/main/java/org/apache/servicecomb/registry/consumer/MicroserviceManager.java
index 0c6482a..432cae7 100644
--- a/foundations/foundation-registry/src/main/java/org/apache/servicecomb/registry/consumer/MicroserviceManager.java
+++ b/foundations/foundation-registry/src/main/java/org/apache/servicecomb/registry/consumer/MicroserviceManager.java
@@ -21,6 +21,7 @@ import java.util.Map;
 import java.util.concurrent.CompletableFuture;
 
 import org.apache.servicecomb.foundation.common.concurrent.ConcurrentHashMapEx;
+import org.apache.servicecomb.foundation.vertx.executor.SinglePoolBlockingExecutor;
 import org.apache.servicecomb.registry.api.event.MicroserviceInstanceChangedEvent;
 import org.apache.servicecomb.registry.api.event.task.SafeModeChangeEvent;
 import org.slf4j.Logger;
@@ -72,30 +73,21 @@ public class MicroserviceManager {
   }
 
   public CompletableFuture<MicroserviceVersions> getOrCreateMicroserviceVersionsAsync(String microserviceName) {
-    CompletableFuture<MicroserviceVersions> result = new CompletableFuture<>();
     MicroserviceVersions microserviceVersions = versionsByName.get(microserviceName);
     if (microserviceVersions == null) {
       if (Vertx.currentContext() == null) {
         // not in event-loop, execute in current thread
-        result.complete(getOrCreateMicroserviceVersions(microserviceName));
+        return CompletableFuture.completedFuture(getOrCreateMicroserviceVersions(microserviceName));
       } else {
-        // executing blocking code in event-loop
-        Vertx.currentContext().<MicroserviceVersions>executeBlocking(blockingCodeHandler -> {
-          blockingCodeHandler.complete(getOrCreateMicroserviceVersions(microserviceName));
-        }, r -> {
-          if (r.failed()) {
-            result.completeExceptionally(r.cause());
-          } else {
-            result.complete(r.result());
-          }
-        });
+        // execute in an single thread pool to make sure make less requests to service center
+        return CompletableFuture.supplyAsync(() -> getOrCreateMicroserviceVersions(microserviceName),
+            SinglePoolBlockingExecutor.create());
       }
     } else {
-      result.complete(microserviceVersions);
+      // here do not need switch to another thread, can improve performance
       tryRemoveInvalidMicroservice(microserviceVersions);
+      return CompletableFuture.completedFuture(microserviceVersions);
     }
-
-    return result;
   }
 
   private void tryRemoveInvalidMicroservice(MicroserviceVersions microserviceVersions) {
diff --git a/foundations/foundation-vertx/src/main/java/org/apache/servicecomb/foundation/vertx/executor/SinglePoolBlockingExecutor.java b/foundations/foundation-vertx/src/main/java/org/apache/servicecomb/foundation/vertx/executor/SinglePoolBlockingExecutor.java
new file mode 100644
index 0000000..176e66a
--- /dev/null
+++ b/foundations/foundation-vertx/src/main/java/org/apache/servicecomb/foundation/vertx/executor/SinglePoolBlockingExecutor.java
@@ -0,0 +1,53 @@
+/*
+ * 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.servicecomb.foundation.vertx.executor;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.Executors;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class SinglePoolBlockingExecutor implements Executor {
+  private static final Logger LOGGER = LoggerFactory.getLogger(SinglePoolBlockingExecutor.class);
+
+  private static final Executor SINGLE_POOL = Executors.newSingleThreadExecutor((r) -> {
+    Thread thread = new Thread(r);
+    thread.setName("single-pool-blocking-executor");
+    return thread;
+  });
+
+  public static SinglePoolBlockingExecutor create() {
+    return new SinglePoolBlockingExecutor();
+  }
+
+  private SinglePoolBlockingExecutor() {
+
+  }
+
+  @Override
+  public void execute(Runnable command) {
+    SINGLE_POOL.execute(() -> {
+      try {
+        command.run();
+      } catch (Throwable e) {
+        LOGGER.error("Logic should not throw exception, please fix it", e);
+      }
+    });
+  }
+}
diff --git a/foundations/foundation-vertx/src/main/java/org/apache/servicecomb/foundation/vertx/executor/VertxContextExecutor.java b/foundations/foundation-vertx/src/main/java/org/apache/servicecomb/foundation/vertx/executor/VertxContextExecutor.java
new file mode 100644
index 0000000..a7157ba
--- /dev/null
+++ b/foundations/foundation-vertx/src/main/java/org/apache/servicecomb/foundation/vertx/executor/VertxContextExecutor.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.servicecomb.foundation.vertx.executor;
+
+import java.util.concurrent.Executor;
+
+import io.vertx.core.Context;
+import io.vertx.core.Vertx;
+
+public class VertxContextExecutor implements Executor {
+  public static VertxContextExecutor create(Context context) {
+    return new VertxContextExecutor(context);
+  }
+
+  private Context context;
+
+  private VertxContextExecutor(Context context) {
+    this.context = context;
+  }
+
+  @Override
+  public void execute(Runnable command) {
+    if (context == Vertx.currentContext()) {
+      command.run();
+      return;
+    }
+
+    context.runOnContext(v -> command.run());
+  }
+}