App下載

將 Grpc 添加到您的 Java 應(yīng)用程序

激萌少女李逵 2021-09-03 09:48:14 瀏覽數(shù) (2138)
反饋

?Grpc?是一個(gè)高性能、開源的通用 RPC 框架。

使用 gRPC 有多種好處:

  • 它通過提供客戶端/服務(wù)器代碼來簡化開發(fā)
  • 它支持多種語言

這一切都始于定義一個(gè)? .proto ?文件,?.proto ?文件是位于 ?src/main/proto ?文件中。

請注意:將 proto 文件保存在 repo 上并進(jìn)行一些模式版本控制是一種很好的做法。通過這種方式,其他團(tuán)隊(duì)的開發(fā)人員可以通過引用它們來生成他們的 sdk,甚至適用于其他語言。

我們將在 ?src/main/proto/Order.proto? 上創(chuàng)建一個(gè)訂單服務(wù)

yntax = "proto3";

option java_multiple_files = true;
option java_package = "com.egkatzioura.order.v1";

service OrderService {
    rpc ExecuteOrder(OrderRequest) returns (OrderResponse) {};
}

message OrderRequest {
    string email = 1;
    string product = 2;
    int32 amount = 3;
}

message OrderResponse {
    string info = 1;
}

為了使用 ?grpc?,需要放置以下相關(guān)文件

<dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-netty-shaded</artifactId>
            <version>1.39.0</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-protobuf</artifactId>
            <version>1.39.0</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-stub</artifactId>
            <version>1.39.0</version>
        </dependency>
        <dependency> <!-- necessary for Java 9+ -->
            <groupId>org.apache.tomcat</groupId>
            <artifactId>annotations-api</artifactId>
            <version>6.0.53</version>
            <scope>provided</scope>
        </dependency
<build>
        <extensions>
            <extension>
                <groupId>kr.motd.maven</groupId>
                <artifactId>os-maven-plugin</artifactId>
                <version>1.6.2</version>
            </extension>
        </extensions>
        <plugins>
            <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.6.1</version>
                <configuration>
                    <protocArtifact>com.google.protobuf:protoc:3.17.2:exe:${os.detected.classifier}</protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.39.0:exe:${os.detected.classifier}</pluginArtifact>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

通過執(zhí)行 ?mvn clean install?,將在目標(biāo)/類上生成類。這些類足以啟動(dòng)服務(wù)器并運(yùn)行客戶端與它進(jìn)行通信。

因此,讓我們嘗試啟動(dòng)服務(wù)器。

我們將創(chuàng)建一個(gè)服務(wù)實(shí)現(xiàn):

package com.egkatzioura.order.impl;
 
import com.egkatzioura.order.v1.Order;
import com.egkatzioura.order.v1.OrderServiceGrpc;
 
import io.grpc.stub.StreamObserver;
 
public class OrderServiceImpl extends OrderServiceGrpc.OrderServiceImplBase {
 
    @Override
    public void executeOrder(Order.OrderRequest request, StreamObserver&amp;lt;Order.OrderResponse&amp;gt; responseObserver) {
 
        Order.OrderResponse response = Order.OrderResponse.newBuilder()
                                                          .setInfo("Hi "+request.getEmail()+", you order has been executed")
                                                          .build();
 
        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }
}

然后我們的主類將啟動(dòng)服務(wù)器并為請求提供服務(wù):

package com.egkatzioura.order;
 
import java.io.IOException;
 
import com.egkatzioura.order.impl.OrderServiceImpl;
import io.grpc.Server;
import io.grpc.ServerBuilder;
 
public class Application {
 
    public static void main(String[] args) throws IOException, InterruptedException {
        Server server = ServerBuilder
                .forPort(8080)
                .addService(new OrderServiceImpl()).build();
 
        server.start();
        server.awaitTermination();
    }
 
}

當(dāng)服務(wù)器運(yùn)行時(shí),我們可以啟動(dòng)另一個(gè)主類,該類將與服務(wù)器通信并向服務(wù)器執(zhí)行 grpc 請求:

package com.egkatzioura.order;
 
import com.egkatzioura.order.v1.Order;
import com.egkatzioura.order.v1.OrderServiceGrpc;
 
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
 
public class ApplicationClient {
    public static void main(String[] args) {
        ManagedChannel managedChannel = ManagedChannelBuilder.forAddress("localhost", 8080)
                                                      .usePlaintext()
                                                      .build();
 
        OrderServiceGrpc.OrderServiceBlockingStub orderServiceBlockingStub
                = OrderServiceGrpc.newBlockingStub(managedChannel);
 
        Order.OrderRequest orderRequest = Order.OrderRequest.newBuilder()
                                             .setEmail("hello@word.com")
                                             .setProduct("no-name")
                                             .setAmount(3)
                                             .build();
 
        Order.OrderResponse orderResponse = orderServiceBlockingStub.executeOrder(orderRequest);
 
        System.out.println("Received response: "+orderResponse.getInfo());
 
        managedChannel.shutdown();
    }
}

所以我們只是自動(dòng)生成了 grpc 代碼,我們用一個(gè)實(shí)現(xiàn)支持了一個(gè) grpc 服務(wù),一個(gè)服務(wù)器啟動(dòng)了,一個(gè)客戶端從服務(wù)器得到了響應(yīng)。

到這里,本篇關(guān)于如何將 grpc 添加到 java 應(yīng)用程序的文章就介紹到此結(jié)束了,感謝各位讀者的閱讀。


0 人點(diǎn)贊