6.3. java

Java 快速开始

下载示例代码

示例代码在 dubbo-samples

  1. 下载源码:$ Git clone -b master https://github.com/apache/dubbo-samples.git
  2. 进入示例目录:$ cd dubbo-samples/dubbo-samples-protobuf

快速运行示例

在 dubbo-samples-protobuf 目录

  1. 编译并打包示例项目:$ mvn clean package
  2. 运行 Provider:$ java -jar ./protobuf-provider/target/protobuf-provider-1.0-SNAPSHOT.jar
  3. 运行 consumer
    $ java -jar ./protobuf-consumer/target/protobuf-consumer-1.0-SNAPSHOT.jar 
    输出以下结果
    result: Hello Hello, response from provider: 30.225.20.43:20880
    

以上就是一个简单的 Dubbo 服务定义、服务调用流程

详细讲解

  1. 服务定义
    syntax = "proto3";
    option java_multiple_files = true;
    option java_package = "org.apache.dubbo.demo";
    option java_outer_classname = "DemoServiceProto";
    option objc_class_prefix = "DEMOSRV";
    package demoservice;
    // The demo service definition.
    service DemoService {
      rpc SayHello (HelloRequest) returns (HelloReply) {}
    }
    // The request message containing the user's name.
    message HelloRequest {
      string name = 1;
    }
    // The response message containing the greetings
    message HelloReply {
      string message = 1;
    }
    
  2. Protobuf Compiler 插件配置
    <plugin>
        <groupId>org.xolstice.maven.plugins</groupId>
        <artifactId>protobuf-maven-plugin</artifactId>
        <version>0.5.1</version>
        <configuration>
            <protocArtifact>com.google.protobuf:protoc:3.7.1:exe:${os.detected.classifier}</protocArtifact>
            <outputDirectory>build/generated/source/proto/main/java</outputDirectory>
            <clearOutputDirectory>false</clearOutputDirectory>
            <protocPlugins>
                <protocPlugin>
                    <id>dubbo</id>
                    <groupId>org.apache.dubbo</groupId>
                    <artifactId>dubbo-compiler</artifactId>
                    <version>${dubbo.compiler.version}</version>
                    <mainClass>org.apache.dubbo.gen.dubbo.Dubbo3Generator</mainClass>
                </protocPlugin>
            </protocPlugins>
        </configuration>
        <executions>
            <execution>
                <goals>
                    <goal>compile</goal>
                    <goal>test-compile</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
    
  3. 编译与stub 运行 mvn clean compile 后,
    1. 生成代码路径 dubbo-samples-protobuf/protobuf-provider/build/generated/source/proto/main/java/org/apache/dubbo/demo
    2. 生成文件列表
      .
      ├── DemoService.java
      ├── DemoServiceDubbo.java
      ├── DemoServiceProto.java
      ├── HelloReply.java
      ├── HelloReplyOrBuilder.java
      ├── HelloRequest.java
      └── HelloRequestOrBuilder.java
      
    3. DemoService.java 定义如下
      @javax.annotation.Generated(
      value = "by Dubbo generator",
      comments = "Source: DemoService.proto")
      public interface DemoService {
          static final String JAVA_SERVICE_NAME = "org.apache.dubbo.demo.DemoService";
          static final String SERVICE_NAME = "demoservice.DemoService";
          static final boolean inited = DemoServiceDubbo.init();
          org.apache.dubbo.demo.HelloReply sayHello(org.apache.dubbo.demo.HelloRequest request);
          CompletableFuture<org.apache.dubbo.demo.HelloReply> sayHelloAsync(org.apache.dubbo.demo.HelloRequest request);
      }
      
  4. 发布服务
    public class DemoServiceImpl implements DemoService {
        private static final Logger logger = LoggerFactory.getLogger(DemoServiceImpl.class);
        @Override
        public HelloReply sayHello(HelloRequest request) {
            logger.info("Hello " + request.getName() + ", request from consumer: " + RpcContext.getContext().getRemoteAddress());
            return HelloReply.newBuilder()
                    .setMessage("Hello " + request.getName() + ", response from provider: "
                            + RpcContext.getContext().getLocalAddress())
                    .build();
        }
        @Override
        public CompletableFuture<HelloReply> sayHelloAsync(HelloRequest request) {
            return CompletableFuture.completedFuture(sayHello(request));
        }
    }
    
    <bean id="demoServiceImpl" class="org.apache.dubbo.demo.provider.DemoServiceImpl"/>
    <dubbo:service serialization="protobuf" interface="org.apache.dubbo.demo.DemoService"
                   ref="demoServiceImpl"/>
    
  5. 使用服务
    <dubbo:reference scope="remote" id="demoService" check="false" interface="org.apache.dubbo.demo.DemoService"/>
    
    public class ConsumerApplication {
        public static void main(String[] args) throws Exception {
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/dubbo-consumer.xml");
            context.start();
            DemoService demoService = context.getBean("demoService", DemoService.class);
            HelloRequest request = HelloRequest.newBuilder().setName("Hello").build();
            HelloReply reply = demoService.sayHello(request);
            System.out.println("result: " + reply.getMessage());
            System.in.read();
        }
    }
    

Java 语言定义服务

示例使用 Spring XML 配置方式进行演示。除此之外,Dubbo Java 还提供了包括注解、API、配置文件、Spring boot等多种启动与接入方式,具体可参见配置章节具体描述。

下载示例代码

示例代码在 dubbo-samples

  1. 下载源码:$ Git clone -b master https://github.com/apache/dubbo-samples.git
  2. 进入示例目录:$ cd dubbo-samples/dubbo-samples-basic

快速运行示例

在 dubbo-samples-basic 目录

  1. 编译 Provider:$ mvn clean compile -Pprovider
  2. 运行 Provider:$ java -jar ./target/provider.jar
  3. 编译 Consumer:$ mvn clean compile -Pconsumer
  4. 运行 consumer:$ java -jar ./target/consumer.jar

详细解释

  • 定义服务接口
    • DemoService.java
      package org.apache.dubbo.samples.basic.api;
      public interface DemoService {
          String sayHello(String name);
      }
      
  • 在服务提供方实现接口
    • DemoServiceImpl.java
      public class DemoServiceImpl implements DemoService {
          @Override
          public String sayHello(String name) {
              System.out.println("[" + new SimpleDateFormat("HH:mm:ss").format(new Date()) + "] Hello " + name +
                      ", request from consumer: " + RpcContext.getContext().getRemoteAddress());
              return "Hello " + name + ", response from provider: " + RpcContext.getContext().getLocalAddress();
          }
      }
      
  • 用 Spring 配置声明暴露服务
    • provider.xml:
      <bean id="demoService" class="org.apache.dubbo.samples.basic.impl.DemoServiceImpl"/>
      <dubbo:service interface="org.apache.dubbo.samples.basic.api.DemoService" ref="demoService"/>
      

服务消费者

  • 引用远程服务
    • consumer.xml:
      <dubbo:reference id="demoService" check="true" interface="org.apache.dubbo.samples.basic.api.DemoService"/>
      
  • 加载Spring配置,并调用远程服务
    • Consumer.java
      public static void main(String[] args) {
          ...
          DemoService demoService = (DemoService) context.getBean("demoService");
          String hello = demoService.sayHello("world");
          System.out.println(hello);
      }