反序列化之前如何使用Java Reactor WebClient打印responseBody

时间:2019-09-17 09:15:11

标签: spring project-reactor spring-webclient

我们计划从spring Rest-Template迁移到Reactor-webclient。

使用Rest-template,我们编写了自定义日志记录拦截器,在反序列化之前,我们在其中打印带有uniqueId的请求和响应。

现在weblient提供了过滤器,但是在过滤器中,我无法访问responseBody进行记录。

我们有一些第三方API,它们在发生错误的情况下会发送字符串,而在成功的情况下会发送一些对象。在这种情况下,我迫不及待要在反序列化之后记录响应,因为它会中断并且我们将无法记录得到的响应。

2 个答案:

答案 0 :(得分:4)

您可以尝试创建包装WebClient,该WebClient首先记录响应,然后反序列化。

成功响应将落在doOnSuccess上,错误将落在onErrorResume上。

public <T> Mono<T> get(String url, Map<String, String> headersMap, Class<T> type) {

    Mono<T> responseMono = client.get().uri(url).headers((h) -> headersMap.forEach(h::set)).retrieve()
            .bodyToMono(type);

    return responseMono.doOnSuccess(response -> log.debug("REST GET call to {} is successfull and response is {}",
        url,response).onErrorResume(err -> {
          log.error("Exception occurred calling get({}): {}", url,
              err.getMessage());
          return Mono.error(err);
        });
  }

答案 1 :(得分:0)

以下是一些我用来测试的sudo代码:

CREATE PROCEDURE make_booking (IN p_room_id VARCHAR(255), IN p_booked_date DATE, IN p_booked_time 
TIME, IN p_member_id VARCHAR(255))
BEGIN

/* Declare some temporary variables to hold some data that we'll be SELECTing later */
DECLARE v_price DECIMAL(6, 2);
DECLARE v_payment_due DECIMAL(6, 2);    

/* SELECT the price of the room and put it into the v_price variable */
SELECT price INTO v_price FROM rooms WHERE id = p_room_id;  

/* INSERT a record into the bookings table for the room and member */
INSERT INTO bookings (room_id, booked_date, booked_time, member_id) VALUES (p_room_id, 
p_booked_date, p_booked_time, p_member_id); 

/* Get the current payment due for the member and put it into the v_payment_due variable */
SELECT payment_due INTO v_payment_due FROM members WHERE id = p_member_id;

/* Update the payment due for the member to whatever it was before plus the price of the room we put into v_price earlier */
UPDATE members SET payment_due = v_payment_due + v_price WHERE id = p_member_id;  

END $$;