WebFlux系列WebClient 日志

Posted JAVA微编程

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WebFlux系列WebClient 日志相关的知识,希望对你有一定的参考价值。

#Java#Spring#WebClient#WebFlux#log#日志#

WebClient 日志

视频讲解 : https://www.bilibili.com/video/av83627944/

 

WebfluxConsumerApplication.java
package com.example.webfluxconsumer;

import lombok.extern.log4j.Log4j2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Log4j2
@SpringBootApplication
public class WebfluxConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(WebfluxConsumerApplication.class, args);
    }
@RestController
class EmployeeController {
    @PostMapping("save")
    public Mono<Boolean> save(@RequestBody Mono<Employee> employeeMono) {
        WebClient webClient  = WebClient.builder().baseUrl("http://localhost:8080/save")
                .filter(logRequest())
                .filter(logResponse())
                .build();
        return webClient.post().body(employeeMono, Employee.class).retrieve().bodyToMono(Boolean.class);
    }
    private ExchangeFilterFunction logRequest() {
        return (clientRequest, next) -> {
            log.info("Request: {} {}", clientRequest.method(), clientRequest.url());
            clientRequest.headers()
                    .forEach((name, values) -> values.forEach(value -> log.info("Request: {}={}", name, value)));
            return next.exchange(clientRequest);
        };
    }
    private ExchangeFilterFunction logResponse() {
        return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
            clientResponse.headers().asHttpHeaders()
                    .forEach((name, values) -> values.forEach(value -> log.info("Response: {}={}", name, value)));
            return Mono.just(clientResponse);
        });
    }
}
}

公众号,坚持每天3分钟视频学习

以上是关于WebFlux系列WebClient 日志的主要内容,如果未能解决你的问题,请参考以下文章

WebFlux系列WebClient Post传参

WebFlux系列WebClient VS RestTemplate

WebFlux系列WebClient Uri列表数组传参

Spring WebFlux WebClient 构建器设置请求正文

使用 Apache HttpComponents 使用 Webflux Webclient 配置 SSL

Webflux WebClient中如何自定义异常?