gRPC初探

資源

[1] gRPC Java Example

關(guān)鍵詞

高性能,開源,雙向流式,多開發(fā)語言支持,Apache 2.0

示例

ProtoBuffer定義

protobuf-maven-plugin編譯的默認(rèn)路徑

1566788979168.png
syntax = "proto3";

option java_multiple_files = true;
package com.wjg.grpc.helloworld;

message Person {
  string first_name = 1;
  string last_name = 2;
}

message Greeting {
  string message = 1;
}

service HelloWorldService {
  rpc sayHello (Person) returns (Greeting);
}

使用protobuf-maven-plugin生成stub

源:https://github.com/xolstice/protobuf-maven-plugin

grpc-spring-boot-starter@GRpcService使應(yīng)用內(nèi)嵌一個gRPC server。

os-maven-plugin:生成平臺依賴的工程屬性,ProtocolBuffer編譯器依賴這些信息。即是說,protobuf-maven-plugin需要獲取當(dāng)前平臺使用的正確的編譯器。

sprint-boot-maven-plugin:可以構(gòu)建獨立可運行的jar。

pom.xml

<?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">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.codenotfound</groupId>
  <artifactId>grpc-java-hello-world</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>grpc-java-hello-world</name>
  <description>gRPC Java Example</description>
  <url>https://codenotfound.com/grpc-java-example.html</url>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <grpc-spring-boot-starter.version>3.0.0</grpc-spring-boot-starter.version>
    <os-maven-plugin.version>1.6.1</os-maven-plugin.version>
    <protobuf-maven-plugin.version>0.6.1</protobuf-maven-plugin.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>io.github.lognet</groupId>
      <artifactId>grpc-spring-boot-starter</artifactId>
      <version>${grpc-spring-boot-starter.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <extensions>
      <extension>
        <groupId>kr.motd.maven</groupId>
        <artifactId>os-maven-plugin</artifactId>
        <version>${os-maven-plugin.version}</version>
      </extension>
    </extensions>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.xolstice.maven.plugins</groupId>
        <artifactId>protobuf-maven-plugin</artifactId>
        <version>${protobuf-maven-plugin.version}</version>
        <configuration>
          <protocArtifact>com.google.protobuf:protoc:3.5.1-1:exe:${os.detected.classifier}</protocArtifact>
          <pluginId>grpc-java</pluginId>
          <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.16.1:exe:${os.detected.classifier}</pluginArtifact>
        </configuration>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
              <goal>compile-custom</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

mvn compile生成的類

1566788914309.png

server代碼示例

GRpcService:自動配置gRPC服務(wù)在端口6565上發(fā)布。可以使用grpc.port=xxxx進行修改發(fā)布端口。

package com.wjg.wjggrpcstart.service;


import com.wjg.grpc.helloworld.Greeting;
import com.wjg.grpc.helloworld.HelloWorldServiceGrpc;
import com.wjg.grpc.helloworld.Person;
import io.grpc.stub.StreamObserver;
import org.lognet.springboot.grpc.GRpcService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * created by jingang.wu on 2019/8/26
 */
@GRpcService
public class HelloWorldServiceImpl
        extends HelloWorldServiceGrpc.HelloWorldServiceImplBase {

    private static final Logger LOGGER =
            LoggerFactory.getLogger(HelloWorldServiceImpl.class);

    @Override
    public void sayHello(Person request,
                         StreamObserver<Greeting> responseObserver) {
        LOGGER.info("server received {}", request);

        String message = "Hello " + request.getFirstName() + " "
                + request.getLastName() + "!";
        Greeting greeting =
                Greeting.newBuilder().setMessage(message).build();
        LOGGER.info("server responded {}", greeting);

        // 使用onNext返回greeting,調(diào)用onCompleted告訴gRPC響應(yīng)寫入完成
        responseObserver.onNext(greeting);
        responseObserver.onCompleted();
    }
}

client示例代碼

調(diào)用gRPC服務(wù),首先需要創(chuàng)建一個stub。stub的類型有:

  • 同步stub,阻塞等待server響應(yīng)
  • 異步stub,響應(yīng)異步返回

gRPC使用http/2傳輸消息。MessageChannel管理連接,隱藏了復(fù)雜性。

建立:

一個應(yīng)用使用一個channel,并在service stubs中共享。

package com.wjg.wjggrpcstart.service;

import com.wjg.grpc.helloworld.Greeting;
import com.wjg.grpc.helloworld.HelloWorldServiceGrpc;
import com.wjg.grpc.helloworld.Person;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * created by jingang.wu on 2019/8/26
 */
@Component
public class HelloWorldClient {

    private static final Logger LOGGER =
            LoggerFactory.getLogger(HelloWorldClient.class);

    private HelloWorldServiceGrpc.HelloWorldServiceBlockingStub helloWorldServiceBlockingStub;

    @PostConstruct
    private void init() {
        //gRPC默認(rèn)使用TLS安全連接,需要配置安全組件,這里示例不使用
        ManagedChannel managedChannel = ManagedChannelBuilder
                .forAddress("localhost", 6565).usePlaintext().build();
        
        // 這里使用同步調(diào)用
        helloWorldServiceBlockingStub =
                HelloWorldServiceGrpc.newBlockingStub(managedChannel);
        //異步調(diào)用HelloWorldServiceGrpc.newFutureStub(managedChannel);
    }

    public String sayHello(String firstName, String lastName) {
        Person person = Person.newBuilder().setFirstName(firstName)
                .setLastName(lastName).build();
        LOGGER.info("client sending {}", person);

        Greeting greeting =
                helloWorldServiceBlockingStub.sayHello(person);
        LOGGER.info("client received {}", greeting);

        return greeting.getMessage();
    }
}

unit test

@RunWith(SpringRunner.class)
@SpringBootTest
public class WjgGrpcStartApplicationTests {

    @Test
    public void contextLoads() {
    }

    @Autowired
    private HelloWorldClient helloWorldClient;

    @Test
    public void testSayHello() {
        assert(helloWorldClient.sayHello("John", "Doe").equals("Hello John Doe!"));
    }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • gRPC 是一個高性能、通用的開源RPC框架,基于HTTP/2協(xié)議標(biāo)準(zhǔn)和Protobuf序列化協(xié)議開發(fā),支持眾多的...
    小波同學(xué)閱讀 19,813評論 6 19
  • 1.簡介 在gRPC中,客戶端應(yīng)用程序可以直接調(diào)用不同計算機上的服務(wù)器應(yīng)用程序上的方法,就像它是本地對象一樣,使您...
    第八共同體閱讀 2,075評論 0 6
  • 本文是gRPC的一個簡單例子,以protocol buffers 3作為契約類型,使用gRPC自動生成服務(wù)端和客戶...
    ted005閱讀 5,371評論 0 50
  • 原文連接: 一文了解RPC以及gRPC基于Golang和Java的簡單實現(xiàn) 一:什么是RPC 簡介:RPC:Re...
    賈順閱讀 9,076評論 2 12
  • date: 2019-04-25 22:16:01title: tech| 再探 grpc 折騰 grpc 過幾次...
    daydaygo閱讀 15,324評論 2 17

友情鏈接更多精彩內(nèi)容