当前位置: 首页 > news >正文

Spring6.0新特性-HTTP接口:使用@HttpExchange实现更优雅的Http客户端

文章目录

  • 一、概述
  • 二、使用
    • 1、创建接口@HttpExchange方法
    • 2、创建一个在调用方法时执行请求的代理
    • 3、方法参数
    • 4、返回值
    • 5、错误处理
      • (1)为RestClient
      • (2)为WebClient
      • (3)为RestTemplate
  • 注意

一、概述

官方文档:https://docs.spring.io/spring-framework/reference/6.1/integration/rest-clients.html#rest-http-interface

Spring6.0推出了新的HTTP接口(类似Openfeign,但是无法做到根据微服务名称进行负载均衡),Spring框架允许您将HTTP服务定义为Java接口@HttpExchange方法。
可以将这样的接口传递给HttpServiceProxyFactory创建通过HTTP客户端执行请求的代理,例如RestClient或者WebClient。
也可以从实现接口@Controller用于服务器请求处理。

二、使用

1、创建接口@HttpExchange方法

interface RepositoryService {@GetExchange("/repos/{owner}/{repo}")Repository getRepository(@PathVariable String owner, @PathVariable String repo);// more HTTP exchange methods...}

2、创建一个在调用方法时执行请求的代理

// 为RestClient
RestClient restClient = RestClient.builder().baseUrl("https://api.github.com/").build();
// 适配
RestClientAdapter adapter = RestClientAdapter.create(restClient);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();
// 构建接口的代理,可以注册为Bean,直接调用
RepositoryService service = factory.createClient(RepositoryService.class);
// 为WebClient
WebClient webClient = WebClient.builder().baseUrl("https://api.github.com/").build();
WebClientAdapter adapter = WebClientAdapter.create(webClient);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();RepositoryService service = factory.createClient(RepositoryService.class);
// 为RestTemplate 
RestTemplate restTemplate = new RestTemplate();
restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory("https://api.github.com/"));
RestTemplateAdapter adapter = RestTemplateAdapter.create(restTemplate);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();RepositoryService service = factory.createClient(RepositoryService.class);
// @HttpExchange在类型级别受支持,它适用于所有方法
@HttpExchange(url = "/repos/{owner}/{repo}", accept = "application/vnd.github.v3+json")
interface RepositoryService {@GetExchangeRepository getRepository(@PathVariable String owner, @PathVariable String repo);@PatchExchange(contentType = MediaType.APPLICATION_FORM_URLENCODED_VALUE)void updateRepository(@PathVariable String owner, @PathVariable String repo,@RequestParam String name, @RequestParam String description, @RequestParam String homepage);}

3、方法参数

带注解的HTTP交换方法支持具有以下方法参数的灵活方法签名
在这里插入图片描述

4、返回值

支持的返回值取决于底层客户端。

客户适应HttpExchangeAdapter诸如RestClient和RestTemplate支持同步返回值:
在这里插入图片描述

客户响应ReactorHttpExchangeAdapter诸如WebClient,支持上述所有功能以及反应性变体。下表显示了反应器类型,但是也可以使用通过ReactiveAdapterRegistry:
在这里插入图片描述
默认情况下,同步返回值与ReactorHttpExchangeAdapter取决于底层HTTP客户端的配置。您可以设置一个blockTimeout值,但是我们建议依赖底层HTTP客户机的超时设置,它在较低的级别上运行并提供更多的控制。

5、错误处理

要定制错误响应处理,您需要配置底层HTTP客户端。

(1)为RestClient

默认情况下,RestClient抛出RestClientException对于4xx和5xx HTTP状态代码。要对此进行自定义,请注册一个适用于通过客户端执行的所有响应的响应状态处理程序:

RestClient restClient = RestClient.builder().defaultStatusHandler(HttpStatusCode::isError, (request, response) -> ...).build();RestClientAdapter adapter = RestClientAdapter.create(restClient);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();

有关更多详细信息和选项(如取消错误状态代码),请参见的JavadocdefaultStatusHandlerRestClient.Builder

(2)为WebClient

默认情况下,WebClient抛出WebClientResponseException对于4xx和5xx HTTP状态代码。要对此进行自定义,请注册一个适用于通过客户端执行的所有响应的响应状态处理程序:

WebClient webClient = WebClient.builder().defaultStatusHandler(HttpStatusCode::isError, resp -> ...).build();WebClientAdapter adapter = WebClientAdapter.create(webClient);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builder(adapter).build();

(3)为RestTemplate

默认情况下,RestTemplate抛出RestClientException对于4xx和5xx HTTP状态代码。要对此进行自定义,请注册一个适用于通过客户端执行的所有响应的错误处理程序:

RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(myErrorHandler);RestTemplateAdapter adapter = RestTemplateAdapter.create(restTemplate);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();

有关更多详细信息和选项,请参见的JavadocsetErrorHandler在RestTemplate和ResponseErrorHandler等级制度。

注意

  1. HttpEntity标题和正文必须提供给RestClient通过headers(Consumer<HttpHeaders>)和body(Object).
  2. RequestEntity方法、URI、标头和正文必须提供给RestClient通过method(HttpMethod), uri(URI), headers(Consumer<HttpHeaders>)body(Object).
http://www.lryc.cn/news/523006.html

相关文章:

  • springboot医院信管系统
  • 迅为RK3568开发板篇OpenHarmony实操HDF驱动控制LED-编写内核 LED HDF 驱动程序
  • [javaWeb]初识Web
  • 复健第二天之[MoeCTF 2022]baby_file
  • uniapp 微信小程序 editor 富文本编辑器
  • SparkSQL函数
  • 从零开始学数据库 day2 DML
  • 电脑换固态硬盘
  • 【大数据】机器学习------支持向量机(SVM)
  • Android系统开发(八):从麦克风到扬声器,音频HAL框架的奇妙之旅
  • Golang Gin系列-2:搭建Gin 框架环境
  • FGC_grasp复现
  • 实力认证 | 海云安入选《信创安全产品及服务购买决策参考》
  • Avalonia系列文章之小试牛刀
  • 中国数字安全产业年度报告(2024)
  • LabVIEW桥接传感器配置与数据采集
  • 简明docker快速入门并实践方法
  • 《MambaIR:一种基于状态空间模型的简单图像修复基线方法》学习笔记
  • 链式前向星的写法
  • 【逆境中绽放:万字回顾2024我在挑战中突破自我】
  • 尺取法(算法优化技巧)
  • 基于 K-Means 聚类分析实现人脸照片的快速分类
  • 【漏洞预警】FortiOS 和 FortiProxy 身份认证绕过漏洞(CVE-2024-55591)
  • 7.5.4 MVCC优化测试
  • STM32 FreeRTOS 事件标志组
  • 生成树机制实验
  • 企业分类相似度筛选实战:基于规则与向量方法的对比分析
  • 2024年博客之星年度评选—创作影响力评审入围名单公布
  • 递归40题!再见递归
  • 社区版Dify实现文生视频 LLM+ComfyUI+混元视频