服务粉丝

我们一直在努力
当前位置:首页 > 财经 >

替换OpenFeign,Spring 新版本自带的 HTTP 客户端工具来了!

日期: 来源:石杉的架构笔记收集编辑:丛林
「 关注“石杉的架构笔记”,大厂架构经验倾囊相授 

文章来源:【公众号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

欢迎扫码加入儒猿技术交流群,每天晚上20:00都有Java面试、Redis、MySQL、RocketMQ、SpringCloudAlibaba、Java架构等技术答疑分享,更能跟小伙伴们一起交流技术


另外推荐儒猿课堂的9.9元系列课程给您,欢迎加入一起学习~


互联网Java工程师面试突击课
(9.9元专享)

SpringCloudAlibaba零基础入门到项目实战
9.9元专享)

亿级流量下的电商详情页系统实战项目
9.9元专享)

Kafka消息中间件内核源码精讲
9.9元专享)

12个实战案例带你玩转Java并发编程
9.9元专享)

Elasticsearch零基础入门到精通
9.9元专享)

基于Java手写分布式中间件系统实战
9.9元专享)

基于ShardingSphere的分库分表实战课
9.9元专享)

相关阅读

  • 二级上士娶了女上尉

  • 明月出关山,苍茫云海间。欢迎收听西陆夜读“关山月”。二级上士焦嘉禹和助理工程师焦秀芝在3月18日迎来了他们相识十周年的纪念日。回望过去,他们在前进的道路上始终互相鼓励,
  • 自动化网格ETF周报20230325

  • 点击上方『西门吹雪实盘』可关注并“星标”本号。文章仅记录西门个人投资思考和交易,不构成投资建议,作者不收费荐股、不代客理财。“这是西门吹雪的第450篇原创文章”前言西
  • 这类商品税率为零!国务院最新发布

  • 点蓝字关注,不迷路~来源:财政部网站据财政部网站消息,为支持国内煤炭安全稳定供应,国务院关税税则委员会按程序决定,自2023年4月1日至2023年12月31日,继续对煤炭实施税率为
  • 看,太仓乡村的“云”

  • 近日由省委网信办、省农业农村厅等部门联合开展的第二批江苏省数字乡村试点工作地区名单公示太仓入选特色专项试点地区(智慧绿色乡村类)太仓将重点围绕基础设施数字化提档、农

热门文章

  • “复活”半年后 京东拍拍二手杀入公益事业

  • 京东拍拍二手“复活”半年后,杀入公益事业,试图让企业捐的赠品、家庭闲置品变成实实在在的“爱心”。 把“闲置品”变爱心 6月12日,“益心一益·守护梦想每一步”2018年四

最新文章