feign client请求参数用json,响应参数接收protobuf
时间: 2023-08-10 07:53:07 浏览: 124
实现protobuf与json的互转
5星 · 资源好评率100%
可以通过Feign的`@RequestBody`注解将请求参数转换为JSON格式,同时通过定义`@Headers`注解设置请求的`Content-Type`为`application/json`。然后在定义Feign接口时,可以使用`@Headers`注解定义接收响应的`Content-Type`为`application/protobuf`,并且使用`@ResponseParser`注解指定响应解析器为Protobuf格式。示例代码如下:
```java
import feign.Headers;
import feign.Param;
import feign.RequestLine;
import feign.Response;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.codec.ErrorDecoder;
import feign.protobuf.ProtobufDecoder;
import feign.protobuf.ProtobufEncoder;
import feign.slf4j.Slf4jLogger;
public interface MyService {
@RequestLine("POST /api")
@Headers({"Content-Type: application/json"})
@ResponseParser(ProtobufResponseParser.class)
MyResponse postJson(@RequestBody MyRequest request);
static class ProtobufResponseParser implements ResponseParser {
private final ProtobufDecoder decoder = new ProtobufDecoder(MyResponse.class);
@Override
public Object parseResponse(Response response) throws IOException {
return decoder.decode(response, MyResponse.class);
}
}
static MyService connect(String url) {
return Feign.builder()
.logger(new Slf4jLogger())
.encoder(new ProtobufEncoder())
.decoder(new ProtobufDecoder())
.errorDecoder(new MyErrorDecoder())
.target(MyService.class, url);
}
}
```
注意:这里假设`MyRequest`和`MyResponse`分别是请求和响应的Java对象,且`MyResponse`是Protobuf格式的。同时需要定义一个`ProtobufResponseParser`类,用于将响应转换为Java对象。在`Feign.builder()`中需要设置`encoder`和`decoder`为`ProtobufEncoder`和`ProtobufDecoder`,并且还需要定义一个错误解码器`MyErrorDecoder`,用于处理HTTP请求失败时的异常情况。
阅读全文