Java使用gRPC调用完全指南:从入门到实战

gRPC说明及使用(java版) 一元 RPC,其中客户端向服务器发送单个请求并得到单个响应,就像普通函数调用一样。服务器流式 RPC 中,客户端向服务器发送请求并获取流以读取一系列消息。客户端从返回的流中读取,直到没有更多消息。gRPC 保证单个RPC 调用中的消息排序。客户端流式 RPC,客户端使用提供的流编写一系列消息并将其发送到服务器。客户端完成编写消息后,它会等待服务器读取消息并返回响应。同样,gRPC 保证了单个 RPC 调用中的消息排序。双向流式RPC,双方使用读写流发送一系列消息。 阅读详情
AI摘要

本文以Java为例,详细介绍gRPC调用。先阐述gRPC核心优势与适用场景,接着说明Java项目集成gRPC的环境准备,包括工具、依赖配置等。还讲解了.proto文件编写、Java代码生成、服务端与客户端实现、测试验证,最后给出常见问题解决方案及最佳实践,提升微服务通信效率。

在微服务架构盛行的今天,服务间通信是核心问题之一。传统的RESTful API基于HTTP/1.1,存在​​冗余头信息​​、​​队头阻塞​​等问题,难以满足高并发、低延迟的需求。而gRPC凭借​​HTTP/2协议​​、​​Protobuf序列化​​和​​多语言支持​​,成为微服务间通信的首选方案。本文将以Java为例,手把手教你实现gRPC调用,从环境搭建到完整实战,一站式解决你的疑惑。

一、gRPC核心优势:为什么选择它?

在开始实战前,先明确gRPC的核心价值,帮你判断是否适合你的项目:

特性 说明
​​高性能​​ 基于HTTP/2(多路复用、二进制帧),传输效率比HTTP/1.1高3-5倍
​​强类型契约​​ 使用Protobuf(.proto文件)定义服务接口,自动生成多语言代码
​​多语言支持​​ 支持Java、Go、Python等50+语言,天然适配微服务跨语言场景
​​流式通信​​ 支持单向流、双向流,适合实时数据传输(如聊天、日志推送)
​​内置认证与压缩​​ 支持TLS加密、JWT认证,内置Gzip/Protobuf压缩,减少网络传输量

​​适用场景​​:微服务内部通信、高并发低延迟API、实时数据传输(如物联网、金融行情)。


二、环境准备:Java项目集成gRPC

1. 工具与依赖

  • ​​JDK 8+​​(推荐JDK 11+,gRPC 1.42+支持)
  • ​​Maven/Gradle​​:管理依赖
  • ​​Protobuf插件​​:编译.proto文件生成Java代码
  • ​​gRPC Java库​​:核心依赖

2. Maven依赖配置

在pom.xml中添加gRPC相关依赖(以gRPC 1.59.0为例):

<!-- gRPC核心库 -->
<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-netty-shaded</artifactId>
    <version>1.59.0</version>
</dependency>
<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-protobuf</artifactId>
    <version>1.59.0</version>
</dependency>
<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-stub</artifactId>
    <version>1.59.0</version>
</dependency>

<!-- Protobuf运行时 -->
<dependency>
    <groupId>com.google.protobuf</groupId>
    <artifactId>protobuf-java</artifactId>
    <version>3.24.1</version>
</dependency>

<!-- Spring Boot集成(可选) -->
<dependency>
    <groupId>net.devh</groupId>
    <artifactId>grpc-spring-boot-starter</artifactId>
    <version>2.15.0.RELEASE</version>
</dependency>

3. 安装Protobuf插件(IDEA)

为了在IDE中方便编写和编译.proto文件,需安装Protobuf插件:

  1. 打开IDEA → File → Settings → Plugins → 搜索Protobuf Support → 安装并重启。
  2. 配置Protobuf编译路径:Settings → Languages & Frameworks → Protocol Buffers → 设置Protobuf Compiler路径(可选,Maven会自动编译)。

三、定义服务:编写.proto文件

.proto

gRPC之gRPC开发流程与入门案例 阅读详情

相关推荐

java版gRPC实战之三:服务端流

本文是《java版gRPC实战》系列的第三篇,前文咱们实战体验了简单的RPC请求和响应,那种简单的请求响应方式其实只是gRPC定义的四种类型之一,这里给出《gRPC 官方文档中文版》对这四种gRPC类型的描述:简单 RPC:客户端使用存根(stub)发送请求到服务器并等待响应返回,就像平常的函数调用一样;服务器端流式 RPC:客户端发送请求到服务器,拿到一个流去读取返回的消息序列。客户端读取返回的流,直到里面没有任何消息;(即本篇内容)

2401_84003554的博客 1125

java实现grpc实例(附完整源码)

java实现grpc实例(附完整源码)

希望我的博客,能帮上你解决学习中工作中所遇到的问题 1230

计算机组成原理实验:手把手教你用模拟程序实现中断机制(附完整代码)

