Grpc-java请求与响应参数统一打印

背景

公司使用的GoogleProtobufGrpc-java相关框架,对于调用第二/三方接口的请求日志统一打印一直是一个问题

思路一:

如下图所示:Protobuf生成的xxxGrpc相关类把请求参数和响应参数放在了requestMarshallerresponseMarshaller里面,我们只需要拿到Marshaller并重写Marshallerstream()parse()即可,然后在start()或者初始化Grpc时向MethodDescriptor.Builder提供自己的Marshaller

Grpc类

upload successful

Marshaller接口

upload successful

初始化并装载Grpc
package com.ypshengxian.store.server.infrastructure.marshaller;

import io.grpc.MethodDescriptor;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;


/**
 * 描述:
 * 思路:proto文件生成的所有Grpc类都有SERVICE_NAME(文件唯一全限定名)
 * 且所有文件都将请求和响应放在了RequestMarshaller和ResponseMarshaller中
 *
 * Created by zjw on 2021/9/9 13:52
 */
@Slf4j
public class GlobalMarshallerInitializer {

    private static final String SERVICE_NAME = "SERVICE_NAME";
    private static final String requestMarshaller = "requestMarshaller";
    private static final String responseMarshaller = "responseMarshaller";


    private GlobalMarshallerInitializer(){
        throw new IllegalStateException("Utility class");
    }

    /**
     * 把grpc中的requestMarshaller注册到JsonLoggerMarshaller进行json日志输出
     * @param serviceClass
     */
    public static void initiateJsonLoggerMarshaller(Class<?> serviceClass) {
        try {
            Field serviceNameField = serviceClass.getField(SERVICE_NAME);
            if (serviceNameField == null) return;

            for (Method m : serviceClass.getDeclaredMethods()) {

                if (Modifier.isStatic(m.getModifiers()) && m.getReturnType() == MethodDescriptor.class) {

                    // 为各RPC调用方法生成默认的MethodDescriptor,默认MethodDescriptor中的Marshaller使用的是二进制格式传输报文
                    MethodDescriptor<?, ?> md = (MethodDescriptor<?, ?>) m.invoke(null);

                    Field requestMarshallerField = md.getClass().getDeclaredField(requestMarshaller);
                    Field responseMarshallerField = md.getClass().getDeclaredField(responseMarshaller);

                    // 使用反射机制设置输入与输出Marshaller
                    requestMarshallerField.setAccessible(true);
                    requestMarshallerField.set(md, new JsonLoggerMarshaller(md.getRequestMarshaller()));
                    requestMarshallerField.setAccessible(false);

                    responseMarshallerField.setAccessible(true);
                    responseMarshallerField.set(md, new JsonLoggerMarshaller(md.getResponseMarshaller()));
                    responseMarshallerField.setAccessible(false);

                    log.info("initialization success~" + md.getFullMethodName());
                }
            }
        } catch (Exception e) {
            log.error("JsonLoggerMarshaller initialization fail~" + serviceClass.getName(), e);
        }
    }

}
重写Grpc的Marshaller接口
package com.ypshengxian.store.server.infrastructure.marshaller;

import com.google.protobuf.Message;
import com.google.protobuf.util.JsonFormat;
import com.google.protobuf.util.JsonFormat.Printer;
import com.ypshengxian.store.server.infrastructure.utils.EnvLogPrintUtil;
import io.grpc.MethodDescriptor.Marshaller;

import java.io.InputStream;

/**
 * 描述:打印
 * Created by zjw on 2021/9/9 14:54
 */
public class JsonLoggerMarshaller<T extends Message> implements Marshaller<T> {

    private final Marshaller<T> baseMarshaller;

    private final Printer printer = JsonFormat.printer().omittingInsignificantWhitespace();

    public JsonLoggerMarshaller(Marshaller<T> baseMarshaller) {
        this.baseMarshaller = baseMarshaller;
    }

    public InputStream stream(T value) {
        try {
            String info = printer.print(value);
            EnvLogPrintUtil.info("input:" + info);
        } catch (Exception e) {
            EnvLogPrintUtil.error("print InputStream error", e);
        }

        return baseMarshaller.stream(value);
    }

    public T parse(InputStream stream) {
        T msg = baseMarshaller.parse(stream);
        try {
            String info = printer.print(msg);
            EnvLogPrintUtil.info("output:" + info);
        } catch (Exception e) {
            EnvLogPrintUtil.error("InputStream parse error", e);
        }

        return msg;
    }
}
使用

在Rpc注册到Spring容器时初始化Grpc,这样此Grpc在调用其他接口时便会相关请求、响应

