You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@dubbo.apache.org by mi...@apache.org on 2018/12/25 07:03:17 UTC

[incubator-dubbo-samples] branch samples-for-2.7.0-SNAPSHOT updated: add generic call sample

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

min pushed a commit to branch samples-for-2.7.0-SNAPSHOT
in repository https://gitbox.apache.org/repos/asf/incubator-dubbo-samples.git


The following commit(s) were added to refs/heads/samples-for-2.7.0-SNAPSHOT by this push:
     new 15e272b  add generic call sample
15e272b is described below

commit 15e272b2566531779812e3d76da752543294a5ee
Author: nzomkxia <z8...@gmail.com>
AuthorDate: Tue Dec 25 15:03:12 2018 +0800

    add generic call sample
---
 dubbo-samples-generic-call/pom.xml                 |  15 ++
 .../samples/generic/call/EmbeddedZooKeeper.java    | 255 +++++++++++++++++++++
 .../samples/generic/call/GenericCallConsumer.java  |  44 ++++
 .../samples/generic/call/GenericCallProvider.java  |  36 +++
 .../samples/generic/call/api/HelloService.java     |  24 ++
 .../generic/call/impl/HelloServiceImpl.java        |  30 +++
 .../src/main/resources/log4j.properties            |  26 +++
 .../src/main/resources/spring/generic-provider.xml |  37 +++
 pom.xml                                            |   1 +
 9 files changed, 468 insertions(+)

diff --git a/dubbo-samples-generic-call/pom.xml b/dubbo-samples-generic-call/pom.xml
new file mode 100644
index 0000000..5e24aa8
--- /dev/null
+++ b/dubbo-samples-generic-call/pom.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <parent>
+        <artifactId>dubbo-samples-all</artifactId>
+        <groupId>org.apache.dubbo</groupId>
+        <version>1.0-SNAPSHOT</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+
+    <artifactId>dubbo-samples-generic-call</artifactId>
+
+
+</project>
diff --git a/dubbo-samples-generic-call/src/main/java/org/apache/dubbo/samples/generic/call/EmbeddedZooKeeper.java b/dubbo-samples-generic-call/src/main/java/org/apache/dubbo/samples/generic/call/EmbeddedZooKeeper.java
new file mode 100644
index 0000000..bbac4fb
--- /dev/null
+++ b/dubbo-samples-generic-call/src/main/java/org/apache/dubbo/samples/generic/call/EmbeddedZooKeeper.java
@@ -0,0 +1,255 @@
+/*
+ * 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.generic.call;
+
+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
+ *
+ * Helper class to start an embedded instance of standalone (non clustered) ZooKeeper.
+ *
+ * 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/dubbo-samples-generic-call/src/main/java/org/apache/dubbo/samples/generic/call/GenericCallConsumer.java b/dubbo-samples-generic-call/src/main/java/org/apache/dubbo/samples/generic/call/GenericCallConsumer.java
new file mode 100644
index 0000000..169c7a4
--- /dev/null
+++ b/dubbo-samples-generic-call/src/main/java/org/apache/dubbo/samples/generic/call/GenericCallConsumer.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.samples.generic.call;
+
+import org.apache.dubbo.config.ApplicationConfig;
+import org.apache.dubbo.config.ReferenceConfig;
+import org.apache.dubbo.config.RegistryConfig;
+import org.apache.dubbo.rpc.service.GenericService;
+
+public class GenericCallConsumer {
+
+    public static void main(String[] args) {
+        ApplicationConfig applicationConfig = new ApplicationConfig();
+        applicationConfig.setName("generic-call-consumer");
+        RegistryConfig registryConfig = new RegistryConfig();
+        registryConfig.setAddress("zookeeper://127.0.0.1:2181");
+        ReferenceConfig<GenericService> referenceConfig = new ReferenceConfig<>();
+        referenceConfig.setInterface("org.apache.dubbo.samples.generic.call.api.HelloService");
+        applicationConfig.setRegistry(registryConfig);
+        referenceConfig.setApplication(applicationConfig);
+        referenceConfig.setGeneric(true);
+        GenericService genericService = referenceConfig.get();
+        Object result = genericService.$invoke("sayHello", new String[]{"java.lang.String"}, new Object[]{"world"});
+        System.out.println(result);
+    }
+
+}
diff --git a/dubbo-samples-generic-call/src/main/java/org/apache/dubbo/samples/generic/call/GenericCallProvider.java b/dubbo-samples-generic-call/src/main/java/org/apache/dubbo/samples/generic/call/GenericCallProvider.java
new file mode 100644
index 0000000..8970f5d
--- /dev/null
+++ b/dubbo-samples-generic-call/src/main/java/org/apache/dubbo/samples/generic/call/GenericCallProvider.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.samples.generic.call;
+
+import org.springframework.context.support.ClassPathXmlApplicationContext;
+
+/**
+ * GenericCallProvider
+ */
+public class GenericCallProvider {
+
+    public static void main(String[] args) throws Exception {
+        new EmbeddedZooKeeper(2181, false).start();
+        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"spring/generic-provider.xml"});
+        context.start();
+        System.in.read();
+    }
+
+}
diff --git a/dubbo-samples-generic-call/src/main/java/org/apache/dubbo/samples/generic/call/api/HelloService.java b/dubbo-samples-generic-call/src/main/java/org/apache/dubbo/samples/generic/call/api/HelloService.java
new file mode 100644
index 0000000..0718a35
--- /dev/null
+++ b/dubbo-samples-generic-call/src/main/java/org/apache/dubbo/samples/generic/call/api/HelloService.java
@@ -0,0 +1,24 @@
+/*
+ *
+ *   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.samples.generic.call.api;
+
+public interface HelloService {
+    String sayHello(String name);
+}
diff --git a/dubbo-samples-generic-call/src/main/java/org/apache/dubbo/samples/generic/call/impl/HelloServiceImpl.java b/dubbo-samples-generic-call/src/main/java/org/apache/dubbo/samples/generic/call/impl/HelloServiceImpl.java
new file mode 100644
index 0000000..b2d88f1
--- /dev/null
+++ b/dubbo-samples-generic-call/src/main/java/org/apache/dubbo/samples/generic/call/impl/HelloServiceImpl.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.samples.generic.call.impl;
+
+import org.apache.dubbo.samples.generic.call.api.HelloService;
+
+public class HelloServiceImpl implements HelloService {
+
+    @Override
+    public String sayHello(String name) {
+        return "=======" + "Hello " + name + "========";
+    }
+}
diff --git a/dubbo-samples-generic-call/src/main/resources/log4j.properties b/dubbo-samples-generic-call/src/main/resources/log4j.properties
new file mode 100644
index 0000000..7232873
--- /dev/null
+++ b/dubbo-samples-generic-call/src/main/resources/log4j.properties
@@ -0,0 +1,26 @@
+#
+#
+#   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.
+#  
+#
+
+###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-samples-generic-call/src/main/resources/spring/generic-provider.xml b/dubbo-samples-generic-call/src/main/resources/spring/generic-provider.xml
new file mode 100644
index 0000000..4c5d7c6
--- /dev/null
+++ b/dubbo-samples-generic-call/src/main/resources/spring/generic-provider.xml
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~
+  ~   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.
+  ~
+  -->
+
+<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:dubbo="http://dubbo.apache.org/schema/dubbo"
+       xmlns="http://www.springframework.org/schema/beans"
+       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
+       http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd">
+
+    <dubbo:application name="generic-call"/>
+
+    <dubbo:registry address="zookeeper://127.0.0.1:2181"/>
+
+    <dubbo:protocol name="dubbo" port="20880"/>
+
+    <bean id="helloserviceimpl" class="org.apache.dubbo.samples.generic.call.impl.HelloServiceImpl"/>
+
+    <dubbo:service interface="org.apache.dubbo.samples.generic.call.api.HelloService" ref="helloserviceimpl"/>
+
+</beans>
diff --git a/pom.xml b/pom.xml
index 4df253e..7f5c36c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -57,6 +57,7 @@
         <module>dubbo-samples-metadata-report</module>
         <module>dubbo-samples-simplified-registry</module>
         <module>dubbo-samples-chain</module>
+        <module>dubbo-samples-generic-call</module>
     </modules>
 
     <properties>