spring boot使用WebClient调用其他系统提供的HTTP服务
2023-09-14 09:00:01 时间
WebClient的请求模式属于异步非阻塞,能够以少量固定的线程处理高并发的HTTP请求
WebClient是Spring WebFlux模块提供的一个非阻塞的基于响应式编程的进行Http请求的客户端工具,从Spring5.0开始提供
在Spring Boot应用中
1.添加Spring WebFlux依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency>
2.使用
(1)Restful接口demoController.java
package com.example.demo.controller; import com.example.demo.domain.MyData; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; @RestController @RequestMapping("/api") public class demoController { @GetMapping(value = "/getHeader", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}) public MyData getHeader(HttpServletRequest request) { int id = 0; if (request.getParameter("id") != null) { id = Integer.valueOf(request.getParameter("id")); } String name = request.getParameter("name"); //header String userAgent = "USER_AGENT——" + request.getHeader(HttpHeaders.USER_AGENT); userAgent += " | ACCEPT_CHARSET——" + request.getHeader(HttpHeaders.ACCEPT_CHARSET); userAgent += " | ACCEPT_ENCODING——" + request.getHeader(HttpHeaders.ACCEPT_ENCODING); userAgent += " | ContextPath——" + request.getContextPath(); userAgent += " | AuthType——" + request.getAuthType(); userAgent += " | PathInfo——" + request.getPathInfo(); userAgent += " | Method——" + request.getMethod(); userAgent += " | QueryString——" + request.getQueryString(); Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { System.out.println(cookie.getName() + ":" + cookie.getValue()); } } MyData data = new MyData(); data.setId(id); data.setName(name); data.setOther(userAgent); return data; } @PostMapping(value = "/getPost", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}) public MyData getPost(HttpServletRequest request) { int id = 0; if (request.getParameter("id") != null) { id = Integer.valueOf(request.getParameter("id")); } String name = request.getParameter("name"); System.out.println(name + "," + id); MyData data = new MyData(); data.setId(id); data.setName(name); return data; } /** * POST传JSON请求 */ @PostMapping(value = "/getPostJson", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}) public MyData getPostJson(@RequestBody(required = true) MyData data) { System.out.println(data.getId()); System.out.println(data.getName()); return data; } }
MyData.java
package com.example.demo.domain; public class MyData { private int id; private String name; private String other; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getOther() { return other; } public void setOther(String other) { this.other = other; } }
(2)WebClient使用
DemoApplicationTests.java
package com.example.demo; import com.example.demo.domain.MyData; import org.junit.Test; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; import java.time.Duration; import java.time.temporal.ChronoUnit; public class DemoApplicationTests { private WebClient webClient = WebClient.builder() .baseUrl("http://127.0.0.1:8080") .defaultHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)") .defaultCookie("ACCESS_TOKEN", "test_token").build(); @Test public void WebGetDemo() { try { Mono<MyData> resp = webClient.method(HttpMethod.GET).uri("api/getHeader?id={id}&name={name}", 123, "abc") .retrieve() .bodyToMono(MyData.class); MyData data = resp.block(); System.out.println("WebGetDemo result----- " + data.getString()); } catch (Exception e) { e.printStackTrace(); } } @Test public void WebPostDemo() { MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(2); formData.add("id", "456"); formData.add("name", "xyz"); Mono<MyData> response = webClient.method(HttpMethod.POST).uri("/api/getPost") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .body(BodyInserters.fromFormData(formData)) .retrieve() .bodyToMono(MyData.class).timeout(Duration.of(10, ChronoUnit.SECONDS)); System.out.println(response); MyData data = response.block(); System.out.println("WebPostDemo result----- " + data.getString()); } @Test public void WebPostJson() { MyData requestData = new MyData(); requestData.setId(789); requestData.setName("lmn"); Mono<MyData> response = webClient.post().uri("/api/getPostJson") .contentType(MediaType.APPLICATION_JSON_UTF8) .syncBody(requestData) .retrieve() .bodyToMono(MyData.class).timeout(Duration.of(10, ChronoUnit.SECONDS)); MyData data = response.block(); System.out.println("WebPostJson result----- " + data.getString()); } }
相关文章
- spring boot: EL和资源 (一般注入说明(二) @Service注解 @Component注解)
- spring与jdbc整合
- Spring Boot 开发集成 WebSocket,实现私有即时通信系统
- Spring Boot 整合 Log4j2 日志并压测性能
- Spring -- 配置bean
- spring boot properties 编码问题[四]
- spring boot: 用thymeleaf嵌套循环展示多层数据(spring boot 2.3.2)
- spring boot2X整合Consul一服务注册与发现
- [Spring学习笔记 5 ] Spring AOP 详解1
- 【收藏】Spring Boot自定义启动Banner在线生成工具
- Netweaver的端口号和Spring boot内嵌的Tomcat端口
- 一种Java Spring框架里将配置文件里定义的值注入到Java变量的简单办法
- spring boot热部署 -- 实现 后端java热更新 -- 详细操作 【idea 的 JRebel破解】
- Spring Boot 项目访问依赖 jar 包内部的资源文件的路径问题详解
- What is Spring Boot? Autoconfigurations In-Depth
- 毕业设计 Spring Boot的中药店商城系统(含源码+论文)
- 毕业设计 Spring Boot的运动健身管理系统(含源码+论文)
- 毕业设计 Spring Boot的汽车租赁系统(含源码+论文)
- Spring Boot系列——AOP配自定义注解的最佳实践
- 001-Spring Cloud Edgware.SR3 升级最新 Finchley.SR1,spring boot 1.5.9.RELEASE 升级2.0.4.RELEASE注意问题点
- Spring Boot Actuator
- 【项目实战】基于netty-websocket-spring-boot-starter实现WebSocket服务器长链接处理
- 【Spring Boot】SpringBoot项目jar、war包启动解析
- 【java】Spring Boot --spring boot项目整合xxl-job