资讯动态

spring boot3.0新特性Http客户端远程调用,http客户端调用接口

发布时间:2026/10/18 2:29:25 来源:尧图企业网站定制
1、安装依赖!-- For reactive support -- dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-webflux/artifactId /dependency2、项目结构3、新建配置类WebConfigpackage com.example.fire_web_manage.system_config.config; import com.example.fire_web_manage.system_config.rest_service.ControlLogicClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.reactive.function.client.WebClient; import org.springframework.web.reactive.function.client.support.WebClientAdapter; import org.springframework.web.service.invoker.HttpServiceProxyFactory; Configuration public class WebConfig { Bean UserClient postClient() { WebClient webClientcreateWebClient(http://localhost:8080); HttpServiceProxyFactory httpServiceProxyFactoryHttpServiceProxyFactory.builderFor(WebClientAdapter.create(webClient)).build(); return httpServiceProxyFactory.createClient(UserClient.class); } private WebClient createWebClient(String baseUrl) { return WebClient.builder() .baseUrl(baseUrl) .filter((request, next) - { //如果有鉴权验证的话这个地方是获取token用的代码是示例可以更换成自己的逻辑 if (!request.url().getPath().contains(/api/user/login) StringUtils.isNotBlank(tokenHolder.getSlopeToken())) { request ClientRequest.from(request) .header(Authorization, tokenHolder.getSlopeToken()) .build(); } return next.exchange(request); }) .build(); } }4、新建Http客户接口UserClientpackage com.example.springboot3.client; import org.springframework.web.service.annotation.GetExchange; import org.springframework.web.service.annotation.HttpExchange; HttpExchange(accept application/json, contentType application/json) public interface UserClient { GetExchange(/dubboTest) String getAllTest(); }5、controller测试接口package com.example.springboot3.controller; import com.example.springboot3.client.UserClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; RestController public class TestController { Autowired UserClient userClient; GetMapping(/test) public String test(){ return userClient.getAllTest(); } }6、调用的方式HttpExchange:是指定HTTP端点的通用注释。当在接口级别使用时它适用于所有方法。GetExchange:为HTTP GET请求指定HttpExchange。PostExchange:对于HTTP POST请求指定HttpExchange。PutExchange:为HTTP PUT请求指定HttpExchange。DeleteExchange:对于HTTP DELETE请求指定HttpExchange。PatchExchange:对于HTTP Patch请求指定HttpExchange。7、传递参数格式PathVariable:将请求URL中的值替换为占位符。RequestBody:提供请求的主体。RequestParam:添加请求参数。当“content-type”设置为“application/x-www-form-urlencoded”时请求参数会在请求体中编码。否则它们将作为URL查询参数添加。 requesttheader:添加请求头的名称和值。RequestPart:可用于添加请求部分(表单字段资源或HttpEntity等)。CookieValue:向请求中添加cookie。

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价 →
↑