初识 Protobuf 和 gRpc

初步了解 Protobuf 和 gRpc

Protocol Buffers

Protocol Buffers(又称protobuf)是谷歌的语言无关、平台无关、可扩展的机制,用于序列化结构化数据。您可以在protobuf的文档中了解更多关于它的信息。

ProtoBuf 的定义

ProtoBuf是将类的定义使用.protobuf文件进行描述。

//语言版本
syntax = "proto3";
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
package helloworld;//数据体User 属性username
message User{string username = 1;
}

通过protoc可以将.proto文件编译成需要的语言文件。本文以java语言示例。

protoc --proto_path=src --java_out=build/gen src/foo.proto

详细用法可以查看protoc的使用。

gRpc

在 gRPC 中,客户端应用程序可以像本地对象一样直接调用不同机器上的服务器应用程序上的方法,从而使您可以更轻松地创建分布式应用程序和服务。与许多 RPC 系统一样,gRPC 基于定义服务的思想,指定可以远程调用的方法及其参数和返回类型。在服务器端,服务器实现这个接口并运行一个gRPC服务器来处理客户端调用。在客户端,客户端有一个存根(在某些语言中简称为客户端),它提供与服务器相同的方法。(类似Android AIDL使用方式)。
gRPC 客户端和服务器可以在各种环境中运行并相互通信(从 Google 内部的服务器到您自己的桌面),并且可以用 gRPC 支持的任何语言编写。例如,您可以使用 Java 轻松创建 gRPC 服务器,并使用 Go、Python 或 Ruby 编写客户端。
默认情况下,gRPC 使用Protocol Buffers,Google 成熟的开源机制,用于序列化结构化数据(尽管它可以与 JSON 等其他数据格式一起使用)。
【以上来自grpc简介】

Grpc 的定义

grpc 也定义在.proto文件,如下:

// The greeting service definition.
service Greeter {// Sends a greetingrpc SayHello (HelloRequest) returns (HelloReply) {}
}// The request message containing the  name and user.
message HelloRequest {string name = 1;User user = 2;
}// The response message containing the greetings
message HelloReply {string message = 1;
}

grpc 的编译仍然需要编译.proto文件。所以离不开protoc, 还需要另外的插件配合编译。例如:

protoc --plugin=protoc-gen-grpc-java \--grpc-java_out="$OUTPUT_FILE" --proto_path="$DIR_OF_PROTO_FILE" "$PROTO_FILE"

Protobuf 插件

使用命令行对于大部分人来说是比较不方便的,我们也可以使用Gradle插件来完成.proto的编译。下面分享一下完整的build.gradle文件。

