GRPC入门及Server Client示范
GRPC
GRPC是谷歌google出的一款RPC框架,RPC是远程过程调用remote procedure call,就是像调用本地方法一样调用远程机器上的方法
提供被调用的方法写在xxx.proto文件中,然后我们利用maven的compile编译生成代码,然后将定义的那些方法实现即可。绑定端口启动服务器即可提供这些方法被需要的人调用。
调用者使用stub来调用这些方法,返回结果。
- demo项目结构
-
Test.proto文件
syntax = "proto3"; option java_multiple_files = true; option java_package = "com.example.grpc_java_demo"; option java_outer_classname = "Test"; option objc_class_prefix = "xlf"; package test; //定义服务 service TestService { //注意:这里是returns 不是return rpc SayHello(Request) returns (Response){ } } //定义参数类型 message Request { string message=1; } message Response { string message=1; }
-
服务提供端类
package com.example.grpc_java_demo.server; import com.example.grpc_java_demo.*; import com.google.protobuf.Descriptors; import io.grpc.Server; import io.grpc.ServerBuilder; import io.grpc.stub.StreamObserver; import java.io.IOException; import java.util.Map; /** * 服务端 */ public class TestServer { //定义端口 private final int port = 50051; //服务 private Server server; //启动服务,并且接受请求 private void start() throws IOException { server = ServerBuilder.forPort(port).addService(new TestImpl()).build().start(); System.out.println("服务开始启动-------"); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.err.println("------shutting down gRPC server since JVM is shutting down-------"); System.err.println("调用者断开连接"); TestServer.this.stop(); System.err.println("------server shut down------"); } }); } //stop服务 private void stop() { if (server != null) { server.shutdown(); } } //server阻塞到程序退出 private void blockUntilShutdown() throws InterruptedException { if (server!=null){ server.awaitTermination(); } } //实现服务接口的类 private class TestImpl extends TestServiceGrpc.TestServiceImplBase { @Override public void sayHello(Request request, StreamObserver<Response> responseObserver) { String msg=request.getMessage()+"我是服务器"; System.err.println("收到请求:"+request.getMessage()+" 回复:"+msg); Response build = Response.newBuilder().setMessage(msg).build(); //onNext()方法向客户端返回结果 responseObserver.onNext(build); //告诉客户端这次调用已经完成 responseObserver.onCompleted(); } } public static void main(String[] args) throws IOException, InterruptedException { final TestServer server=new TestServer(); server.start(); server.blockUntilShutdown(); } }
-
调用端client
构建所需参数,调用stub里的方法即可完成。
package com.example.grpc_java_demo.client; import com.example.grpc_java_demo.*; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import java.util.concurrent.TimeUnit; /** * 客户端 */ public class TestClient { private final ManagedChannel channel; private final TestServiceGrpc.TestServiceBlockingStub blockingStub; private static final String host="127.0.0.1"; private static final int ip=50051; public TestClient(String host,int port){ //usePlaintext表示明文传输,否则需要配置ssl //channel 表示通信通道 channel= ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build(); //存根 blockingStub=TestServiceGrpc.newBlockingStub(channel); } public void shutdown() throws InterruptedException { channel.shutdown().awaitTermination(5, TimeUnit.SECONDS); } public void sayHello(){ String msg="你好"; System.err.println("发送:"+msg); Request request=Request.newBuilder().setMessage(msg).build(); Response response=blockingStub.sayHello(request); System.err.println("收到回复:"+response.getMessage()); } public static void main(String[] args) throws InterruptedException { TestClient client=new TestClient(host,ip); client.sayHello(); client.shutdown(); } }
服务器收到的请求参数:
调用者收到的回复
本文来自博客园,作者:HumorChen99,转载请注明原文链接:https://www.cnblogs.com/HumorChen/p/18039677
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~