本文通过一个计算机组成原理模拟实验,手把手教你从零实现一个可工作的中断系统。实验详细演示了如何配置中断控制器、编写主程序与中断服务程序,并观察中断响应、现场保护和恢复的全过程,深入解析了中断原理的核心机制。

471

2025.06.25【微生物】|Emu工具安装与使用详解:全长16S扩增子微生物丰度分析

Emu是一款基于贝叶斯方法的微生物多样性分析工具,专为处理高错误率的长读长16S/18S扩增子数据优化。本文详细介绍了Emu的安装与使用方法:1)通过conda创建独立环境并安装Emu;2)提供SILVA等预构建数据库的下载指南,并说明自定义数据库的构建方法;3)演示单样本和多样本分析流程,解读关键输出文件;4)介绍丰度表合并、分类等级汇总等实用功能扩展;5)建议后续分析方向。文章还附有官方GitHub链接和相关文献资源,为微生物群落结构研究提供了一套完整的分析解决方案。

1256

python-snap7 报错:can‘t find snap7 library. If installed, try running ldconfig

1、使用场景: Python 读取西门子 S7 系列 PLC 信息,会用到 snap7 库,网上也有很多案例。但是,运行时会报错:can't find snap7 library. If installed, try running ldconfig 2、解决方案: A、下载项目需要依赖的 dll、lib 文件: i、Sourceforge下载:https://sourceforge.net/projects/snap7/files/ ii、优快云下载(免费):https://dow.

蜡笔小新历险记的博客 3650

字节开源 DeerFlow 2.0:从 Deep Research 到 Super Agent Harness 的进化之路

GitHub Trending 冠军项目,字节跳动完全开源的超级智能体框架。支持子代理、沙箱执行、长期记忆、技能扩展,可完成从几分钟到几小时的复杂任务。本文深度解析架构设计、安装实战、技能系统,并附上独家配置指南。

qq_38610923的博客 1712

【数据湖仓】:Iceberg、Hudi 和 Paimon 对比

适用于需要多计算引擎支持和复杂查询的离线批处理场景。其中立性和灵活性使其成为构建新型数据平台的理想选择。:在需要高频数据更新和高效小文件管理的场景中表现出色,适合实时数据处理和增量数据更新的业务需求。:专为实时流式数据处理设计,适用于对数据实时性要求高的业务场景,如实时数据分析和实时指标监控。通过以上分析,可以看出 Apache Iceberg、Apache Hudi 和 Apache Paimon 各有其独特的优势和适用场景。企业应根据自身业务需求和技术栈选择合适的数据湖仓方案,以充分发挥其价值。

欢迎来到我的博客,一起探索代码里的世界! 1610

【扣子AI开发】如何开发一个图像生成智能体?

【扣子AI开发】如何开发一个图像生成智能体,从创建到发布

tl437002770的博客 2427

ComfyUI整合包V8中文版最新版介绍

和普通AI绘图网页不同,它把图像生成的每一个步骤拆分成一个个"节点",用连线把它们串起来,形成工作流。里面包含ComfyUI内核、Python运行环境、常用插件、部分预置模型,还有一个叫"绘世启动器"的图形界面管理工具。网上的对比数据显示,WebUI最低需要4G显存,ComfyUI最低3G显存就能运行。可以在里面管理插件、切换模型路径、设置显存模式、查看日志报错,还有"疑难解答"功能,遇到报错可以先扫描一下看是不是已知问题。原版ComfyUI的界面是英文的,右键菜单、节点名称全是英文。

欢迎来到鸾姝淡月博客,专为程序员和编程爱好者打造的技术博客。我们分享编程语言趋势、开发工具、编程哲学、职业发展等,助你掌握新技术,优化技能,激发编程热情。 5228

【29】软考软件设计师——SQL语句编写与优化深度精讲|数据库大题延伸满分攻略

本文是《软件设计师·50讲通关|从零基础到工程师职称》专栏第29篇,承接第28篇ER图转关系模式核心内容,作为**下午第2题数据库大题核心延伸必考模块**,单模块累计占分5~8分,是数据库板块性价比极高的提分重点。全文超4000字深度拆解软考全部SQL高频考点:全覆盖多表连接底层逻辑、嵌套子查询分类实操、GROUP BY分组聚合硬核规则、索引全品类设计原理、联合索引最左匹配底层机制,搭配海量可直接复刻的考场SQL模板、历年真题完整改写案例、索引失效场景实操复盘、慢查询优化落地技巧。

专注于人工智能、软件开发、工控自动化、工厂数字化及智能化等领域,希望和大家共同进步! 526

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

上一篇: Java接口请求耗时优化深度解析:从网络到JVM的全链路调优指南
下一篇: HTTP与HTTPS深度解析:从明文传输到安全通信的演进之路
码里看花‌
博客等级 码龄8年 321粉丝 68原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码里看花‌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值