mac 本地實現(xiàn)java grpc demo

一、 安裝protobuf插件

  1. IntelliJ IDEA 上操作


    image.png

    image.png
  2. 我的已經安裝,所以出現(xiàn)在了Installed tab下

二略就、代碼相關

  1. 創(chuàng)建maven項目grpc3
  2. 修改pom文件如下
<?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.qf</groupId>
    <artifactId>grpc3</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
    <!-- https://mvnrepository.com/artifact/io.grpc/grpc-stub -->
    <dependency>
        <groupId>io.grpc</groupId>
        <artifactId>grpc-all</artifactId>
        <version>1.20.0</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.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <!--<version>0.5.1</version>-->
                <configuration>
                    <protocArtifact>com.google.protobuf:protoc:3.0.0:exe:${os.detected.classifier}</protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:0.15.0:exe:${os.detected.classifier}</pluginArtifact>
                    <!--<protocExecutable>/Users/sgf/Documents/yang/MyWork/protoc-3.7.1-osx-x86_64/bin/protoc</protocExecutable>-->
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>
</project>
  1. 創(chuàng)建proto文件
    目錄:src/main/proto
    文件名:helloworld.proto
syntax = "proto3";

option java_multiple_files = true;

option java_package = "io.grpc.examples.helloworld";

option java_outer_classname = "HelloWorldProto";

option objc_class_prefix = "HLW";

package helloworld;


// The greeting service definition.

service Greeter {

    // Sends a greeting

    rpc SayHello (HelloRequest) returns (HelloReply) {}

}

// The request message containing the user's name.

message HelloRequest {

    string name = 1;

}

// The response message containing the greetings

message HelloReply {

    string message = 1;

}
  1. 編寫client和server
    目錄:src/main/java/io/grpc/examples/helloworld
    client: src/main/java/io/grpc/examples/helloworld/HelloWorldClient.java
    server: src/main/java/io/grpc/examples/helloworld/HelloWorldServer.java
// HelloWorldClient.java
/*

 * Copyright 2015 The gRPC Authors

 *

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */



package io.grpc.examples.helloworld;



import io.grpc.ManagedChannel;

import io.grpc.ManagedChannelBuilder;

import io.grpc.StatusRuntimeException;

import java.util.concurrent.TimeUnit;

import java.util.logging.Level;

import java.util.logging.Logger;



/**

 * A simple client that requests a greeting from the {@link HelloWorldServer}.

 */

public class HelloWorldClient {

    private static final Logger logger = Logger.getLogger(HelloWorldClient.class.getName());



    private final ManagedChannel channel;

    private final io.grpc.examples.helloworld.GreeterGrpc.GreeterBlockingStub blockingStub;



    /** Construct client connecting to HelloWorld server at {@code host:port}. */

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

                .build());

    }



    /** Construct client for accessing RouteGuide server using the existing channel. */

    HelloWorldClient(ManagedChannel channel) {

        this.channel = channel;

        blockingStub = io.grpc.examples.helloworld.GreeterGrpc.newBlockingStub(channel);

    }



    public void shutdown() throws InterruptedException {

        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);

    }



    /** Say hello to server. */

    public void greet(String name) {

        logger.info("Will try to greet " + name + " ...");

        io.grpc.examples.helloworld.HelloRequest request = io.grpc.examples.helloworld.HelloRequest.newBuilder().setName(name).build();

        io.grpc.examples.helloworld.HelloReply response;

        try {

            response = blockingStub.sayHello(request);

        } catch (StatusRuntimeException e) {

            logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());

            return;

        }

        logger.info("Greeting: " + response.getMessage());

    }



    /**

     * Greet server. If provided, the first element of {@code args} is the name to use in the

     * greeting.

     */

    public static void main(String[] args) throws Exception {

        HelloWorldClient client = new HelloWorldClient("localhost", 50051);

        try {

            /* Access a service running on the local machine on port 50051 */

            String user = "world";

            if (args.length > 0) {

                user = args[0]; /* Use the arg as the name to greet if provided */

            }

            client.greet(user);

        } finally {

            client.shutdown();

        }

    }

}
// HelloWorldServer

/*

 * Copyright 2015 The gRPC Authors

 *

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */



package io.grpc.examples.helloworld;



import io.grpc.BindableService;
import io.grpc.Server;

import io.grpc.ServerBuilder;

import io.grpc.stub.StreamObserver;

import java.io.IOException;

import java.util.logging.Logger;



/**

 * Server that manages startup/shutdown of a {@code Greeter} server.

 */

public class HelloWorldServer {

    private static final Logger logger = Logger.getLogger(HelloWorldServer.class.getName());



    private Server server;