@Bean
  public UserCartGrpc.UserCartBlockingStub userCartBlockingStub(ManagedChannelFactory factory) {
      GlobalMarshallerInitializer.initiateJsonLoggerMarshaller(UserCartGrpc.class);
      return UserCartGrpc.newBlockingStub(factory.create(UserCartGrpc.SERVICE_NAME)).withInterceptors(new GrpcClientInterceptor());
  }

思路二

在将Grpc注册到Spring容器的时候可以使用拦截器,在拦截器中打印相关请求与响应。tips:客户端拦截器实现ClientInterceptor,服务端拦截器实现ServerInterceptor

重写ClientInterceptor
package com.ypshengxian.store.server.infrastructure.config;

import com.ypshengxian.store.server.infrastructure.utils.EnvLogPrintUtil;
import io.grpc.*;
import lombok.extern.slf4j.Slf4j;

/**
 * 描述:用来打印请求与响应日志
 * Created by zjw on 2021/9/10 09:52
 */
@Slf4j
public class GrpcClientInterceptor implements ClientInterceptor {

    @Override
    public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
        // MethodDescriptor.Marshaller<ReqT> requestMarshaller = method.getRequestMarshaller();
        // next.newCall(method, callOptions);


        return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(
                next.newCall(method, callOptions)) {

            @Override
            public void sendMessage(ReqT message) {
                EnvLogPrintUtil.info("interceptCall sending message, method:{} message:{} ", method.getFullMethodName(), message.toString());
                super.sendMessage(message);
            }

            @Override
            public void start(Listener<RespT> responseListener, Metadata headers) {

                ClientCall.Listener<RespT> listener = new ForwardingClientCallListener<RespT>() {
                    @Override
                    protected Listener<RespT> delegate() {
                        return responseListener;
                    }

                    @Override
                    public void onMessage(RespT message) {
                        EnvLogPrintUtil.info("interceptCall received message:{} ", message.toString());
                        super.onMessage(message);
                    }
                };

                super.start(listener, headers);
            }
        };
    }
}
使用

在将Grpc注册到Spring容器的时候使用我们自定义的拦截器

@Bean
public UserCartGrpc.UserCartBlockingStub userCartBlockingStub(ManagedChannelFactory factory) {
    return UserCartGrpc.newBlockingStub(factory.create(UserCartGrpc.SERVICE_NAME)).withInterceptors(new GrpcClientInterceptor());
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java + gRPC + grpc-gateway 的实践主要分为以下几个步骤: 1. 定义 proto 文件 在 proto 文件中定义需要调用的服务以及方法,同时指定请求响应数据类型。例如: ``` syntax = "proto3"; package example; service ExampleService { rpc ExampleMethod (ExampleRequest) returns (ExampleResponse) {} } message ExampleRequest { string example_field = 1; } message ExampleResponse { string example_field = 1; } ``` 2. 使用 protoc 编译 proto 文件 使用 protoc 编译 proto 文件,生成 Java 代码。例如: ``` protoc --java_out=./src/main/java ./example.proto ``` 3. 实现 gRPC 服务 在 Java 代码中实现定义的 gRPC 服务,例如: ``` public class ExampleServiceImpl extends ExampleServiceGrpc.ExampleServiceImplBase { @Override public void exampleMethod(ExampleRequest request, StreamObserver<ExampleResponse> responseObserver) { // 实现具体逻辑 ExampleResponse response = ExampleResponse.newBuilder().setExampleField("example").build(); responseObserver.onNext(response); responseObserver.onCompleted(); } } ``` 4. 启动 gRPC 服务器 使用 gRPC 提供的 ServerBuilder 构建 gRPC 服务器,并启动服务器。例如: ``` Server server = ServerBuilder.forPort(8080).addService(new ExampleServiceImpl()).build(); server.start(); ``` 5. 集成 grpc-gateway 使用 grpc-gateway 可以将 gRPC 服务转换为 HTTP/JSON API。在 proto 文件中添加以下内容: ``` import "google/api/annotations.proto"; service ExampleService { rpc ExampleMethod (ExampleRequest) returns (ExampleResponse) { option (google.api.http) = { post: "/example" body: "*" }; } } ``` 在 Java 代码中添加以下内容: ``` Server httpServer = ServerBuilder.forPort(8081).addService(new ExampleServiceImpl()).build(); httpServer.start(); String grpcServerUrl = "localhost:8080"; String httpServerUrl = "localhost:8081"; ProxyServerConfig proxyConfig = new ProxyServerConfig(grpcServerUrl, httpServerUrl, "/example"); HttpProxyServer httpProxyServer = new HttpProxyServer(proxyConfig); httpProxyServer.start(); ``` 6. 测试 使用 HTTP/JSON API 调用 gRPC 服务,例如: ``` POST http://localhost:8081/example Content-Type: application/json { "example_field": "example" } ``` 以上就是 Java + gRPC + grpc-gateway 的实践步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值