简体   繁体   English

Feign REST客户端:如何获取HTTP状态?

[英]Feign REST Client: How to get the HTTP status?

I have Feign client setup with Hystrix and I am trying to log all the HTTP status codes that I get from my API calls into a database. 我使用Hystrix进行了Feign客户端设置,并且试图将我从API调用获得的所有HTTP状态代码记录到数据库中。 So this means, if one of my calls give me a 201, I would want to log that into DB. 因此,这意味着,如果我的一个电话给我201,我希望将其登录到DB。 If my call results in a failure, my fallback handler can obviously log that but I want to do the DB inserts in one place. 如果我的呼叫导致失败,那么我的后备处理程序显然可以记录该事件,但是我想将数据库插入到一个地方。 Does feign have a way to get access to responses or some kind of general callback? 假装是否有办法获得响应或某种通用回调?

You have to provide custom decoder to get your response in ResponseEntity<Object> . 您必须提供自定义decoder才能在ResponseEntity<Object>获得响应。

NotificationClient notificationClient = Feign.builder()
                .encoder(new JacksonEncoder())
                .decoder(customDecoder())
                .target(Target.EmptyTarget.create(NotificationClient.class));

Here you define your custom decoder bean. 在这里定义您的自定义解码器bean。 You can define your own by implementing Decoder but I'm using spring decoder. 您可以通过实现Decoder来定义自己的代码,但我使用的是Spring解码器。

@Bean
public Decoder customDecoder() {
    HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter(customObjectMapper());
    ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(jacksonConverter);
    return new ResponseEntityDecoder(new SpringDecoder(objectFactory));
}

Now collect your response in ResponseEntity<Object> 现在在ResponseEntity<Object>收集您的响应

ResponseEntity<Object> response = notificationClient.notify();
int status = response.getStatusCodeValue();

Another option is to create your own feign.Logger implementation, overriding the logAndRebufferResponse method: 另一个选择是创建自己的feign.Logger实现,覆盖logAndRebufferResponse方法:

protected Response logAndRebufferResponse(
   String configKey, Level logLevel, Response response, long elapsedTime);

This may be simpler than creating a Decoder and is guaranteed to be called when a response is received regardless of status. 这可能比创建Decoder更简单,并且可以确保无论状态如何,在收到响应时都将调用它。 Decoder s are only called if the request does not trigger an error. 仅在请求未触发错误的情况下才调用Decoder

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM