0


Spring Boot 中调用外部接口的 3 种方式

💧 简介

  SpringBoot不仅继承了Spring框架原有的优秀特性,而且还通过简化配置来进一步简化了Spring应用的整个搭建和开发过程。在Spring-Boot项目开发中,存在着本模块的代码需要访问外面模块接口,或外部url链接的需求。
  调用外部接口是指在应用程序中与其他系统、服务或服务端点进行通信,以获取数据或执行某些操作。这种通信可以通过 HTTP、HTTPS、SOAP、gRPC 等协议来实现。

调用外部接口通常涉及以下几个步骤:

  1. 创建请求:根据接口文档或约定,构造请求的 URL、请求方法(如 GET、POST、PUT、DELETE 等)、请求头、请求参数等信息。
  2. 发送请求:使用合适的客户端工具(如 RestTemplate、WebClient、Feign 等)发送请求。这些工具提供了便捷的 API 来发送请求并将响应结果返回给你。
  3. 处理响应:根据接口的响应格式(如 JSON、XML 等),解析响应内容并提取需要的数据。你可以使用解析库(如 Jackson、Gson、JAXB 等)来处理响应内容。
  4. 错误处理:在调用外部接口时,可能会遇到各种错误情况,如网络连接失败、接口返回错误码等。你需要适当处理这些错误情况,例如进行重试、回退、记录日志等操作。

在调用外部接口时,还需要注意以下事项:

  1. 接口安全性:如果接口需要身份验证或授权,你需要提供相应的凭据(如 API 密钥、令牌)或配置安全设置,以确保请求能够被正确处理。
  2. 异步调用和并发性:如果你的应用程序需要高并发或异步处理,你可以考虑使用基于消息队列、异步任务或多线程等技术,在后台进行接口调用,以提高系统的性能和可伸缩性。
  3. 监控和日志记录:对于重要的接口调用,建议设置适当的监控和日志记录,以便及时发现问题并进行故障排查。

总之,调用外部接口是实现应用程序与其他系统集成的重要方式,它能够使你的应用程序获取到外部数据,实现复杂的业务逻辑,并与其他系统进行交互。选择合适的调用方式和合理处理错误情况,能够保证接口调用的可靠性和性能。

💧 方案一:采用原生的httpClient请求

/**
 1. 跨域请求工具类
 */publicclassHttpClientUtils{publicstaticStringdoGet(String url,Map<String,String> param){// 创建Httpclient对象CloseableHttpClient httpclient =HttpClients.createDefault();String resultString ="";CloseableHttpResponse response =null;try{// 创建uriURIBuilder builder =newURIBuilder(url);if(param !=null){for(String key : param.keySet()){
                    builder.addParameter(key, param.get(key));}}URI uri = builder.build();// 创建http GET请求HttpGet httpGet =newHttpGet(uri);// 执行请求
            response = httpclient.execute(httpGet);// 判断返回状态是否为200if(response.getStatusLine().getStatusCode()==200){
                resultString =EntityUtils.toString(response.getEntity(),"UTF-8");}}catch(Exception e){
            e.printStackTrace();}finally{try{if(response !=null){
                    response.close();}
                httpclient.close();}catch(IOException e){
                e.printStackTrace();}}return resultString;}publicstaticStringdoGet(String url){returndoGet(url,null);}publicstaticStringdoPost(String url,Map<String,String> param){// 创建Httpclient对象CloseableHttpClient httpClient =HttpClients.createDefault();CloseableHttpResponse response =null;String resultString ="";try{// 创建Http Post请求HttpPost httpPost =newHttpPost(url);// 创建参数列表if(param !=null){List<NameValuePair> paramList =newArrayList<>();for(String key : param.keySet()){
                    paramList.add(newBasicNameValuePair(key, param.get(key)));}// 模拟表单UrlEncodedFormEntity entity =newUrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);}// 执行http请求
            response = httpClient.execute(httpPost);
            resultString =EntityUtils.toString(response.getEntity(),"utf-8");}catch(Exception e){
            e.printStackTrace();}finally{try{
                response.close();}catch(IOException e){
                e.printStackTrace();}}return resultString;}publicstaticStringdoPost(String url){returndoPost(url,null);}publicstaticStringdoPostJson(String url,String json){// 创建Httpclient对象CloseableHttpClient httpClient =HttpClients.createDefault();CloseableHttpResponse response =null;String resultString ="";try{// 创建Http Post请求HttpPost httpPost =newHttpPost(url);// 创建请求内容StringEntity entity =newStringEntity(json,ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);// 执行http请求
            response = httpClient.execute(httpPost);
            resultString =EntityUtils.toString(response.getEntity(),"utf-8");}catch(Exception e){
            e.printStackTrace();}finally{try{
                response.close();}catch(IOException e){
                e.printStackTrace();}}return resultString;}}

