grpc ----実行

grpcの定義については、Baiduが多すぎるため、説明しません。
しかし、私はまだ言わなければなりません:gRPCは高性能でオープンソースのユニバーサルRPC(リモートプロシージャコールプロトコル)フレームワークです

これで、コードは簡単な例になり、公式Webサイトといくつかのブログを模倣しました。
開発ツール:IDEA、mavenビルド
プロジェクト構造、proto、javaこれら2つのフォルダーを空のビューとして

ここに画像の説明を挿入します

1:Mavenファイル構成:
3つの重要なjarパッケージ

<?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.ming</groupId>
    <artifactId>grpc_demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>grpc_demo Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>
    <properties>
        <grpc.version>1.0.3</grpc.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-netty</artifactId>
            <version>${grpc.version}</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-protobuf</artifactId>
            <version>${grpc.version}</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-stub</artifactId>
            <version>${grpc.version}</version>
        </dependency>
    </dependencies>

    <build>
        <extensions>
            <extension>
                <groupId>kr.motd.maven</groupId>
                <artifactId>os-maven-plugin</artifactId>
                <version>1.4.1.Final</version>
            </extension>
        </extensions>
        <plugins>
            <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.5.0</version>
                <configuration>
                    <protocArtifact>com.google.protobuf:protoc:3.1.0:exe:${os.detected.classifier}</protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
                </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>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

2:protoフォルダーにhello.protoを作成します

// 指定格式 
syntax = "proto3";

//一些生成代码的设置
option java_multiple_files = true;
option java_package = "com.ming.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";

package helloworld;

// 定义了一个 service
service Greeter {
    // 发送一个greeting
    rpc SayHello (HelloRequest) returns (HelloReply) {
    }
}

// 定义一个消息请求体
message HelloRequest {
    string name = 1;
}

// 定义一个消息回复体
message HelloReply {
    string message = 1;
}

3:コードを生成する
ここに画像の説明を挿入します

次に、これを見つけます
ここに画像の説明を挿入します

ここで、サーバーとクライアントのコードの記述を開始します。
クライアント:HelloWorldClient.java

import com.ming.helloworld.HelloReply;
import com.ming.helloworld.HelloRequest;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import com.ming.helloworld.GreeterGrpc;

import java.util.Scanner;
import java.util.concurrent.TimeUnit;

/**
 * 客户端
 * @author MING
 * @date 2018/10/28 2:38
 */
public class HelloWorldClient {
    private final ManagedChannel channel; //一个gRPC信道
    private final GreeterGrpc.GreeterBlockingStub blockingStub;//阻塞/同步 存根

    //初始化信道和存根
    public HelloWorldClient(String host,int port){
        this(ManagedChannelBuilder.forAddress(host, port)
                // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
                // needing certificates.
                .usePlaintext(true));
    }

    /** Construct client for accessing RouteGuide server using the existing channel. */
    private HelloWorldClient(ManagedChannelBuilder<?> channelBuilder) {
        channel = channelBuilder.build();
        blockingStub = GreeterGrpc.newBlockingStub(channel);
    }

    public void shutdown() throws InterruptedException {
        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    }

    //客户端方法
    public  void greet(String name){
        HelloRequest request = HelloRequest.newBuilder().setName(name).build();
        HelloReply response;
        try {
            response = blockingStub.sayHello(request);
        } catch (StatusRuntimeException e) {
            System.out.println("RPC调用失败:"+e.getMessage());
            return;
        }
        System.out.println("服务器返回信息:"+response.getMessage());
    }

    public static void main(String[] args) throws InterruptedException {
        HelloWorldClient client = new HelloWorldClient("127.0.0.1",50051);
        try {
            Scanner sc = new Scanner(System.in);
            String next = sc.next();
            client.greet("world:"+next);
        }finally {
            client.shutdown();
        }
    }
}

サーバー:HelloWorldServer.java

import com.ming.helloworld.GreeterGrpc;
import com.ming.helloworld.HelloReply;
import com.ming.helloworld.HelloRequest;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;

import java.io.IOException;

/**
 * 服务端
 * @author MING
 * @date 2018/10/28 2:36
 */
public class HelloWorldServer {
    private int port = 50051;
    private Server server;

    /**
     * 启动服务
     * @throws IOException
     */
    private void start() throws IOException {
        server = ServerBuilder.forPort(port)
                .addService(new GreeterImpl())
                .build()
                .start();

        System.out.println("service start...");

        Runtime.getRuntime().addShutdownHook(new Thread() {

            @Override
            public void run() {
                System.err.println("*** shutting down gRPC server since JVM is shutting down");
                HelloWorldServer.this.stop();
                System.err.println("*** server shut down");
            }
        });
    }

    private void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    // block 一直到退出程序
    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }


    public static void main(String[] args) throws IOException, InterruptedException {
        final HelloWorldServer server = new HelloWorldServer();
        server.start();
        server.blockUntilShutdown();
    }


    // 实现 定义一个实现服务接口的类
    private class GreeterImpl extends GreeterGrpc.GreeterImplBase {

        public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
            //获取参数
            System.out.println("收到的信息:"+req.getName());

            //这里可以放置具体业务处理代码 start

            //这里可以放置具体业务处理代码 end

            //构造返回
            HelloReply reply = HelloReply.newBuilder().setMessage(("Hello: " + req.getName())).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }
}

最終的なプロジェクト構造:
ここに画像の説明を挿入します

次に、実行して効果を確認します。最初にサーバーを実行します
ここに画像の説明を挿入します

IDEAはprotoをサポートするプラグインをダウンロードする必要があります
ここに画像の説明を挿入します

一般的に言って、それほど難しいことではありませんが、この小さなデモが正常に実行された理由に基づいて、問題が見つかりますか?
https://www.jianshu.com/p/46d600e5a1b1この記事に詳細な手順があります

転載元:https//www.jianshu.com/p/46d600e5a1b1

おすすめ

転載: blog.csdn.net/qq_38637558/article/details/83480385