GRPC-JAVA

近一年来一直在用公司内wiki进行技术调研以及记录,后期有时间将逐步迁移至博客园

 

参考资料:

https://github.com/grpc/grpc-java

https://www.cnblogs.com/gutousu/p/9951956.html

可以一次性的在一个 .proto 文件中定义服务并使用任何支持它的语言去实现客户端和服务器,反过来,它们可以在各种环境中,从Google的服务器到你自己的平板电脑- gRPC 帮你解决了不同语言间通信的复杂性以及环境的不同.使用 protocol buffers 还能获得其他好处,包括高效的序列号,简单的 IDL 以及容易进行接口更新,无注册中心

 

依赖包

<dependency>
    <groupId>com.google.protobuf</groupId>
    <artifactId>protobuf-java</artifactId>
</dependency>
<dependency>
    <groupId>com.google.protobuf</groupId>
    <artifactId>protobuf-java-util</artifactId>
</dependency>
<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-all</artifactId>
</dependency>

build

<build>
   
    <extensions>
        <extension>
            <!-- provides os.detected.classifier (i.e. linux-x86_64, osx-x86_64) property -->
            <groupId>kr.motd.maven</groupId>
            <artifactId>os-maven-plugin</artifactId>
            <version>1.6.1</version>
        </extension>
    </extensions>

    <plugins>
       
        <plugin>
            <groupId>org.xolstice.maven.plugins</groupId>
            <artifactId>protobuf-maven-plugin</artifactId>
            <configuration>
                <protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}
                </protocArtifact>
                <pluginId>grpc-java</pluginId>
                <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}
                </pluginArtifact>
                <!-- proto文件目录 -->
                <protoSourceRoot>${project.basedir}/src/main/proto</protoSourceRoot>
            </configuration>
            <executions>
                <execution>
                    <id>bean</id>
                    <goals>
                        <goal>compile</goal>
                        <goal>test-compile</goal>
                    </goals>
                    <configuration>
                        <!-- 生成的Java文件目录 -->
                        <outputDirectory>${project.build.directory}/generated-sources/protobuf/java</outputDirectory>
                    </configuration>
                </execution>

                <execution>
                    <id>grpc</id>
                    <goals>
                        <goal>compile-custom</goal>
                        <goal>test-compile-custom</goal>
                    </goals>
                    <configuration>
                        <!-- 生成的grpc-Java文件目录 -->
                        <outputDirectory>${project.build.directory}/generated-sources/protobuf/grpc-java
                        </outputDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

 

proto-demo

syntax = "proto2";

package java_test;

service TestService {
    rpc method (Request) returns (Result) {

    }
}

message Request {
    optional string request1 = 1;
    optional string request2 = 2;
}

message Result {
    optional string result1 = 1;
    optional string result2 = 2;
}

 

编译项目,生成bean文件和通信文件

 

server端demo

package com.baidu.traffic.sc.test;

import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import java_test.TestGrpc;
import java_test.TestServiceGrpc;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Created by liushouyun on 2019-12-20 12:36.
 */

@Component
public class JavaGrpcServer extends TestServiceGrpc.TestServiceImplBase implements InitializingBean {


    @Override
    public void method(TestGrpc.Request request, StreamObserver<TestGrpc.Result> responseObserver) {
        TestGrpc.Result result = TestGrpc.Result.newBuilder().setResult1("结果1").setResult2("结果2不想给你").build();
        responseObserver.onNext(result);
        responseObserver.onCompleted();
        // super.method(request, responseObserver);
    }

    @Override
    public void afterPropertiesSet() throws IOException {
        ServerBuilder.forPort(8582)
                .addService(new JavaGrpcServer())
                .build().start();
    }
}

 client端demo

package com.baidu.traffic.signal.test;

import io.grpc.Channel;
import io.grpc.ManagedChannelBuilder;
import io.swagger.annotations.Api;
import java_test.TestGrpc;
import java_test.TestServiceGrpc;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by liushouyun on 2019-12-20 12:36.
 */

@Api(tags = "grpc-test")
@RestController
@RequestMapping(value = "/test/grpc")
@Slf4j
public class JavaGrpcClient {

    private Channel channel = channel();

    @GetMapping("/run")
    public TestResult run() {
        TestServiceGrpc.TestServiceBlockingStub testServiceBlockingStub = TestServiceGrpc.newBlockingStub(channel);
        TestGrpc.Request request = TestGrpc.Request.newBuilder().setRequest1("ha?").setRequest2("en?").build();
        TestGrpc.Result result = testServiceBlockingStub.method(request);
        return new TestResult(result.getResult1(), result.getResult2());
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    private class TestResult {
        private String result1;
        private String result2;
    }

    private Channel channel() {
        return ManagedChannelBuilder
                .forAddress("127.0.0.1", 8582)
                .usePlaintext()
                .build();
    }
}
posted @ 2020-03-03 16:03  房上的猫  阅读(1751)  评论(0编辑  收藏  举报