💧 方案二:采用原生的RestTemplate方法

  RestTemplate 是 Spring 框架提供的用于访问 RESTful 服务的客户端工具类。它封装了常见的 HTTP 请求操作,提供了简单易用的 API,这里主要介绍Get和Post方法的使用。

🌀 Get请求

  在 RestTemplate 中,getForEntity 方法有多个重载形式,可以根据需要选择合适的方法进行 GET 请求。提供了getForObject 、getForEntity两种方式。

🔥 getForEntity

以下是

getForEntity

方法的三种形式:

1.getForEntity(String url,Class<T> responseType,Object... uriVariables);2.getForEntity(String url,Class<T> responseType,Map<String,?> uriVariables);3.getForEntity(URI url,Class<T> responseType);

以下是对每个方法的说明和示例:

  1. getForEntity(String url, Class<T> responseType, Object... uriVariables): 该方法提供了三个参数,其中url为请求的地址,responseType为请求响应body的包装类型,urlVariables为url中的参数绑定- 此方法发送带有路径参数的 GET 请求,并以可变参数的形式传递路径参数。- 路径参数将按顺序替换 URL 中的占位符 {}。示例:RestTemplate restTemplate =newRestTemplate();ResponseEntity<User> response = restTemplate.getForEntity("http://example.com/api/users/{id}",User.class,1);User user = response.getBody();
  2. getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables):- 此方法发送带有路径参数的 GET 请求,并以键值对的形式传递路径参数。- 路径参数通过键值对映射进行替换。示例:RestTemplate restTemplate =newRestTemplate();Map<String,Integer> uriVariables =newHashMap<>();uriVariables.put("id",1);ResponseEntity<User> response = restTemplate.getForEntity("http://example.com/api/users/{id}",User.class, uriVariables);User user = response.getBody();
  3. getForEntity(URI url, Class<T> responseType):- 此方法发送 GET 请求,并通过 URI 对象来指定请求的完整 URL。示例:RestTemplate restTemplate =newRestTemplate();URI url =newURI("http://example.com/api/users/1");ResponseEntity<User> response = restTemplate.getForEntity(url,User.class);User user = response.getBody();

或者

RestTemplate restTemplate=newRestTemplate();UriComponents uriComponents=UriComponentsBuilder.fromUriString("http://example.com/api/users/{id}").build().expand(1).encode();URI uri=uriComponents.toUri();ResponseEntity<User> response = restTemplate.getForEntity(uri,User.class);User user = response.getBody();

🔥 getForObject

以下是

getForEntity

方法的三种形式:

1.getForObject(String url,Class<T> responseType,Object... uriVariables);2.getForObject(String url,Class<T> responseType,Map<String,?> uriVariables);3.getForObject(URI url,Class<T> responseType);

这段代码是

RestTemplate

类中的

getForObject

方法的重写实现。它用于发送 GET 请求,并返回一个指定类型的对象,而不是完整的响应实体。

以下是对每个方法的说明和示例:

  1. getForObject(String url, Class<T> responseType, Object... uriVariables):- 此方法发送带有路径参数的 GET 请求,并以可变参数的形式传递路径参数。- 路径参数将按顺序替换 URL 中的占位符 {}。- 最后,返回响应体中转换为指定类型的对象。示例:RestTemplate restTemplate =newRestTemplate();User user = restTemplate.getForObject("http://example.com/api/users/{id}",User.class,1);
  2. getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables):- 此方法发送带有路径参数的 GET 请求,并以键值对的形式传递路径参数。- 路径参数通过键值对映射进行替换。- 最后,返回响应体中转换为指定类型的对象。示例:RestTemplate restTemplate =newRestTemplate();Map<String,Integer> uriVariables =newHashMap<>();uriVariables.put("id",1);User user = restTemplate.getForObject("http://example.com/api/users/{id}",User.class, uriVariables);
  3. getForObject(URI url, Class<T> responseType):- 此方法发送 GET 请求,并通过 URI 对象来指定请求的完整 URL。- 最后,返回响应体中转换为指定类型的对象。示例:RestTemplate restTemplate =newRestTemplate();URI url =newURI("http://example.com/api/users/1");User user = restTemplate.getForObject(url,User.class);

🔥 getForEntity和getForObject的联系

getForObject

getForEntity

RestTemplate

类中用于发送 GET 请求并获取响应的两个方法。它们在功能上有一些相似之处,但也有一些区别。

相同点:

  • 都用于发送 GET 请求,并接收服务器返回的响应。
  • 都支持传递 URL、路径参数和查询参数来构建完整的请求 URL。
  • 都可以指定响应的期望类型,并进行自动的类型转换。

区别:

  • getForObject 方法返回的是服务器响应体中的内容,并将其转换为指定类型的对象。这意味着你直接获取到了响应体的内容。
  • getForEntity 方法返回的是一个 ResponseEntity 对象,包含了完整的响应信息,包括响应头、响应状态码和响应体。可以通过 ResponseEntity 对象来获取更多的响应信息。

选择使用哪个方法取决于你对响应的需求:

  • 如果你只需要获得响应体的内容,并将其转换为指定类型的对象,可以使用 getForObject 方法。这样可以简化代码,仅关注响应体的内容。
  • 如果你还需要获取更多的响应信息,例如响应头或状态码,或者需要对响应进行更细粒度的处理,那么可以使用 getForEntity 方法。它提供了更多的灵活性,可以访问完整的响应信息。

示例:

RestTemplate restTemplate =newRestTemplate();// 使用 getForObject 方法User user1 = restTemplate.getForObject("http://example.com/api/users/1",User.class);// 使用 getForEntity 方法ResponseEntity<User> responseEntity = restTemplate.getForEntity("http://example.com/api/users/1",User.class);User user2 = responseEntity.getBody();HttpStatus statusCode = responseEntity.getStatusCode();HttpHeaders headers = responseEntity.getHeaders();

总之,

getForObject

getForEntity

都是用于发送 GET 请求并获取响应的方法,选择使用哪个方法取决于你对响应的需求。

🌀 Post请求

Post请求提供有

postForEntity

postForObject

postForLocation

三种方式,其中每种方式都有三种方法,下面介绍

postForEntity

的使用方法。

🔥 postForEntity

以下是

postForEntity

方法的三种形式:

1.postForEntity(String url,@NullableObject request,Class<T> responseType,Object... uriVariables);2.postForEntity(String url,@NullableObject request,Class<T> responseType,Map<String,?> uriVariables);3.postForEntity(URI url,@NullableObject request,Class<T> responseType);

这段代码是

RestTemplate

类中的

postForEntity

方法的重写实现。它用于发送 POST 请求,并返回一个包含完整响应信息的

ResponseEntity

对象,而不仅仅是响应体内容。

