grpc 使用技巧,最近在做的项目是服务端是go语言提供服务使用的是grpc框架。

java在实现客户端的时候,参数的生成大部分采用创建者模式。java在接受go服务端

返回数据的时候,更多的是通过parseFrom形式来创建。

  demo样例:

  

import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors;
import com.google.protobuf.InvalidProtocolBufferException;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pino.RequestInstance2;
import pino.grpc.routeguide.*;
import pino.pino_resp_pb;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
* Created  on 2017/5/4.
*/
public class PinoClient {

public static final RequestInstance2.FeatureGroup.Builder BUILDER_FEATURE = RequestInstance2.RequestInstance.newBuilder().getCommonFeature().toBuilder();
protected static final Logger logger = LoggerFactory.getLogger("file_logger");

private final ManagedChannel channel;
private final RouteGuideGrpc.RouteGuideBlockingStub blockingStub;

/** Construct client connecting to HelloWorld server at {@code host:port}. */
public PinoClient(String host, int port) {
this(ManagedChannelBuilder.forAddress(host, port)
// Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
// needing certificates.
.usePlaintext(true));
}

/** Construct client for accessing RouteGuide server using the existing channel. */
PinoClient(ManagedChannelBuilder<?> channelBuilder) {
channel = channelBuilder.build();
blockingStub = RouteGuideGrpc.newBlockingStub(channel);
}

public void shutdown() throws InterruptedException {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}

/** call pino to server. */
public Double callPino(double[] arr) {
if(logger.isInfoEnabled())
logger.info("start pino...");

if(arr==null)
return 0d;

RequestInstance2.Feature feature1 = RequestInstance2.RequestInstance.newBuilder()
.getCommonFeature().toBuilder().addFeaturesBuilder(0).setName("1").setSValue(String.valueOf(arr[0])).build();
RequestInstance2.Feature feature2 = RequestInstance2.RequestInstance.newBuilder()
.getCommonFeature().toBuilder().addFeaturesBuilder(0).setName("2").setSValue(String.valueOf(arr[1])).build();
RequestInstance2.Feature feature3 = RequestInstance2.RequestInstance.newBuilder()
.getCommonFeature().toBuilder().addFeaturesBuilder(0).setName("3").setSValue(String.valueOf(arr[2])).build();
RequestInstance2.Feature feature4 = RequestInstance2.RequestInstance.newBuilder()
.getCommonFeature().toBuilder().addFeaturesBuilder(0).setName("4").setSValue(String.valueOf(arr[3])).build();
RequestInstance2.Feature feature5 = RequestInstance2.RequestInstance.newBuilder()
.getCommonFeature().toBuilder().addFeaturesBuilder(0).setName("5").setSValue(String.valueOf(arr[4])).build();
RequestInstance2.Feature feature6 = RequestInstance2.RequestInstance.newBuilder()
.getCommonFeature().toBuilder().addFeaturesBuilder(0).setName("6").setSValue(String.valueOf(arr[5])).build();
RequestInstance2.Feature feature7 = RequestInstance2.RequestInstance.newBuilder()
.getCommonFeature().toBuilder().addFeaturesBuilder(0).setName("7").setSValue(String.valueOf(arr[6])).build();
RequestInstance2.Feature feature8 = RequestInstance2.RequestInstance.newBuilder()
.getCommonFeature().toBuilder().addFeaturesBuilder(0).setName("8").setSValue(String.valueOf(arr[7])).build();
RequestInstance2.Feature feature9 = RequestInstance2.RequestInstance.newBuilder()
.getCommonFeature().toBuilder().addFeaturesBuilder(0).setName("9").setSValue(String.valueOf(arr[8])).build();
RequestInstance2.Feature feature10 = RequestInstance2.RequestInstance.newBuilder()
.getCommonFeature().toBuilder().addFeaturesBuilder(0).setName("10").setSValue(String.valueOf(arr[9])).build();
RequestInstance2.Feature feature11 = RequestInstance2.RequestInstance.newBuilder()
.getCommonFeature().toBuilder().addFeaturesBuilder(0).setName("11").setSValue(String.valueOf(arr[10])).build();

RequestInstance2.RequestInstance.Builder builder = RequestInstance2.RequestInstance.newBuilder()
.addInstanceFeature(0, RequestInstance2.RequestInstance.newBuilder()
.getCommonFeature().toBuilder()
.addFeatures(0,feature1)
.addFeatures(1,feature2)
.addFeatures(2,feature3)
.addFeatures(3,feature4)
.addFeatures(4,feature5)
.addFeatures(5,feature6)
.addFeatures(6,feature7)
.addFeatures(7,feature8)
.addFeatures(8,feature9)
.addFeatures(9,feature10)
.addFeatures(10,feature11)
);

RequestInstance2.RequestInstance instance = builder.build();
byte[] bytes = instance.toByteArray();
ByteString bs = ByteString.copyFrom(bytes);

InputHead inputHead = InputHead.getDefaultInstance().toBuilder().setVersion(20).setBodySize(bs.size()).addAppKeys(0).setAppKeys(0, 85001).build();
Request request = Request.getDefaultInstance().toBuilder().setHead(inputHead).setBody(bs).build();

Response response = null;
try {
response = blockingStub.getPredictorValue(request);
} catch (StatusRuntimeException e) {
logger.error("RPC failed: "+ e.getStatus());
return 0d;
}
double value = 0d;
if(response!=null){

ByteString tempBytes = response.getBody();
try {
pino_resp_pb.Resp resp = pino_resp_pb.Resp.parseFrom(tempBytes);

if(resp.getOutputCount()>0){
pino_resp_pb.Output output = resp.getOutput(0);

pino_resp_pb.Matrix matrix = output.getMatrix();
if(matrix!=null&&matrix.getDoubleValCount()>0)
value = matrix.getDoubleVal(0);
}

System.out.println(value);
} catch (InvalidProtocolBufferException e) {
logger.error(e.getMessage(),e);
}
}

if(logger.isInfoEnabled())
logger.info("end pino.");
return value;
}

/**
* Greet server. If provided, the first element of {@code args} is the name to use in the
* greeting.
*/
public static void main(String[] args) throws Exception {
PinoClient client = new PinoClient("10.187.81.155", 80);

try {
/* Access a service running on the local machine on port 50051 */
String user = "world";
if (args.length > 0) {
user = args[0]; /* Use the arg as the name to greet if provided */
}
double[] features = {52.9186,4.2,0.0,0,0.03168337,8.771171,54.85312,0,0,0,0};
double[] features2 = {52.9186,4.2,0.0,0,0.03168337,8.771171,54.85312,0,0.03168337,8.771171,54.85312};
for(int i=0;i<10;i++){
client.callPino(features);
client.callPino(features2);
}
} finally {
client.shutdown();
}
}

}

