1、Intellij IDEA中使用Protobuf的正确姿势

一、.proto文件语法高亮显示

需要安装Protobuf Support插件

依次点击Intellij中的“File”-->"Settings"-->"Plugins"-->"Browse repositories",如下所示:

重启即可。

问题:若还是无法识别,按照下面图片配置。

二、grpc-java实践教程

1、新建一个Maven工程,添加gRPC相关依赖

        <!-- https://mvnrepository.com/artifact/io.grpc/grpc-stub --><dependency><groupId>io.grpc</groupId><artifactId>grpc-all</artifactId><version>1.20.0</version></dependency>

2、在POM文件中添加protocol buffers 编译插件

 <dependencies><dependency><groupId>com.google.protobuf</groupId><artifactId>protobuf-java</artifactId><version>3.10.0</version></dependency><!-- https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java-util --><dependency><groupId>com.google.protobuf</groupId><artifactId>protobuf-java-util</artifactId><version>3.10.0</version></dependency><!-- https://mvnrepository.com/artifact/io.grpc/grpc-all --><dependency><groupId>io.grpc</groupId><artifactId>grpc-all</artifactId><version>1.11.0</version></dependency><!--protobuf相关end--></dependencies>
<!--    //先创建<build></build>在里面创建<extensions></extensions>--><build><extensions><extension><groupId>kr.motd.maven</groupId><artifactId>os-maven-plugin</artifactId><version>1.5.0.Final</version></extension></extensions>
<!--        //之后再创建<plugins></plugins>--><plugins><plugin><groupId>org.xolstice.maven.plugins</groupId><artifactId>protobuf-maven-plugin</artifactId><version>0.6.1</version><configuration><protocArtifact>com.google.protobuf:protoc:3.7.1:exe:${os.detected.classifier}</protocArtifact><pluginId>grpc-java</pluginId><pluginArtifact>io.grpc:protoc-gen-grpc-java:1.9.1:exe:${os.detected.classifier}</pluginArtifact></configuration><executions><execution><goals><goal>compile</goal><goal>compile-custom</goal></goals></execution></executions></plugin></plugins></build>

3 通过下面链接下载对应版本的protoc执行程序

https://github.com/protocolbuffers/protobuf/releases

4 当前项目文件结构

5 编写.proto文件

syntax = "proto3";option java_multiple_files = true;
option java_package = "com.page.awesome.dto.proto";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";//package helloworld;// The greeting service definition.
service Greeter {// Sends a greetingrpc SayHello (HelloRequest) returns (HelloReply) {}// Sends another greetingrpc SayHelloAgain (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;
}

6  现在文件目录如下

7 maven编译

注意:有两种编译方式,详情参考https://blog.csdn.net/qq_29319189/article/details/93539198

这里只选用第二种方式:

用刚才在项目里边添加的插件进行编译。

  • 右击Maven.Projects\protobuf\protobuf:compile ,选择run,生成用于序列化的java文件。
  • 再右击Maven.Projects\protobuf\protobuf:compile-custom,选择run,生成用于rpc的java代码。

8  生成相应代码

9 创建HelloWorldClient和HelloWorldServer

HelloWorldClient

/** 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 com.page.awesome.hello;import com.page.awesome.dto.proto.GreeterGrpc;
import com.page.awesome.dto.proto.HelloReply;
import com.page.awesome.dto.proto.HelloRequest;
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 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 HelloWorld server using the existing channel. */HelloWorldClient(ManagedChannel channel) {this.channel = channel;blockingStub = 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("client request ==============" + name + " ...");HelloRequest request = HelloRequest.newBuilder().setName(name).build();HelloReply response;try {response = blockingStub.sayHello(request);} catch (StatusRuntimeException e) {logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());return;}logger.info("response: ===============" + 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 com.page.awesome.hello;import com.page.awesome.dto.proto.GreeterGrpc;
import com.page.awesome.dto.proto.HelloReply;
import com.page.awesome.dto.proto.HelloRequest;
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(new GreeterImpl()).build().start();logger.info("Server started, listening on " + port);Runtime.getRuntime().addShutdownHook(new Thread() {@Overridepublic 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 GreeterGrpc.GreeterImplBase {@Overridepublic void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {HelloReply reply = HelloReply.newBuilder().setMessage("Hello ++++++++++++++++" + req.getName()).build();responseObserver.onNext(reply);responseObserver.onCompleted();}}
}

10 运行

先运行server,再运行client

报错:

考虑是不是版本的问题,未完待续。

注意:这里报错,但是不影响程序运行。

【gRPC基础知识】快速部署相关推荐

  1. thinkph 上花院 生多行mysql_PHP_ThinkPHP3.1基础知识快速入门,在当今众多的MVC框架中,ThinkPH - phpStudy...

    ThinkPHP3.1基础知识快速入门 在当今众多的MVC框架中,ThinkPHP是一个快速.简单的基于MVC和面向对象的轻量级PHP开发框架,其遵循Apache2开源协议发布,自从诞生以来一直秉承简 ...

  2. 网络基础知识 快速计算子网掩码的2种方法

    网络基础知识 快速计算子网掩码的2种方法<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office ...

  3. 黑客术语基础知识快速了解

    黑客术语基础知识快速了解 1.肉鸡:所谓"肉鸡"是一种很形象的比方,比方那些能够随意被我们操控的电脑,对方可所以WINDOWS体系,也可所以UNIX/LINUX体系,可所以一般的个 ...

  4. 【笔记】——MySQL数据库——基础知识-——快速回顾——(加深印象篇)

    文章目录 前言 一.MySQL是什么? 二.数据库的常见概念 三.数据库存储数据的特点 四.SQL语言的分类 1.)DML 2.)DDL 3.)DCL 五.数据库的基本操作 5.1.)创建数据库 5. ...

  5. 计算机概论--计算机基础知识快速入门

    0.前言 1.计算机:辅助人脑的好工具 1.1计算机硬件的五大单元 1.2CPU的种类 1.3接口设备 1.4运作流程 2.个人计算机架构与接口设备 2.1CPU 2.2内存 2.3显卡 2.4硬盘与 ...

  6. 如何利用深度学习知识--快速部署高速目标检测智能小车?

    点击上方"小白学视觉",选择加"星标"或"置顶" 重磅干货,第一时间送达 3月26日,英伟达图像处理系列公开课第三期线上开播,来自NVIDI ...

  7. JAVA面向对象的基础知识快速通过---自学笔记(一)

    网上的教学很多,看视频非常浪费时间,看文字快点,快速捡起知识点,我只根据我学到的,集各种教学学习,把精华提取出来,把主要概念通俗的展示出来,基本常识就不介绍了,其他的资料谁看了都能看懂,只是java特 ...

  8. JAVA进阶的基础知识快速通过---自学笔记(二)

    温故而知新---陆续学习陆续更新中,你有更好的记忆和学习方法,请在评论区提出来大家一起交流,认真看完,一行行代码备注看完看懂,保证学会,学不会找我. 前言: 代码学完发现很简单,很多初学者搞不明白什么 ...

  9. python基础知识资料-Python基础知识快速学习系列视频课程

    Python 是一种面向对象的解释型计算机程序设计语言,由荷兰人Guido van Rossum于1989年发明,第一个公开发行版发行于1991年. Python是纯粹的自由软件, 源代码和解释器C ...

最新文章

  1. 计算机网页基础课专业,关于《计算机应用基础》课程网页下的学习资源使用说明....
  2. altium designer寻找未连接飞线
  3. http://blog.csdn.net/u011026037/article/list/2
  4. React  学习第一天-2018-07-21
  5. [改善Java代码]若有必要,使用变长数组
  6. windows安装双JDK并实现版本切换
  7. visual studio installer可以卸载吗_技术帖 | 这些宝藏软件你安装了吗?
  8. mysql转txt_MyToTxt-MySQL转Txt工具下载 v3.6 官方版 - 安下载
  9. css改火狐滚动条样式_自定义滚动条,可解决火狐滚动条默认样式修改不了问题...
  10. Android 自定义View 三板斧之三——重写View来实现全新控件
  11. Android编译tcpdump,android 5.0以上使用tcpdump
  12. 手机如何安装java软件_如何在手机上安装JAVA平台
  13. 微信小程序直播插件live-player-plugin使用
  14. sublime text3怎么分屏显示及关闭分屏?
  15. 5. Prometheus概念-Jobs和Instances
  16. 浅谈响应式开发与自适应布局!
  17. 985、211外,你还应该清楚这些高校联盟!
  18. CSS3中steps()动画的详解
  19. .cast( )函数的使用
  20. 洛朗级数与泰勒展开的区别

热门文章

  1. AngularJS获取项目中定义的json文件
  2. 禁止选择文字和文本超出显示省略号
  3. 一个servlet,多个dwr.xml配置文件
  4. MIX08,迎来Silverlight2的新时代
  5. leetcode 646 python
  6. 单源最短路径——Dijkstra代码实现
  7. C语言课后习题(39)
  8. SQL必知必会-约束
  9. 数据库-MySQL-JDBC-execute、executeUpdate、executeQuery
  10. 回顾丨2021数据库大咖讲坛(第6期)视频PPT互动问答