下面是对每个重写方法的详细说明和示例:

  1. postForEntity(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables):- 此方法发送带有路径参数的 POST 请求,并以可变参数的形式传递路径参数。- request 参数用于发送 POST 请求时的请求体内容。- 最后,返回一个包含完整响应信息的 ResponseEntity 对象,其中包括响应头、响应状态码和响应体。示例:RestTemplate restTemplate =newRestTemplate();User userRequest =newUser("John","Doe");ResponseEntity<User> responseEntity = restTemplate.postForEntity("http://example.com/api/users", userRequest,User.class,1);User user = responseEntity.getBody();HttpStatus statusCode = responseEntity.getStatusCode();HttpHeaders headers = responseEntity.getHeaders();
  2. postForEntity(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables):- 此方法发送带有路径参数的 POST 请求,并以键值对的形式传递路径参数。- request 参数用于发送 POST 请求时的请求体内容。- 最后,返回一个包含完整响应信息的 ResponseEntity 对象。示例:RestTemplate restTemplate =newRestTemplate();User userRequest =newUser("John","Doe");Map<String,Integer> uriVariables =newHashMap<>();uriVariables.put("id",1);ResponseEntity<User> responseEntity = restTemplate.postForEntity("http://example.com/api/users/{id}", userRequest,User.class, uriVariables);User user = responseEntity.getBody();HttpStatus statusCode = responseEntity.getStatusCode();HttpHeaders headers = responseEntity.getHeaders();
  3. postForEntity(URI url, @Nullable Object request, Class<T> responseType):- 此方法发送 POST 请求,并通过 URI 对象来指定请求的完整 URL。- request 参数用于发送 POST 请求时的请求体内容。- 最后,返回一个包含完整响应信息的 ResponseEntity 对象。示例:RestTemplate restTemplate =newRestTemplate();User userRequest =newUser("John","Doe");URI url =newURI("http://example.com/api/users");ResponseEntity<User> responseEntity = restTemplate.postForEntity(url, userRequest,User.class);User user = responseEntity.getBody();HttpStatus statusCode = responseEntity.getStatusCode();HttpHeaders headers = responseEntity.getHeaders();

request

uriVariables

是用于构造 POST 请求的两个不同的参数,它们在不同的作用域中起作用。

  1. request 参数:- request 参数表示发送 POST 请求时的请求体内容。- 它可以是任意类型的对象,根据实际的请求需求来决定具体的类型。通常情况下,request 参数会作为请求体的内容进行发送。- 如果你的 POST 请求不需要请求体,可以将 request 参数设置为 null
  2. uriVariables 参数:- uriVariables 参数表示可选的路径参数,用于替换 URL 中的占位符。- 它是一个可变参数,可以传递多个参数值。参数值的顺序必须与 URL 中占位符的顺序一致。- 在发送 POST 请求时,将路径参数与 URL 进行替换,以获得最终的请求 URL。

综上所述,

request

uriVariables

是两个用于构建 POST
请求不同参数,分别代表请求体的内容和路径参数。需要根据具体的需求来使用它们。如果需要发送请求体,将内容放在

request

参数中;如果需要替换 URL 中的占位符,将参数值传递给

uriVariables

参数。

🔥 postForObject

以下是

postForObject

方法的三种形式:

1.postForObject(String url,@NullableObject request,Class<T> responseType,Object... uriVariables);2.postForObject(String url,@NullableObject request,Class<T> responseType,Map<String,?> uriVariables);3.postForObject(URI url,@NullableObject request,Class<T> responseType);

这是

RestTemplate

类中关于 POST 请求的三个

postForObject

方法的实现。下面将详细解释每个方法及其示例用法:

  1. postForObject(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables)- 通过传递 URL 字符串、请求体对象、响应类型和路径参数数组,发送一个 POST 请求,并将响应体转换为指定的类型对象。- 如果不需要发送请求体,可以将 request 参数设置为 null。- 此方法使用占位符来替换 URL 中的路径参数。示例:String url ="http://example.com/api/users/{id}";User request =newUser("John","Doe");Class<User> responseType =User.class;Object[] uriVariables ={1};User user = restTemplate.postForObject(url, request, responseType, uriVariables);
  2. postForObject(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables)- 通过传递 URL 字符串、请求体对象、响应类型和路径参数映射,发送一个 POST 请求,并将响应体转换为指定的类型对象。- 如果不需要发送请求体,可以将 request 参数设置为 null。- 此方法使用键-值对来替换 URL 中的路径参数。示例:String url ="http://example.com/api/users/{id}";User request =newUser("John","Doe");Class<User> responseType =User.class;Map<String,Object> uriVariables =newHashMap<>();uriVariables.put("id",1);User user = restTemplate.postForObject(url, request, responseType, uriVariables);
  3. postForObject(URI url, @Nullable Object request, Class<T> responseType)- 通过传递完整的 URI 对象、请求体对象和响应类型,发送一个 POST 请求,并将响应体转换为指定的类型对象。- 如果不需要发送请求体,可以将 request 参数设置为 null。- 此方法不支持替换 URL 中的路径参数。示例:URI url =newURI("http://example.com/api/users");User request =newUser("John","Doe");Class<User> responseType =User.class;User user = restTemplate.postForObject(url, request, responseType);

