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();}}}