网站首页 > java教程 正文
我们在日常开发中,经常会需要远程调用其他服务提供的接口,比较常用的 HTTP 远程代理框架有OpenFeign、Retrofit以及一些第三方封装工具类,例如Hutool提供的HttpUtil。
11月24日,Spring Boot 3正式发布,Spring官方已经自身支持使用声明式服务调用的方式来调用远程接口。
虽然类似的远程调用框架如OpenFeign和Retrofit仍然可以使用,但HttpServiceProxyFactory增加了对 Spring 框架的原生支持。如果Spring本身可以做到远程调用的话,这些大量的第三方库应该很快会被原生方法取代,我们今天来了解一下这个新特征。
声明式 Http 接口
声明性 HTTP 接口可以让你像定义Java接口那样定义HTTP服务,用法和你平时写Controller中方法完全一致。
引入
声明性 HTTP 接口功能是spring-web依赖项的一部分,使用前必须引入如下依赖包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- For reactive support -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
创建 HTTP 服务接口
在 Spring 中,HTTP 服务接口是一个带有@HttpExchange方法的 Java 接口。注释方法被视为 HTTP 端点,细节通过注释属性和输入方法参数类型静态定义。
支持的注解类型
- @HttpExchange:是用于指定 HTTP 端点的通用注释。在接口级别使用时,它适用于所有方法。
- @GetExchange:为 HTTP GET请求指定@HttpExchange。
- @PostExchange:为 HTTP POST请求指定@HttpExchange。
- @PutExchange:为 HTTP PUT请求指定@HttpExchange。
- @DeleteExchange:为 HTTP DELETE请求指定@HttpExchange。
- @PatchExchange:为 HTTP PATCH请求指定@HttpExchange。
方法参数
返回值
声明性 HTTP 接口支持以下返回值:
使用示例
@PutExchange
void update(@PathVariable Long id, @RequestBody User user);
完整使用案例
我们以一个简单的用户信息请求为例
0、构建HttpServiceProxyFactory:
HttpServiceProxyFactory是一个从 HTTP 服务接口创建客户端代理的工厂类。使用HttpServiceProxyFactory.builder(client).build()方法来获取代理 bean 的实例。
import com.fasterxml.jackson.databind.ObjectMapper;
import com.howtodoinjava.app.web.UserClient;
import lombok.SneakyThrows;
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
WebClient webClient(ObjectMapper objectMapper) {
return WebClient.builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.build();
}
@SneakyThrows
@Bean
UserClient postClient(WebClient webClient) {
HttpServiceProxyFactory httpServiceProxyFactory =
HttpServiceProxyFactory.builder(WebClientAdapter.forClient(webClient))
.build();
return httpServiceProxyFactory.createClient(UserClient.class);
}
}
1、定义一个简单的用户信息实体类:
public class User {
private int id;
private String username;
private String password;
// 省略
}
2、请求接口:
import com.howtodoinjava.app.model.User;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.service.annotation.DeleteExchange;
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.annotation.HttpExchange;
import org.springframework.web.service.annotation.PostExchange;
import org.springframework.web.service.annotation.PutExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@HttpExchange(url = "/users", accept = "application/json", contentType = "application/json")
public interface UserClient {
@GetExchange("/")
Flux<User> getAll();
@GetExchange("/{id}")
Mono<User> getById(@PathVariable("id") Long id);
@PostExchange("/")
Mono<ResponseEntity<Void>> save(@RequestBody User user);
@PutExchange("/{id}")
Mono<ResponseEntity<Void>> update(@PathVariable Long id, @RequestBody User user);
@DeleteExchange("/{id}")
Mono<ResponseEntity<Void>> delete(@PathVariable Long id);
}
3、将UserClient bean 注入应用程序类并调用方法来获取 API 响应:
@Autowired
UserClient userClient;
//Get All Users
userClient.getAll().subscribe(
data -> log.info("User: {}", data)
);
//Get User By Id
userClient.getById(1L).subscribe(
data -> log.info("User: {}", data)
);
//Create a New User
userClient.save(new User(null, "Lokesh", "lokesh", "admin@email.com"))
.subscribe(
data -> log.info("User: {}", data)
);
//Delete User By Id
userClient.delete(1L).subscribe(
data -> log.info("User: {}", data)
);
完工,不需要定义方法实现就能进行远程HTTP调用,非常方便!
扩展
1、Spring Boot3 新特征一览:
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-3.0-Release-Notes
2、文章相关代码:
https://github.com/lokeshgupta1981/Spring-Boot3-Demos/tree/main/declarative-http-client-example
3、Spring官方文档介绍:
https://docs.spring.io/spring-framework/docs/6.0.0-RC1/reference/html/integration.html#rest-http-interface
原文链接:
https://mp.weixin.qq.com/s/olB4VkuZMMkZ6fVAhyKo-g
猜你喜欢
- 2025-07-08 对Spring MVC接口进行Mock测试(springmvc对外接口)
- 2025-07-08 还在用策略模式解决 if-else?Map+函数式接口方法才是YYDS
- 2025-07-08 java开发三年,Java中接口的使用你得知道,不然你凭什么涨薪
- 2025-07-08 Java的类与接口(java接口和接口实现类)
- 2025-07-08 如何理解Java中接口存在的意义(java中接口有什么用)
- 2025-07-08 面试:如何保证接口的幂等性?常见的实现方案有哪些?
- 2025-07-08 java实现接口防刷(java接口防刷策略)
- 2025-07-08 java 9新特性 接口方法私有化(java私有属性怎么调用)
- 2025-07-08 妙用Java 8中的 Function接口(java里function的作用)
- 2025-07-08 调用AI接口API,需要遵循以下步骤
你 发表评论:
欢迎- 最近发表
-
- 搞趣网:我的世界全新皮肤包原始居民下载地址
- 我的世界拔刀剑MOD下载(我的世界拔刀剑mod下载国际版)
- 我的世界无正版账号的简单联机方法(非网易版,仅适用于局域网)
- 一些可以显著提高大型 Java 项目启动速度的尝试
- 常见的java敏感异常介绍(java 常见的异常)
- Java 开发者必看!三招实现外部 Jar 包动态加载(含热更新方案)
- Java JAR 启动内存参数配置指南:从基础设置到性能优化
- 对Spring MVC接口进行Mock测试(springmvc对外接口)
- 还在用策略模式解决 if-else?Map+函数式接口方法才是YYDS
- 干掉OpenFeign,SpringBoot 3.0 自带的 HTTP 客户端真香!
- 标签列表
-
- java反编译工具 (77)
- java反射 (57)
- java接口 (61)
- java随机数 (63)
- java7下载 (59)
- java数据结构 (61)
- java 三目运算符 (65)
- java对象转map (63)
- Java继承 (69)
- java字符串替换 (60)
- 快速排序java (59)
- java并发编程 (58)
- java api文档 (60)
- centos安装java (57)
- java调用webservice接口 (61)
- java深拷贝 (61)
- 工厂模式java (59)
- java代理模式 (59)
- java.lang (57)
- java连接mysql数据库 (67)
- java重载 (68)
- java 循环语句 (66)
- java反序列化 (58)
- java时间函数 (60)
- java是值传递还是引用传递 (62)
本文暂时没有评论,来添加一个吧(●'◡'●)