🔥 postForLocation

以下是

postForLocation

方法的三种形式:

1.postForLocation(String url,@NullableObject request,Object... uriVariables);2.postForLocation(String url,@NullableObject request,Map<String,?> uriVariables);3.postForLocation(URI url,@NullableObject request);

这是

RestTemplate

类中关于 POST 请求并获取 Location 头部信息的三个

postForLocation

方法的实现。下面将详细解释每个方法及其示例用法:

  1. postForLocation(String url, @Nullable Object request, Object... uriVariables)- 通过传递 URL 字符串、请求体对象和路径参数数组,发送一个 POST 请求,并返回响应头部中的 Location 信息,作为一个 URI 对象返回。- 如果不需要发送请求体,可以将 request 参数设置为 null。- 此方法使用占位符来替换 URL 中的路径参数。示例:String url ="http://example.com/api/users";User request =newUser("John","Doe");Object[] uriVariables ={1};URI location = restTemplate.postForLocation(url, request, uriVariables);
  2. postForLocation(String url, @Nullable Object request, Map<String, ?> uriVariables)- 通过传递 URL 字符串、请求体对象和路径参数映射,发送一个 POST 请求,并返回响应头部中的 Location 信息,作为一个 URI 对象返回。- 如果不需要发送请求体,可以将 request 参数设置为 null。- 此方法使用键-值对来替换 URL 中的路径参数。示例:String url ="http://example.com/api/users";User request =newUser("John","Doe");Map<String,Object> uriVariables =newHashMap<>();uriVariables.put("id",1);URI location = restTemplate.postForLocation(url, request, uriVariables);
  3. postForLocation(URI url, @Nullable Object request)- 通过传递完整的 URI 对象和请求体对象,发送一个 POST 请求,并返回响应头部中的 Location 信息,作为一个 URI 对象返回。- 如果不需要发送请求体,可以将 request 参数设置为 null。- 此方法不支持替换 URL 中的路径参数。示例:URI url =newURI("http://example.com/api/users");User request =newUser("John","Doe");URI location = restTemplate.postForLocation(url, request);

🔥 postForEntity、postForObject和postForLocation的联系

postForEntity

postForObject

postForLocation

都是

RestTemplate

类中用于发送 POST 请求的方法,它们之间存在一些联系和区别。

联系:

  1. 参数:这三个方法都接受相同的参数:请求的 URL、请求体对象以及可选的路径参数或路径参数映射。
  2. HTTP 请求方法:这三个方法都使用 POST 方法发送请求。

区别:

  1. 返回值类型:- postForEntity 返回一个 ResponseEntity 对象,包含完整的响应信息,如响应状态码、头部信息和响应体。- postForObject 返回一个指定的响应体类型的对象,仅包含响应体内容。- postForLocation 仅返回响应头部中的 Location 信息作为一个 URI 对象。
  2. 使用场景:- postForEntitypostForObject 适用于需要处理完整响应信息的情况,可以获取响应状态码、头部信息和响应体,并根据需要进行处理。- postForLocation 适用于只关注响应头部中的 Location 信息的情况,常用于资源的创建和重定向场景。

总结:
这三个方法都用于发送 POST 请求,根据需要返回不同的信息。如果需要完整的响应信息,包括响应状态码、头部信息和响应体,可以使用

postForEntity

;如果只需要响应体内容,可以使用

postForObject

;如果仅关注响应头部中的 Location 信息,可以使用

postForLocation

💧 方案三:使用Feign进行消费

Feign 是一个声明式的、基于接口的 HTTP 客户端,它简化了使用 Spring Cloud 进行远程服务调用的过程。通过 Feign,可以以声明式的方式定义和调用远程服务接口,而无需手动编写实现代码。

