赞
踩
通过java的方式对接grpc接口,在java项目中属于第一次对接,编写文档记录一下,方便后期的对接,增加对接效率。
一.项目架构
后端采用Spring Boot、Spring Security、
Redis & Jwt
二.对接细节
1.pom中导入grpc需要的包依赖
下面展示一些 内联代码片
。
<!-- grpc -->
<protobuf.version>3.5.1</protobuf.version>
<protobuf-plugin.version>0.6.1</protobuf-plugin.version>
<grpc.version>1.42.1</grpc.version>
三.项目中添加protobuf-maven编译插件
<plugin> <groupId>org.xolstice.maven.plugins</groupId> <artifactId>protobuf-maven-plugin</artifactId> <version>${protobuf-plugin.version}</version> <configuration> <protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}</protocArtifact> <pluginId>grpc-java</pluginId> <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact> <!--默认值--> <protoSourceRoot>${project.basedir}/src/main/proto</protoSourceRoot> <outputDirectory>${project.basedir}/src/main/java</outputDirectory> <!--设置是否在生成java文件之前清空outputDirectory的文件,默认值为true,设置为false时也会覆盖同名文件--> <clearOutputDirectory>false</clearOutputDirectory> </configuration> <executions> <execution> <goals> <goal>compile</goal> <goal>compile-custom</goal> </goals> </execution> </executions> </plugin>
确定编译插件生效及指定文件生成目录
四.同级目录添加proto文件
指定输出地址
生成的文件在我们指定的目录下面
五.配置grpc地址及相关信息
grpc:
client:
local-grpc-server:
address: 'static://10.251.21.20:31484'
enableKeepAlive: true
keepAliveWithoutCalls: true
negotiationType: plaintext
六.grpc简单调用实例
@GrpcClient("local-grpc-server") private EngineGrpc.EngineBlockingStub engineStub; public String sendMessage() { try { final EngineGrpcProto.AsyncReply response = engineStub.scanAsync(EngineGrpcProto.ScanAsyncParams.newBuilder() .setApkUrl("xxx") .setReqId("1234-12345678-12345678-12345678-123456") .setCateOpt(65535) .setScanOpt(18999035) .setExtendFuncOpt(11) .setTimeout(600) .setEngineVer("292-pc64") .setVirusLibUrl("xxx") .setLicenseUrl("xxx") .setCallbackUrl("someurl") .setPriority(12) .setWaitUntil(Timestamp.newBuilder() .setNanos(0) .setSeconds(1661258870) .build()) .addApi(0, EngineGrpcProto.Api.newBuilder() .setCmd("GetAllVirNames") .build() ) .build() ); return response.getReqId(); } catch (final StatusRuntimeException e) { return "FAILED with " + e.getStatus().getCode().name(); } }
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。