plugins {// Provide convenience executables for trying out the examples.id 'application'id 'com.google.protobuf' version '0.9.4'// Generate IntelliJ IDEA's .idea & .iml project filesid 'idea'
}repositories {maven { // The google mirror is less flaky than mavenCentral()url "https://maven-central.storage-download.googleapis.com/maven2/"}mavenCentral()mavenLocal()
}java {sourceCompatibility = JavaVersion.VERSION_1_8targetCompatibility = JavaVersion.VERSION_1_8
}// IMPORTANT: You probably want the non-SNAPSHOT version of gRPC. Make sure you
// are looking at a tagged version of the example and not "master"!// Feel free to delete the comment at the next line. It is just for safely
// updating the version in our release process.
def grpcVersion = '1.61.0' // CURRENT_GRPC_VERSION
def protobufVersion = '3.25.1'
def protocVersion = protobufVersion
//https://github.com/protocolbuffers/protobuf
//https://github.com/grpc/grpc-java
dependencies {implementation "io.grpc:grpc-protobuf:${grpcVersion}"implementation "io.grpc:grpc-services:${grpcVersion}"implementation "io.grpc:grpc-stub:${grpcVersion}"compileOnly "org.apache.tomcat:annotations-api:6.0.53"// examples/advanced need this for JsonFormatimplementation "com.google.protobuf:protobuf-java-util:${protobufVersion}"runtimeOnly "io.grpc:grpc-netty-shaded:${grpcVersion}"testImplementation "io.grpc:grpc-testing:${grpcVersion}"testImplementation "io.grpc:grpc-inprocess:${grpcVersion}"testImplementation "junit:junit:4.13.2"testImplementation "org.mockito:mockito-core:4.4.0"
}
//https://github.com/google/protobuf-gradle-plugin
protobuf {protoc { artifact = "com.google.protobuf:protoc:${protocVersion}" }plugins {grpc { artifact = "io.grpc:protoc-gen-grpc-java:${grpcVersion}" }}generateProtoTasks {all()*.plugins { grpc {} }}
}// Inform IDEs like IntelliJ IDEA, Eclipse or NetBeans about the generated code.
sourceSets {main {java {srcDirs 'build/generated/source/proto/main/grpc'srcDirs 'build/generated/source/proto/main/java'}}
}

通过build项目或者执行generateProto的task就可以生成java文件。
上面的.proto文件生成目录如下:

在这里插入图片描述
下面提供java中的使用,所有代码只有server和client两个文件。如下:

/** 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.Grpc;
import io.grpc.InsecureServerCredentials;
import io.grpc.Server;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
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 = Grpc.newServerBuilderForPort(port, InsecureServerCredentials.create()).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");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();}static class GreeterImpl extends GreeterGrpc.GreeterImplBase {@Overridepublic void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {System.out.println("sayHello:"+req.getUser().getUsername()+req.getName());HelloReply reply = HelloReply.newBuilder().setMessage("Hello " +req.getUser().getUsername()+req.getName()).build();responseObserver.onNext(reply);responseObserver.onCompleted();}}
}
/** 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.Channel;
import io.grpc.Grpc;
import io.grpc.InsecureChannelCredentials;
import io.grpc.ManagedChannel;
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 GreeterGrpc.GreeterBlockingStub blockingStub;/*** Construct client for accessing HelloWorld server using the existing channel.*/public HelloWorldClient(Channel channel) {// 'channel' here is a Channel, not a ManagedChannel, so it is not this code's responsibility to// shut it down.// Passing Channels to code makes code easier to test and makes it easier to reuse Channels.blockingStub = GreeterGrpc.newBlockingStub(channel);}/*** Say hello to server.*/public void greet(String name) {logger.info("Will try to greet " + name + " ...");HelloRequest request = HelloRequest.newBuilder().setName(name).setUser(User.newBuilder().setUsername("test ").build()).build();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. The second argument is the target server.*/public static void main(String[] args) throws Exception {String user = "world";// Access a service running on the local machine on port 50051String target = "localhost:50051";// Allow passing in the user and target strings as command line argumentsif (args.length > 0) {if ("--help".equals(args[0])) {System.err.println("Usage: [name [target]]");System.err.println("");System.err.println("  name    The name you wish to be greeted by. Defaults to " + user);System.err.println("  target  The server to connect to. Defaults to " + target);System.exit(1);}user = args[0];}if (args.length > 1) {target = args[1];}// Create a communication channel to the server, known as a Channel. Channels are thread-safe// and reusable. It is common to create channels at the beginning of your application and reuse// them until the application shuts down.//// For the example we use plaintext insecure credentials to avoid needing TLS certificates. To// use TLS, use TlsChannelCredentials instead.ManagedChannel channel = Grpc.newChannelBuilder(target, InsecureChannelCredentials.create()).build();try {HelloWorldClient client = new HelloWorldClient(channel);client.greet(user);} finally {// ManagedChannels use resources like threads and TCP connections. To prevent leaking these// resources the channel should be shut down when it will no longer be used. If it may be used// again leave it running.channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/673846.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

PostgreSql与Postgis安装

POstgresql安装 1.登录官网 PostgreSQL: Linux downloads (Red Hat family) 2.选择版本 3.安装 ### 源 yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm ### 客户端 yum install postgresql14 ###…

Python使用zdppy_es国产框架操作Elasticsearch实现增删改查

Python使用zdppy_es国产框架操作Elasticsearch实现增删改查 本套教程配套有录播课程和私教课程&#xff0c;欢迎私信我。 Docker部署ElasticSearch7 创建基本容器 docker run -itd --name elasticsearch -p 9200:9200 -e "discovery.typesingle-node" -e ES_JAVA_…

Docker的镜像和容器的区别

1 Docker镜像 假设Linux内核是第0层&#xff0c;那么无论怎么运行Docker&#xff0c;它都是运行于内核层之上的。这个Docker镜像&#xff0c;是一个只读的镜像&#xff0c;位于第1层&#xff0c;它不能被修改或不能保存状态。 一个Docker镜像可以构建于另一个Docker镜像之上&…

P2957

题目描述 The cows enjoy mooing at the barn because their moos echo back, although sometimes not completely. Bessie, ever the excellent secretary, has been recording the exact wording of the moo as it goes out and returns. She is curious as to just how mu…

numa网卡绑定

#概念 参考&#xff1a;https://www.jianshu.com/p/0f3b39a125eb(opens new window) chip&#xff1a;芯片&#xff0c;一个cpu芯片上可以包含多个cpu core&#xff0c;比如四核&#xff0c;表示一个chip里4个core。 socket&#xff1a;芯片插槽&#xff0c;颗&#xff0c;跟…

Sping Cloud Hystrix 参数配置、简单使用、DashBoard

Sping Cloud Hystrix 文章目录 Sping Cloud Hystrix一、Hystrix 服务降级二、Hystrix使用示例三、OpenFeign Hystrix四、Hystrix参数HystrixCommand.Setter核心参数Command PropertiesFallback降级配置Circuit Breaker 熔断器配置Metrix 健康统计配置Request Context 相关参数C…

Docker容器监控-CIG

目录 一、CIG说明 1. CAdvisor 2. InfluxDB 3. Grafana 二、环境搭建 1. 创建目录 2. 编写 docker-compose.yml 3. 检查并运行容器 三、进行测试 1. 查看 influxdb 存储服务 是否能正常访问 2. 查看 cAdvisor 收集服务能否正常访问 3. 查看 grafana 展现服务&#…

金融行业专题|证券超融合架构转型与场景探索合集(2023版)

更新内容 更新 SmartX 超融合在证券行业的覆盖范围、部署规模与应用场景。新增操作系统信创转型、Nutanix 国产化替代、网络与安全等场景实践。更多超融合金融核心生产业务场景实践&#xff0c;欢迎阅读文末电子书。 在金融行业如火如荼的数字化转型大潮中&#xff0c;传统架…

路由器如何映射端口映射?

在现代互联网中&#xff0c;随着网络应用的不断发展&#xff0c;很多用户需要进行远程访问或搭建服务器来满足自己的需求。由于网络安全的原因&#xff0c;直接将内网设备暴露在公网中是非常危险的。为了解决这个问题&#xff0c;路由器映射端口映射技术应运而生。本文将介绍什…

鸿蒙(HarmonyOS)项目方舟框架(ArkUI)之Span组件

鸿蒙&#xff08;HarmonyOS&#xff09;项目方舟框架&#xff08;ArkUI&#xff09;之Span组件 一、操作环境 操作系统: Windows 10 专业版、IDE:DevEco Studio 3.1、SDK:HarmonyOS 3.1 二、Span组件 鸿蒙&#xff08;HarmonyOS&#xff09;作为Text组件的子组件&#xff0…

【开源】JAVA+Vue+SpringBoot实现公司货物订单管理系统

目录 一、摘要1.1 项目介绍1.2 项目录屏 二、功能模块2.1 客户管理模块2.2 商品维护模块2.3 供应商管理模块2.4 订单管理模块 三、系统展示四、核心代码4.1 查询供应商信息4.2 新增商品信息4.3 查询客户信息4.4 新增订单信息4.5 添加跟进子订单 五、免责说明 一、摘要 1.1 项目…

微信小程序新手入门教程四:样式设计

WXSS (WeiXin Style Sheets)是一套样式语言&#xff0c;用于描述 WXML 的组件样式&#xff0c;决定了 WXML 的组件会怎么显示。 WXSS 具有 CSS 大部分特性&#xff0c;同时为了更适合开发微信小程序&#xff0c;WXSS 对 CSS 进行了扩充以及修改。与 CSS 相比&#xff0c;WXSS …

Tkinter教程21:Listbox列表框+OptionMenu选项菜单+Combobox下拉列表框控件的使用+绑定事件

------------★Tkinter系列教程★------------ Tkinter教程21&#xff1a;Listbox列表框OptionMenu选项菜单Combobox下拉列表框控件的使用绑定事件 Tkinter教程20&#xff1a;treeview树视图组件&#xff0c;表格数据的插入与表头排序 Python教程57&#xff1a;tkinter中如何…

Flink Format系列(2)-CSV

Flink的csv格式支持读和写csv格式的数据&#xff0c;只需要指定 format csv&#xff0c;下面以kafka为例。 CREATE TABLE user_behavior (user_id BIGINT,item_id BIGINT,category_id BIGINT,behavior STRING,ts TIMESTAMP(3) ) WITH (connector kafka,topic user_behavior…

GPT4_VS_ChatGPT(from_nytimes)

GPT4 VS ChatGPT&#xff08;from nytimes &#xff09; 正如文章官网博文&#xff1a;https://openai.com/research/gpt-4所述&#xff0c;GPT4仍有很多不足之处&#xff0c;还不及人类水平。纽约时报报道了一些人体验GPT4的效果和一些评价&#xff1a; Cade Metz 要求专家使…

什么是制动电阻器?工作及其应用

电梯、风力涡轮机、起重机、升降机和电力机车的速度控制是非常必要的。因此&#xff0c;制动电阻器是这些应用不可或缺的一部分&#xff0c;因为它们是电动机驱动器中最常用的高功率电阻器&#xff0c;用于控制其速度&#xff0c;在运输、海事和建筑等行业中。 电动火车主要比柴…

navigator.mediaDevices.getUserMedia获取本地音频/麦克权限并提示用户

navigator.mediaDevices.getUserMedia获取本地音频/麦克权限并提示用户 效果获取权限NotFoundErrorNotAllowedError 代码 效果 获取权限 NotFoundError NotAllowedError 代码 // 调用 captureLocalMedia()// 方法 function captureLocalMedia() {console.warn(Requesting lo…

redis特点

一、redis线程模型有哪些&#xff0c;单线程为什么快&#xff1f; 1、IO模型维度的特征 IO模型使用了多路复用器&#xff0c;在linux系统中使用的是EPOLL 类似netty的BOSS,WORKER使用一个EventLoopGroup(threads1) 单线程的Reactor模型&#xff0c;每次循环取socket中的命令…

oracle 启动命令以及ORA-01033问题处理、删除归档日志

1 启动数据库:startup 2 关闭数据库&#xff1a;Shutdown immediate 3 查看监听状态&#xff1a;lsnrctl status 4 启动监听&#xff1a;lsnrctl start 5 停止监听&#xff1a;lsnrctl stop 常见问题 1、在服务器重启后会出现&#xff0c;Oracle ORA-01033: ORAC…

Java线程是怎么实现run方法的执行的呢?【 多线程在JVM中的实现原理剖析】

Java线程是怎么实现run方法的执行的呢&#xff1f;【 多线程在JVM中的实现原理剖析】 查看naive state0 方法JVM_StartThread 方法创建操作系统线程操作系统线程执行 本文转载-极客时间 我们知道Java线程是通过行start()方法来启动的&#xff0c;线程启动后会执行run方法内的代…