在使用 Feign 进行消费时,需要完成以下几个步骤:

  1. 创建 Feign 客户端接口:定义一个接口,使用 @FeignClient 注解指定服务名称和服务地址。该接口中定义了需要调用的远程服务接口的方法及其相关信息,例如 HTTP 方法、URL 路径、请求参数和请求体等。
  2. 启用 Feign 客户端:在 Spring Boot 应用程序的启动类或配置类上添加 @EnableFeignClients 注解,以启用 Feign 客户端功能。
  3. 使用 Feign 客户端接口:通过注入 Feign 客户端接口对象,即可使用该接口中定义的方法进行远程服务调用。Feign 会根据接口定义自动实现具体的调用逻辑,并处理请求和响应。

Feign 的工作原理如下:

  1. 根据 Feign 客户端接口的定义,在运行时动态生成具体的代理类。
  2. 当调用 Feign 客户端接口的方法时,代理类会负责根据方法的元数据(如 HTTP 方法、URL 路径、请求参数等)组装出一个完整的 HTTP 请求。
  3. 发送构建好的 HTTP 请求到目标服务端,进行远程调用。
  4. 目标服务端响应请求后,将响应结果返回给 Feign 客户端。
  5. Feign 客户端根据定义的返回类型,将响应结果转换为相应的对象或数据,并返回给调用方。

Feign 还具备以下特性:

  1. 内置负载均衡:Feign 集成了 Ribbon 负载均衡器,可以在多个服务提供方之间自动进行负载均衡,提高系统的可用性和性能。
  2. 自动服务发现:Feign 可以与服务注册中心(如 Eureka)集成,自动从服务注册中心获取服务地址,避免硬编码服务地址。
  3. 可插拔的编解码器:Feign 支持多种序列化和反序列化方式,如 JSON、XML 等,可以根据需求选择适合的编解码器。
  4. 客户端日志记录:Feign 具备日志记录功能,可以方便地打印出请求和响应的详细信息,便于排查问题和监控性能。

总而言之,Feign 提供了一种简单且优雅的方式来定义和调用远程服务接口,它屏蔽了底层的 HTTP 请求细节,使得远程服务调用更加便捷和灵活。同时,通过与 Spring Cloud 的集成,Feign 还可以享受到负载均衡、服务发现等分布式系统支持。

🔥 具体实现

使用 Feign 进行消费时,需要进行以下步骤:

  1. 添加 Feign 依赖:在项目的构建文件中添加 Feign 相关的依赖,例如 Maven 的 pom.xml 文件:<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency>
  2. 启用 Feign 客户端:在 Spring Boot 应用程序的启动类或配置类上添加 @EnableFeignClients 注解,以启用 Feign 客户端功能。@SpringBootApplication@EnableFeignClients@ComponentScan(basePackages ={"com.definesys.mpaas","com.xdap.*","com.xdap.*"})publicclassMobilecardApplication{publicstaticvoidmain(String[] args){SpringApplication.run(MobilecardApplication.class, args);}}
  3. 创建 Feign 客户端接口:创建一个接口,使用 @FeignClient 注解指定服务名称和服务地址。定义需要调用的 HTTP 方法、URL 路径、请求参数和请求体等信息。例如://此处name需要设置不为空,url需要在.properties中设置,也可直接写url@FeignClient(name ="example-service",url ="${outSide.url}")publicinterfaceExampleClient{@GetMapping("/api/users/{id}")UsergetUser(@PathVariable("id")Long id);@PostMapping("/api/users")UsercreateUser(@RequestBodyUser user);}
  4. 调用 Feign 客户端接口:通过注入 Feign 客户端接口对象,即可使用其定义的方法进行远程服务调用。例如:@RestControllerpublicclassExampleController{privatefinalExampleClient exampleClient;publicExampleController(ExampleClient exampleClient){this.exampleClient = exampleClient;}@GetMapping("/users/{id}")publicUsergetUser(@PathVariableLong id){return exampleClient.getUser(id);}@PostMapping("/users")publicUsercreateUser(@RequestBodyUser user){return exampleClient.createUser(user);}}
  5. 配置 Feign 客户端:可以通过配置文件来配置 Feign 客户端的行为,例如设置连接超时时间、请求重试等。在 application.propertiesapplication.yml 文件中添加相关配置。

以上是使用 Feign 进行消费的基本步骤。Feign 可以根据接口定义自动生成符合服务提供方 API 规范的客户端实现,并且内部集成了负载均衡和服务发现等功能,简化了远程服务调用的过程。

