0
点赞
收藏
分享

微信扫一扫

java 实现GRPC远程调用(一)

时光已翩然轻擦 2022-02-22 阅读 91
javarpc

gRPC 官方文档中文版_V1.0

grpc的接口调用分为四类

    1.普通调用

    2.请求流调用

    3.响应流调用

    4.双向流调用

从.proto文件开始

常用的关键字

syntax 指定语言版本 option 修改配置选项 service 声明一个服务 rpc 声明一个方法 resturns 方法的返回值 message 定义一个消息类型 repeated 数组 stream 用流来交互

一个例子:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

syntax = "proto3";

option java_package = "java_test";

option java_multiple_files = true;

service TestService

{

    rpc method(Request) returns (Result){}

}

message Request

{

    string request1 = 1;

    string request2 = 2;

}

message Result

{

    string result1 = 1;

    string result2 = 2;

}

jar包

<dependency>

    <groupId>io.grpc</groupId>

    <artifactId>grpc-all</artifactId>

    <version>1.10.1</version>

</dependency>
 

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.example.grpc</groupId>
    <artifactId>grpc-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <grpc.version>1.34.1</grpc.version><!-- CURRENT_GRPC_VERSION -->
        <protobuf.version>3.12.0</protobuf.version>
        <protoc.version>3.12.0</protoc.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencyManagement>
        <dependencies>
        <!--grpc和protobuf依赖库-->
            <dependency>
                <groupId>io.grpc</groupId>
                <artifactId>grpc-bom</artifactId>
                <version>${grpc.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <!-- web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.5.8</version>
        </dependency>
        <!-- 测试类-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>2.5.8</version>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>


        <!--grpc和protobuf依赖-->
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-netty-shaded</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-protobuf</artifactId>
        </dependency>

        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-stub</artifactId>
        </dependency>

        <dependency>
            <groupId>com.google.protobuf</groupId>
            <artifactId>protobuf-java-util</artifactId>
            <version>${protobuf.version}</version>
        </dependency>

    </dependencies>

    <build>
        <extensions>
            <extension>
                <groupId>kr.motd.maven</groupId>
                <artifactId>os-maven-plugin</artifactId>
                <version>1.6.2</version>
            </extension>
        </extensions>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>com.example.grpc.GrpcApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <!--protobuf插件-->
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.6.1</version>
                <configuration>
                    <!--suppress UnresolvedMavenProperty -->
                    <protocArtifact>com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}</protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <!--suppress UnresolvedMavenProperty -->
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
                    <!--proto文件存放的位置,使用protobuf才能找到-->
                    <protoSourceRoot>src/main/resources/proto</protoSourceRoot>
                    <!--通过插件生成的协议代码存放地址-->
                    <outputDirectory>${basedir}/src/main/java</outputDirectory>
                    <!--如果放在src下面,一定要false,不然你的代码都没了,输出放在resources就没关系-->
                    <clearOutputDirectory>false</clearOutputDirectory>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

用maven编译一下

编译一下

生成文件

 

1.普通接口

1.1.服务端

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

package com.gutousu.grpc_service_java_test.service;

import io.grpc.ServerBuilder;

import io.grpc.stub.StreamObserver;

import java_test.Request;

import java_test.Result;

import java_test.TestServiceGrpc;

import org.springframework.beans.factory.InitializingBean;

import org.springframework.stereotype.Component;

@Component

public class JavaGrpcServer extends TestServiceGrpc.TestServiceImplBase implements InitializingBean

{

    @Override

    public void method(Request request, StreamObserver<Result> responseObserver) {

        Result result = Result.newBuilder().setResult1("result1").setResult2("result2").build();

        responseObserver.onNext(result);

        responseObserver.onCompleted();

    }

    @Override

    public void afterPropertiesSet() throws Exception {

        ServerBuilder.forPort(2)

                .addService(new JavaGrpcServer())

                .build()

                .start();

    }

}

这里利用了spring的 InitializingBean 接口和 Component 注解在bean初始化的时候建立服务

好了,服务端搞完了,下一个

1.2.客户端

先写一个叫 Functional 的函数式接口,方便调用

1

2

3

4

5

6

package com.gutousu.grpc_client_java_test;

public interface Functional<Arg,Result>

{

    Result run(Arg arg);

}

  

建一个叫 JavaGrpcClient 的类 来调用接口

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

package com.gutousu.grpc_client_java_test.client;

import com.gutousu.grpc_client_java_test.Functional;

import io.grpc.Channel;

import io.grpc.ManagedChannelBuilder;

import java_test.TestServiceGrpc;

import org.springframework.stereotype.Component;

@Component

public class JavaGrpcClient

{

    private Channel channel = channel();

    public <Result> Result run(Functional<TestServiceGrpc.TestServiceBlockingStub,Result> functional)

    {

        TestServiceGrpc.TestServiceBlockingStub testServiceBlockingStub =

                TestServiceGrpc.newBlockingStub(channel);

        return functional.run(testServiceBlockingStub);

    }

    private Channel channel()

    {

        return ManagedChannelBuilder

                .forAddress("192.168.0.31",2)

                .usePlaintext(true)

                .build();

    }

}

 

举报

相关推荐

0 条评论