溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時(shí)間:2022-02-28 11:04:01 來源:億速云 閱讀:170 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要為大家展示了“如何將Grpc添加到您的Java應(yīng)用程序”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“如何將Grpc添加到您的Java應(yīng)用程序”這篇文章吧。

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

使用 gRPC 有多種好處:

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

  • 它支持多種語言

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

請(qǐng)注意:將 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ù)器并為請(qǐng)求提供服務(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 請(qǐng)求:

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)。

以上是“如何將Grpc添加到您的Java應(yīng)用程序”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI