当前位置: 首页 > news >正文

grpc接口调用

grpc接口调用

  • 准备
  • 依赖包
    • client
    • server

参考博客:
Grpc项目集成到java方式调用实践
gRpc入门和springboot整合
java 中使用grpc java调用grpc服务

准备

因为需要生成代码,所以必备插件
在这里插入图片描述
安装后重启

依赖包

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>mistra</artifactId><version>1.0-SNAPSHOT</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.10</version><relativePath/></parent><properties><maven.compiler.source>11</maven.compiler.source><maven.compiler.target>11</maven.compiler.target><protoc.version>3.25.2</protoc.version><grpc.version>1.61.1</grpc.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>io.grpc</groupId><artifactId>grpc-stub</artifactId><version>${grpc.version}</version></dependency><dependency><groupId>io.grpc</groupId><artifactId>grpc-core</artifactId><version>${grpc.version}</version></dependency><dependency><groupId>com.google.protobuf</groupId><artifactId>protobuf-java</artifactId><version>3.25.2</version> <!-- 或者与你的 protoc.version 相匹配的版本 --></dependency><dependency><groupId>io.grpc</groupId><artifactId>grpc-netty</artifactId><version>${grpc.version}</version></dependency><dependency><!-- necessary for Java 9+ --><groupId>org.apache.tomcat</groupId><artifactId>annotations-api</artifactId><version>6.0.53</version></dependency></dependencies><build><extensions><extension><groupId>kr.motd.maven</groupId><artifactId>os-maven-plugin</artifactId><version>1.6.2</version></extension></extensions><plugins><plugin><groupId>org.xolstice.maven.plugins</groupId><artifactId>protobuf-maven-plugin</artifactId><version>0.6.1</version><configuration><protocArtifact>com.google.protobuf:protoc:${protoc.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></goals></execution></executions></plugin><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>

在resource同级目录下创建一个包,包下创建proto文件
在这里插入图片描述
proto文件

syntax = "proto3";package mistra;
//生成的java代码包名
option java_package = "org.example.mistra";
//创建的javaBean的文件名
option java_outer_classname = "MistraProto";
//option java_generic_services = true;
option java_multiple_files = true;//请求
message MistraRequest {string id = 1;int64 timestamp = 2;string message = 3;
}//响应
message MistraResponse {string message = 1;
}
//声明一个服务名称
service MistraService {rpc SendMessage(MistraRequest) returns (MistraResponse) {}
}

然后使用maven打包,在target目录下生成代码,复制到自己的目录下。
生成代码:
在这里插入图片描述
复制到自己目录下,再创建一个client和server,结构如下
在这里插入图片描述

client

package com.test.grpc.mistra.generate.client;import com.test.grpc.mistra.generate.MistraRequest;
import com.test.grpc.mistra.generate.MistraResponse;
import com.test.grpc.mistra.generate.MistraServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;import java.util.concurrent.TimeUnit;/*** @author清梦* @site www.xiaomage.com* @company xxx公司* @create 2024-06-04 21:59*/
public class MistraClient {private final ManagedChannel channel;private final MistraServiceGrpc.MistraServiceBlockingStub blockingStub;public MistraClient(String host, int port) {channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext().build();blockingStub = MistraServiceGrpc.newBlockingStub(channel);}public void shutdown() throws InterruptedException {channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);}public void greet(String name) {MistraRequest request = MistraRequest.newBuilder().setId(name).build();MistraResponse response = blockingStub.sendMessage(request);System.out.println(response.getMessage());}public static void main(String[] args) throws InterruptedException {MistraClient client = new MistraClient("127.0.0.1", 8001);System.out.println("-------------------客户端开始访问请求-------------------");for (int i = 0; i < 10; i++) {client.greet("你若想生存,绝处也能缝生: " + i);}}
}

server

package com.test.grpc.mistra.generate.server;import com.test.grpc.mistra.generate.MistraRequest;
import com.test.grpc.mistra.generate.MistraResponse;
import com.test.grpc.mistra.generate.MistraServiceGrpc;
import io.grpc.BindableService;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;import java.io.IOException;/*** @author清梦* @site www.xiaomage.com* @company xxx公司* @create 2024-06-04 21:59*/
public class MistraServer {private int port;private Server server;private void start() throws IOException{server = ServerBuilder.forPort(port).addService((BindableService) new MistraSendMessage()).build().start();System.out.println("-------------------服务端服务已开启,等待客户端访问------------------");Runtime.getRuntime().addShutdownHook(new Thread(){@Overridepublic void run() {System.out.println("*** shutting down gRPC server since JVM is shutting down");MistraServer.this.stop();System.err.println("*** server shut down");}});}private void stop() {if (server != null) {server.shutdown();}}private void blockUntilShutdown() throws InterruptedException {if (server != null) {server.awaitTermination();}}public static void main(String[] args) throws IOException, InterruptedException {final MistraServer server = new MistraServer();//启动服务server.start();//服务一直在线,不关闭server.blockUntilShutdown();}private class MistraSendMessage extends MistraServiceGrpc.MistraServiceImplBase {@Overridepublic void sendMessage(MistraRequest request, StreamObserver<MistraResponse> responseObserver) {//业务实现代码System.out.println("server:" + request.getId());MistraResponse response = MistraResponse.newBuilder().setMessage("响应信息" + request.getMessage()).build();responseObserver.onNext(response);responseObserver.onCompleted();}}}
http://www.lryc.cn/news/364253.html

相关文章:

  • 通信技术振幅键控(ASK)调制与解调硬件实验
  • 自动化办公02 用openpyxl库操作excel.xlsx文件(新版本)
  • 用户反馈解决方案 —— 兔小巢构建反馈功能
  • git 下载失败
  • 力扣1438.绝对差不超过限制的最长连续子数组
  • 如何避免Python中默认参数带来的陷阱
  • 代码随想录算法训练营第五十天|198.打家劫舍、213.打家劫舍II、337.打家劫舍III
  • VB.net 进行CAD二次开发(二)
  • 安徽某高校数据挖掘作业6
  • CMakeLists.txt和Package.xml
  • Debian常用命令详解
  • 代码随想录算法训练营day29|491.递增子序列、46.全排列、47.全排列II
  • 【ARM Cache 与 MMU 系列文章 7.8 – ARMv8/v9 MMU Table 表分配原理及其代码实现 2】
  • SAP PP学习笔记17 - MTS(Make-to-Stock) 按库存生产(策略70)
  • 网页音频提取在线工具有哪些 网页音频提取在线工具下载
  • 【ARM Cache 系列文章 2.1 -- Cache PoP 及 PoDP 介绍】
  • 一文了解JVM面试篇(上)
  • C#WPF控件Textbox绑定浮点型数据限制小数位方法
  • mysql引入表名称的注意事项
  • C语言数据结构快速排序的非递归、归并排序、归并排序的非递归等的介绍
  • 学生成绩管理系统(大一大作业)
  • 数据结构:模拟栈
  • 02-2.3.6 顺序表和链表的比较
  • C++ : 模板初阶
  • FFA-Net:用于单图像去雾的特征融合注意力网络
  • 网工内推 | 联通公司,云计算售前,AWS认证优先
  • [Redis]Zset类型
  • 【云原生】Kubernetes----Ingress对外服务
  • 项目管理之maven svn
  • Redis篇 list类型在Redis中的命令操作