grpc使用客户端技巧

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

}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏文渊之博

SSIS 实用表达式部分总结

下面,列出一些实用的表达式: 1,路径取文件名 1 RIGHT([FilePath],FINDSTRING(REVERSE([FilePath]),"\\",1...

1768
来自专栏林德熙的博客

C# 使用Emit深克隆

有人问,复制一个类所有属性到另一个类有多少方法?这也就是问深克隆有多少个方法,容易想的有三个。直接复制,反射复制,序列化复制。但是性能比较快的有表达式树复制 I...

821
来自专栏landv

excel vba获取拼音

1482
来自专栏程序猿

父子节点

create table Jiedian( node hierarchyid primary key, nodLevel as node.Get...

35010
来自专栏杨建荣的学习笔记

使用sed做特殊的行列转换(r2笔记40天)

行列转换在数据库,开发语言中都是一个津津乐道的话题,今天来简单演示一个使用sed所作的特殊行列转换。 日志的内容如下: append data from MIG...

2767
来自专栏技术随笔

医学影像中Dicom的常用Tag分类与说明

3837
来自专栏软件工程师成长笔记

基于MyBatis用mapper.xml文件配置执行任意字符串拼接sql语句

由于做的一个小项目里需要联动查询,一想16种情况,因为我是SSM框架写的,这样我就要写16个接口,16个实现,16条sql语句,想想就大头。既然数据库本身接收的...

3162
来自专栏菩提树下的杨过

无限级分类(非递归算法/存储过程版/GUID主键)完整数据库示例_(4)显示记录

显示记录,其实再简单不过了,一条sql语句即可 Select * From T_Class order By F_RootID,F_Orders 下面给出一个A...

18010
来自专栏码匠的流水账

FluxInterval实例及解析

reactor-core-3.1.3.RELEASE-sources.jar!/reactor/core/publisher/FluxInterval.java

691
来自专栏GreenLeaves

Oracle 表复杂查询之多表合并查询

本文使用到的是oracle数据库scott方案所带的表,scott是oracle数据库自带的方案,使用前请确保其解锁 ? Oracle合并查询一共有四种方式,分...

1866

扫码关注云+社区