    private void start() throws IOException {

        /* The port on which the server should run */

        int port = 50051;

        server = ServerBuilder.forPort(port)

                .addService((BindableService) new GreeterImpl())

                .build()

                .start();

        logger.info("Server started, listening on " + port);

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

            @Override

            public void run() {

                // Use stderr here since the logger may have been reset by its JVM shutdown hook.

                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();

        }

    }



    /**

     * Await termination on the main thread since the grpc library uses daemon threads.

     */

    private void blockUntilShutdown() throws InterruptedException {

        if (server != null) {

            server.awaitTermination();

        }

    }



    /**

     * Main launches the server from the command line.

     */

    public static void main(String[] args) throws IOException, InterruptedException {

        final HelloWorldServer server = new HelloWorldServer();

        server.start();

        server.blockUntilShutdown();

    }



    static class GreeterImpl extends io.grpc.examples.helloworld.GreeterGrpc.GreeterImplBase {



        @Override

        public void sayHello(io.grpc.examples.helloworld.HelloRequest req, StreamObserver<io.grpc.examples.helloworld.HelloReply> responseObserver) {

            io.grpc.examples.helloworld.HelloReply reply = io.grpc.examples.helloworld.HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();

            responseObserver.onNext(reply);

            responseObserver.onCompleted();

        }

    }

}
  1. 自動生成代碼
    在根目錄下執(zhí)行如下命令
mvn install

安裝成功后在target目錄下生成如下文件


image.png
  1. 啟動server
    運行 HelloWorldServer 中main函數
  2. 運行client
    運行HelloWorldClient main函數發(fā)起請求,看到有響應結果


    image.png

附錄

image.png

全部代碼地址:https://gitee.com/neimenggudaxue/grpc3

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末踢星,一起剝皮案震驚了整個濱河市澳叉,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖成洗,帶你破解...
    沈念sama閱讀 219,188評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件五督,死亡現(xiàn)場離奇詭異,居然都是意外死亡瓶殃,警方通過查閱死者的電腦和手機充包,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,464評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來遥椿,“玉大人基矮,你說我怎么就攤上這事」诔。” “怎么了家浇?”我有些...
    開封第一講書人閱讀 165,562評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長碴裙。 經常有香客問我钢悲,道長,這世上最難降的妖魔是什么舔株? 我笑而不...
    開封第一講書人閱讀 58,893評論 1 295
  • 正文 為了忘掉前任莺琳,我火速辦了婚禮,結果婚禮上载慈,老公的妹妹穿的比我還像新娘惭等。我一直安慰自己,他們只是感情好娃肿,可當我...
    茶點故事閱讀 67,917評論 6 392
  • 文/花漫 我一把揭開白布咕缎。 她就那樣靜靜地躺著,像睡著了一般料扰。 火紅的嫁衣襯著肌膚如雪凭豪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,708評論 1 305
  • 那天晒杈,我揣著相機與錄音嫂伞,去河邊找鬼。 笑死拯钻,一個胖子當著我的面吹牛帖努,可吹牛的內容都是我干的。 我是一名探鬼主播粪般,決...
    沈念sama閱讀 40,430評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼拼余,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了亩歹?” 一聲冷哼從身側響起匙监,我...
    開封第一講書人閱讀 39,342評論 0 276
  • 序言:老撾萬榮一對情侶失蹤凡橱,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后亭姥,有當地人在樹林里發(fā)現(xiàn)了一具尸體稼钩,經...
    沈念sama閱讀 45,801評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,976評論 3 337
  • 正文 我和宋清朗相戀三年达罗,在試婚紗的時候發(fā)現(xiàn)自己被綠了坝撑。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,115評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡粮揉,死狀恐怖巡李,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情滔蝉,我是刑警寧澤击儡,帶...
    沈念sama閱讀 35,804評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站蝠引,受9級特大地震影響阳谍,放射性物質發(fā)生泄漏。R本人自食惡果不足惜螃概,卻給世界環(huán)境...
    茶點故事閱讀 41,458評論 3 331
  • 文/蒙蒙 一矫夯、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧吊洼,春花似錦训貌、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,008評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至综液,卻和暖如春款慨,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背谬莹。 一陣腳步聲響...
    開封第一講書人閱讀 33,135評論 1 272
  • 我被黑心中介騙來泰國打工檩奠, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人附帽。 一個月前我還...
    沈念sama閱讀 48,365評論 3 373
  • 正文 我出身青樓埠戳,卻偏偏與公主長得像,于是被迫代替她去往敵國和親蕉扮。 傳聞我的和親對象是個殘疾皇子整胃,可洞房花燭夜當晚...
    茶點故事閱讀 45,055評論 2 355