可以关注我的公众账户 互联网开发者Club,公众账户分享个性化推荐,搜索,分布式架构,高性能,高可用

grpc使用客户端技巧的更多相关文章

  1. gRPC java 客户端,服务器端通讯使用json格式

    使用 protobuf 作为通讯内容序列化的简单例子请看:http://www.cnblogs.com/ghj1976/p/5458176.html . 本文是使用 json 做为内容序列化的简单例子 ...

  2. grpc协议--客户端构造

    由于服务端不在构造,已经构造完成不做构造 gRPC 接口名字为service,proto文件内有定义 1.本目录生成grpc文件 python -m grpc_tools.protoc -I. --p ...

  3. Go gRPC教程-客户端流式RPC(四)

    前言 上一篇介绍了服务端流式RPC,客户端发送请求到服务器,拿到一个流去读取返回的消息序列. 客户端读取返回的流的数据.本篇将介绍客户端流式RPC. 客户端流式RPC:与服务端流式RPC相反,客户端不 ...

  4. GRpc添加客户端的四种方式

    随着微服务的发展,相信越来越多的.net人员也开始接触GRpc这门技术,大家生成GRpc客户端的方式也各不相同,今天给大家介绍一下依据Proto文件生成Rpc客户端的四种方式 前提:需要安装4个Nug ...

  5. gRPC(2):客户端创建和调用原理

    1. gRPC 客户端创建流程 1.1 背景 gRPC 是在 HTTP/2 之上实现的 RPC 框架,HTTP/2 是第 7 层(应用层)协议,它运行在 TCP(第 4 层 - 传输层)协议之上,相比 ...

  6. ASP.NET Core 3.0 使用gRPC

    一.简介 gRPC 是一个由Google开源的,跨语言的,高性能的远程过程调用(RPC)框架. gRPC使客户端和服务端应用程序可以透明地进行通信,并简化了连接系统的构建.它使用HTTP/2作为通信协 ...

  7. google多语言通信框架gRPC

    google多语言通信框架gRPC系列(一)概述 gRPC概述 3/26/2016 9:16:08 AM 目录 一.概述 二.编译gRPC 三.C#中使用gRPC 四.C++中使用gRPC 一直在寻找 ...

  8. 初识google多语言通信框架gRPC系列(一)概述

    gRPC概述 3/26/2016 9:16:08 AM 目录 一.概述 二.编译gRPC 三.C#中使用gRPC 四.C++中使用gRPC 一直在寻找多平台多语言的通信框架,微软的WCF框架很强大和灵 ...

  9. grpc介绍

    grpc入门(一) 一.什么是grpc grpc是谷歌开源的一款高性能的rpc框架 (https://grpc.io),可以使用protocol buffers作为IDL(Interface Defi ...

随机推荐

  1. SRS服务器搭建,ffmpeg 本地推流,srs从本地拉流

    参考: https://github.com/ossrs/srs/wiki/v2_CN_SampleFFMPEG git clone https://github.com/ossrs/srs cd s ...

  2. 嵌入式系统C编程之错误处理

    前言 本文主要总结嵌入式系统C语言编程中,主要的错误处理方式.文中涉及的代码运行环境如下: 一  错误概念 1.1 错误分类 从严重性而言,程序错误可分为致命性和非致命性两类.对于致命性错误,无法执行 ...

  3. Python 优雅获取本机 IP 方法【转】

    转自:https://www.cnblogs.com/lfxiao/p/9672975.html 见过很多获取服务器本地IP的代码,个人觉得都不是很好,例如以下这些 不推荐:靠猜测去获取本地IP方法 ...

  4. Linux 入门记录:十二、Linux 权限机制【转】

    转自:https://www.cnblogs.com/mingc/p/7591287.html 一.权限 权限是操作系统用来限制资源访问的机制,权限一般分为读.写.执行. 系统中每个文件都拥有特定的权 ...

  5. 64位Win7系统WMware安装Mac OS

    1.         准备工作 l  VMWare Workstation,我的版本是 l  MAC OS安装光盘镜像文件,种子地址 http://www.kuaipan.cn/file/id_611 ...

  6. C:详解C中volatile关键字

    原文地址:http://www.cnblogs.com/yc_sunniwell/archive/2010/06/24/1764231.html volatile提醒编译器它后面所定义的变量随时都有可 ...

  7. zabbix3.0.4添加对指定进程的监控

    zabbix3.0.4添加对进程的监控: 主要思路: 通过 ps -ef|grep sdk-push-1.0.0.jar |grep -v grep|wc -l 这个命令来判断进程sdk-push是否 ...

  8. PYTHON-迭代器,xxx生成式

    一 迭代器1 什么是迭代器 #迭代器即迭代的工具,那什么是迭代呢? #迭代是一个重复的过程,每次重复即一次迭代,并且每次迭代的结果都是下一次迭代的初始值 while True: #只是单纯地重复,因而 ...

  9. HTML5事件—visibilitychange 页面可见性改变事件

    转:https://blog.csdn.net/yusirxiaer/article/details/73480916 又看到一个很有意思的HTML5事件 visibilitychange事件是浏览器 ...

  10. mysql命令行怎么清屏

    例如: 怎么清屏? 哈哈 我也百度了半天,之后发现,这是个坑啊,dos(面向磁盘的操作命令)下面我们都是 cls 清屏,所以习惯性的用cls结果报错,打脸了吧.. mysql 命令行窗口不想看到那一堆 ...