Java 快速開始

2022-04-15 10:37 更新

下載示例代碼

示例代碼在 dubbo-samples 中

  1. 下載源碼
$ git clone -b master https://github.com/apache/dubbo-samples.git
  1. 進入示例目錄
$ cd dubbo-samples/dubbo-samples-protobuf

快速運行示例

在 dubbo-samples-protobuf 目錄

  1. 編譯并打包示例項目
$ mvn clean package
  1. 運行 Provider
$ java -jar ./protobuf-provider/target/protobuf-provider-1.0-SNAPSHOT.jar 
  1. 運行 consumer
$ java -jar ./protobuf-consumer/target/protobuf-consumer-1.0-SNAPSHOT.jar 

輸出以下結(jié)果
result: Hello Hello, response from provider: 30.225.20.43:20880

以上就是一個簡單的 Dubbo 服務(wù)定義、服務(wù)調(diào)用流程

詳細講解

  1. 服務(wù)定義
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;
}
  1. 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>
  1. 編譯與stub 運行 mvn clean compile 后

生成代碼路徑 dubbo-samples-protobuf/protobuf-provider/build/generated/source/proto/main/java/org/apache/dubbo/demo

生成文件列表

.
├── DemoService.java
├── DemoServiceDubbo.java
├── DemoServiceProto.java
├── HelloReply.java
├── HelloReplyOrBuilder.java
├── HelloRequest.java
└── HelloRequestOrBuilder.java

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);
}
  1. 發(fā)布服務(wù)
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"/>
  1. 使用服務(wù)
<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();
    }
}

其他

示例運行過程中還用到了服務(wù)發(fā)現(xiàn)等機制,詳情請參見相關(guān)章節(jié)說明


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號