java實現(xiàn)gRpc服務端-客戶端框架代碼

參考官方github代碼例子:https://github.com/grpc/grpc-java/tree/master/examples/src/main/java/io/grpc/examples/helloworld

一祭隔、idea安裝protobuf插件

二樟蠕、添加protobuf和grpc的pom依賴包和插件

依賴包

<properties>
    <protobuf.version>3.6.1</protobuf.version>
    <grpc.version>1.19.0</grpc.version>
</properties>

<dependencies>
    <dependency>
        <groupId>com.google.protobuf</groupId>
        <artifactId>protobuf-java</artifactId>
        <version>${protobuf.version}</version>
    </dependency>
    <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>

pom添加protobuf插件

<build>
    <extensions>
        <extension>
            <groupId>kr.motd.maven</groupId>
            <artifactId>os-maven-plugin</artifactId>
            <version>1.5.0.Final</version>
        </extension>
    </extensions>
    <plugins>
        <!--protobuf插件-->
        <plugin>
            <groupId>org.xolstice.maven.plugins</groupId>
            <artifactId>protobuf-maven-plugin</artifactId>
            <version>0.5.0</version>
            <configuration>
                <!--
                  The version of protoc must match protobuf-java. If you don't depend on
                  protobuf-java directly, you will be transitively depending on the
                  protobuf-java version that grpc depends on.
                -->
                <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>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>compile</goal>
                        <goal>compile-custom</goal>
                        <goal>test-compile</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

三俏讹、編寫Proto文件

注:編寫proto文件彩掐,文件的格式可以參考Protobuf語言指南——.proto文件語法詳解里面講的很詳細 https://blog.csdn.net/u014308482/article/details/52958148



.proto文件內(nèi)容如下

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;
}

四柔昼、生成gRpc java代碼

第一種方式:idea中執(zhí)行如下

compile:用于生成protobuf類
compile-custom:生成rpc調(diào)用類垂券,其中會用到compile過程中生成的protobuf類


第二種方式:

linux下執(zhí)行命令:
mvn protobuf:compile
mvn protobuf:compile-custom //生成rpc調(diào)用類

在64位window環(huán)境下使用的命令:
mvn protobuf:compile -Dos.detected.name=windows -Dos.detected.arch=x86_64 -Dos.detected.classifier=windows-x86_64
mvn protobuf:compile-custom -Dos.detected.name=windows -Dos.detected.arch=x86_64 -Dos.detected.classifier=windows-x86_64
其中需要傳入的三個參數(shù):
os.detected.name
os.detected.arch
os.detected.classifier

最終生成如下文件,其中GreeterGrpc是一個很重要的類执虹,直接關(guān)系到我們的服務拓挥,我們自己提供的服務需要繼承它的一個內(nèi)部類,在客戶端中則是可以從中得到一個stub用于調(diào)用(例如:GreeterGrpc.GreeterBlockingStub)袋励。


五侥啤、編寫服務端-客戶端代碼

服務端代碼主要兩件事:
第一件,實現(xiàn)提供的業(yè)務服務茬故,這是本職工作盖灸。
要實現(xiàn)提供的服務,只需要寫一個類繼承GreeterGrpc.GreeterImplBase這個類即可磺芭,然后因為我們定義的方法是SayHello赁炎,那么我們也實現(xiàn)這個方法,值得一提的是钾腺,需要注意一下這個方法的參數(shù)是固定的徙垫,不能隨心所欲地寫讥裤。

第二件,啟動一個grpc服務器姻报,用于接收客戶端的請求己英。
其中主要是start方法用于啟動服務器并接收客戶端的請求。在server中添加名稱解析服務服務實在構(gòu)造方法中進行的逗抑。另外剧辐,blockUntilShutdown方法則會讓server阻塞到程序退出為止。

代碼如下:

private Server server;

private void start() throws IOException {
    /* The port on which the server should run */
    int port = 50051;
    server = ServerBuilder.forPort(port)
            .addService(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");
            try {
                HelloWorldServer.this.stop();
            } catch (InterruptedException e) {
                e.printStackTrace(System.err);
            }
            System.err.println("*** server shut down");
        }
    });
}

private void stop() throws InterruptedException {
    if (server != null) {
        server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
    }
}

/**
 * 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();
}

客戶端代碼參考樣例邮府。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市溉奕,隨后出現(xiàn)的幾起案子褂傀,更是在濱河造成了極大的恐慌,老刑警劉巖加勤,帶你破解...
    沈念sama閱讀 218,451評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件仙辟,死亡現(xiàn)場離奇詭異,居然都是意外死亡鳄梅,警方通過查閱死者的電腦和手機叠国,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,172評論 3 394
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來戴尸,“玉大人粟焊,你說我怎么就攤上這事∷锩桑” “怎么了项棠?”我有些...
    開封第一講書人閱讀 164,782評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長挎峦。 經(jīng)常有香客問我香追,道長,這世上最難降的妖魔是什么坦胶? 我笑而不...
    開封第一講書人閱讀 58,709評論 1 294
  • 正文 為了忘掉前任透典,我火速辦了婚禮,結(jié)果婚禮上顿苇,老公的妹妹穿的比我還像新娘峭咒。我一直安慰自己,他們只是感情好岖圈,可當我...
    茶點故事閱讀 67,733評論 6 392
  • 文/花漫 我一把揭開白布讹语。 她就那樣靜靜地躺著,像睡著了一般蜂科。 火紅的嫁衣襯著肌膚如雪顽决。 梳的紋絲不亂的頭發(fā)上短条,一...
    開封第一講書人閱讀 51,578評論 1 305
  • 那天,我揣著相機與錄音才菠,去河邊找鬼茸时。 笑死,一個胖子當著我的面吹牛赋访,可吹牛的內(nèi)容都是我干的可都。 我是一名探鬼主播,決...
    沈念sama閱讀 40,320評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼蚓耽,長吁一口氣:“原來是場噩夢啊……” “哼渠牲!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起步悠,我...
    開封第一講書人閱讀 39,241評論 0 276
  • 序言:老撾萬榮一對情侶失蹤签杈,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后鼎兽,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體答姥,經(jīng)...
    沈念sama閱讀 45,686評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,878評論 3 336
  • 正文 我和宋清朗相戀三年谚咬,在試婚紗的時候發(fā)現(xiàn)自己被綠了鹦付。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,992評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡择卦,死狀恐怖敲长,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情互捌,我是刑警寧澤潘明,帶...
    沈念sama閱讀 35,715評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站秕噪,受9級特大地震影響钳降,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜腌巾,卻給世界環(huán)境...
    茶點故事閱讀 41,336評論 3 330
  • 文/蒙蒙 一遂填、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧澈蝙,春花似錦吓坚、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,912評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春哆窿,著一層夾襖步出監(jiān)牢的瞬間链烈,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,040評論 1 270
  • 我被黑心中介騙來泰國打工挚躯, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留强衡,地道東北人。 一個月前我還...
    沈念sama閱讀 48,173評論 3 370
  • 正文 我出身青樓码荔,卻偏偏與公主長得像漩勤,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子缩搅,可洞房花燭夜當晚...
    茶點故事閱讀 44,947評論 2 355