🔥 添加Header解决方法

在使用 Feign 进行远程服务调用时,可以通过添加 Header 来传递额外的请求信息。下面介绍两种常见的方式来添加 Header。

  1. 使用 @RequestHeader 注解:在 Feign 客户端接口的方法参数上使用 @RequestHeader 注解,指定要添加的 Header 的名称和值。例如:@GetMapping("/api/users/{id}")UsergetUser(@PathVariable("id")Long id,@RequestHeader("Authorization")String token);在调用该方法时,将会在请求头中添加一个名为 “Authorization” 的 Header,其值为传入的 token 参数的值。
  2. 使用 Interceptor 拦截器:可以自定义一个 Interceptor 实现 RequestInterceptor 接口,在 apply() 方法中添加需要的 Header。例如:publicclassCustomHeaderInterceptorimplementsRequestInterceptor{@Overridepublicvoidapply(RequestTemplate template){ template.header("Authorization","Bearer your_token");}}然后,在 Feign 客户端接口上使用 @FeignClient 注解的 configuration 属性指定使用的拦截器类。例如:@FeignClient(name ="example-service", url ="http://example.com", configuration =CustomHeaderInterceptor.class)publicinterfaceExampleClient{// ...}这样,在每次使用该 Feign 客户端接口进行远程调用时,都会在请求头中自动添加上述定义的 Header。 以上是两种常见的添加 Header 的方法。根据实际需求和场景,可以选择适合的方式来添加自定义的 Header 信息。

💧 Spring Boot 调用外部接口的三种方式的联系

Spring Boot 调用外部接口的方式有多种,常见的有以下三种方式:RestTemplate、Feign 和 WebClient。它们之间存在一些联系和区别。

  1. RestTemplate:- RestTemplate 是 Spring Framework 提供的传统的 HTTP 客户端工具,在 Spring Boot 中也得到了支持。- 通过 RestTemplate,可以发送 HTTP 请求并接收响应,支持同步调用。- RestTemplate 具有广泛的功能,可以处理各种请求和响应内容,支持自定义编解码、拦截器等功能。- RestTemplate 使用起来相对简单,直接调用其方法即可,适用于简单的接口调用场景。
  2. Feign:- Feign 是基于接口的声明式的 HTTP 客户端,是 Spring Cloud 提供的组件之一。- Feign 在 Spring Boot 中通过 @FeignClient 注解定义和使用。- 通过 Feign,可以以声明式的方式定义远程服务接口,并且 Feign 会自动代理实现具体的调用逻辑,无需手动编写实现代码。- Feign 集成了 Ribbon 负载均衡器和 Eureka 服务注册中心,可以自动进行负载均衡和服务发现。- Feign 更加高级抽象和灵活,适用于需要更多功能和集成分布式系统环境的场景。
  3. WebClient:- WebClient 是 Spring WebFlux 提供的非阻塞的 HTTP 客户端。- WebClient 基于 Reactor 响应式编程模型,能够在异步非阻塞的情况下处理大量并发请求。- WebClient 支持使用函数式编程风格来定义请求和处理响应,可以使用 Mono 和 Flux 处理异步结果。- WebClient 适用于高性能、高并发的场景,并且在 Spring Boot 2.x 中是推荐的方式。

这三种方式在实际使用中有一些联系和区别:

  • RestTemplate 是传统的 HTTP 客户端,使用较为简单,适用于简单的接口调用场景。
  • Feign 是基于接口的声明式客户端,集成了负载均衡和服务发现等功能,适用于分布式系统下的服务调用。
  • WebClient 是非阻塞的 HTTP 客户端,支持异步、响应式编程模型,适用于高并发、高性能的场景。

选择使用哪种方式需要根据具体的需求和场景来决定。在 Spring Boot 中,可以根据项目的特点和要求,灵活选择适合的方式进行外部接口调用。

标签: spring boot java 后端

本文转载自: https://blog.csdn.net/qq_41596778/article/details/131509715
版权归原作者 Wen先森 所有, 如有侵权,请联系我们删除。

“Spring Boot 中调用外部接口的 3 种方式”的评论:

还没有评论