Java开发Grpc,打印debug请求,响应信息

需求

在开发java项目,用到grpc的时候,我们发现调试grpc调用比较不方便,因为grpc基于http2协议封装了请求参数和响应结果,人眼一下子还是不能快速看到请求参数和响应结果的,所以我们需要掌握打印请求参数和响应信息的手段


 

原始代码

 

 /**
 * Get topics (max 10) for our project ID: the topic list is logged to the logger.
 *
 * @param projectID the GCP project ID to get the pubsub topics for. This is a string like
 * "projects/balmy-cirrus-225307" where "balmy-cirrus-225307" is
 * the project ID for the project you created.
 */
 public void getTopics(String projectID) {
 logger.log(Level.INFO, "Will try to get topics for project {0} ...", projectID);

 ListTopicsRequest request = ListTopicsRequest.newBuilder()
 .setPageSize(10) // get max 10 topics
 .setProject(projectID) // for our projectID
 .build();

 ListTopicsResponse response;
 try {
 response = blockingStub.listTopics(request);
 } catch (StatusRuntimeException e) {
 logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
 return;
 }
 logger.log(Level.INFO, "Topics list:\n {0}", response.getTopicsList());
 }

 

这是来自官方example的一段代码片段,大多数的请求调用,都是这样。

 

封装Pb to json转码

pb是二进制协议,我们需要封装一个转换为Json的工具类

 

package com.xxx.xxx.xxx.app.util;

import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.util.JsonFormat;

public class PbJsonHelper {
 /**
 * 打印Pb 为 JSON字符串
 * @param any
 * @return
 */
 public final static String toJson(MessageOrBuilder any) {
 try {
 return JsonFormat.printer().includingDefaultValueFields().print(any);
 } catch (Exception e) {
 //TODO 打印日志或者什么的
 }
 return "";
 }
}

 

打印请求信息和响应结果

 

 /**
 * Get topics (max 10) for our project ID: the topic list is logged to the logger.
 *
 * @param projectID the GCP project ID to get the pubsub topics for. This is a string like
 * "projects/balmy-cirrus-225307" where "balmy-cirrus-225307" is
 * the project ID for the project you created.
 */
 public void getTopics(String projectID) {
 logger.log(Level.INFO, "Will try to get topics for project {0} ...", projectID);

 ListTopicsRequest request = ListTopicsRequest.newBuilder()
 .setPageSize(10) // get max 10 topics
 .setProject(projectID) // for our projectID
 .build();

 ListTopicsResponse response;
 String currentMethod = "getTopics";
 
 log.info(currentMethod + " send request: {}, response: {}", 
 PbJsonHelper.toJson(request),
 PbJsonHelper.toJson(response));
 try {
 response = blockingStub.listTopics(request);
 } catch (StatusRuntimeException e) {
 logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
 return;
 }
 logger.log(Level.INFO, "Topics list:\n {0}", response.getTopicsList());
 }

 

注意看这个新增的代码

 

 String currentMethod = "getTopics";
 
 log.info(currentMethod + " send request: {}, response: {}", 
 PbJsonHelper.toJson(request),
 PbJsonHelper.toJson(response));

分类: 编程语言 标签: JSON Java GRPC 发布于: 2020-12-26 19:07:08, 点击数: