通过WebClient访问Web资源

了解 WebClient

WebClient

  • ⼀个以 Reactive ⽅式处理 HTTP 请求的非阻塞式的客户端

支持的底层 HTTP 库

  • Reactor Netty - ReactorClientHttpConnector(常用)
  • Jetty ReactiveStream HttpClient - JettyClientHttpConnector

WebClient 的基本用法

创建 WebClient

  • WebClient.create()

  • WebClient.builder()

发起请求

  • get() / post() / put() / delete() / patch()

获得结果

  • retrieve() / exchange()

处理 HTTP Status

  • onStatus()

应答正文

  • bodyToMono() / bodyToFlux()

实例

@SpringBootApplication
@Slf4j
public class WebclientDemoApplication implements ApplicationRunner {
	@Autowired
	private WebClient webClient;

	public static void main(String[] args) {
		new SpringApplicationBuilder(WebclientDemoApplication.class)
				.web(WebApplicationType.NONE)
				.bannerMode(Banner.Mode.OFF)
				.run(args);
	}

	@Bean
	public WebClient webClient(WebClient.Builder builder) {
		return builder.baseUrl("http://localhost:8080").build(); //所有请求的基础uri
	}

	@Override
	public void run(ApplicationArguments args) throws Exception {
		CountDownLatch cdl = new CountDownLatch(2);

		webClient.get()  //创造一个get请求
				.uri("/coffee/{id}", 1) //访问的uri
				.accept(MediaType.APPLICATION_JSON_UTF8)//设置一个接收头 响应为JSON_UTF8格式
				.retrieve()			//获取结果 可以用exchange代替
				.bodyToMono(Coffee.class)  //将结果转为Mono类型 baby类型为coffee类型 处理单组数据
				.doOnError(t -> log.error("Error: ", t))
				.doFinally(s -> cdl.countDown()) //让主线程等待异步的线程
				.subscribeOn(Schedulers.single())//在single线程中做subscribe
				.subscribe(c -> log.info("Coffee 1: {}", c));

		Mono<Coffee> americano = Mono.just(
				Coffee.builder()
						.name("americano")
						.price(Money.of(CurrencyUnit.of("CNY"), 25.00))
						.build()
		);
		webClient.post()   //创建一个post请求
				.uri("/coffee/")
				.body(americano, Coffee.class)//post正文
				.retrieve()//获取结果 可以用exchange代替
				.bodyToMono(Coffee.class)//处理单组数据
				.doFinally(s -> cdl.countDown())//让主线程等待异步的线程
				.subscribeOn(Schedulers.single())
				.subscribe(c -> log.info("Coffee Created: {}", c));

		cdl.await();

		webClient.get()//创建一个get请求
				.uri("/coffee/")
				.retrieve() // 获取结果 可以用exchange代替  返回的上一个coffee的list
				.bodyToFlux(Coffee.class)//处理多个对象 即多组数据
				.toStream() //变成一stream
				.forEach(c -> log.info("Coffee in List: {}", c));
	}
}

结果

在这里插入图片描述

分析

因为用了single,使用查询咖啡与创建咖啡的顺序不一定是谁前谁后的,不是按照代码的顺序来的。如果,要写死,就换其他方法。

发布了59 篇原创文章 · 获赞 6 · 访问量 1099

猜你喜欢

转载自blog.csdn.net/weixin_43790623/article/details/104064769