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

Spring Boot 调用外部接口的常用方式!

使用Feign进行服务消费是一种简化HTTP调用的方式,可以通过声明式的接口定义来实现。下面是一个使用Feign的示例,包括设置Feign客户端和调用服务的方法。

添加依赖
首先,请确保你的项目中已经添加了Feign的依赖。如果你使用的是Maven,可以在pom.xml中添加以下依赖(如果使用Spring Boot,通常已经包含了这些依赖):

<dependency>  <groupId>org.springframework.cloud</groupId>  <artifactId>spring-cloud-starter-openfeign</artifactId>  
</dependency>  

以下是完整示例的结构:

主应用类(YourApplication.java):

import org.springframework.boot.SpringApplication;  
import org.springframework.boot.autoconfigure.SpringBootApplication;  
import org.springframework.cloud.openfeign.EnableFeignClients;  @SpringBootApplication  
@EnableFeignClients  
public class YourApplication {  public static void main(String[] args) {  SpringApplication.run(YourApplication.class, args);  }  
}  

Feign客户端接口(UserServiceClient.java):

import org.springframework.cloud.openfeign.FeignClient;  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.RequestParam;  @FeignClient(name = "user-service", url = "http://USER-SERVICE")  
public interface UserServiceClient {  @GetMapping("/user")  String getUserByName(@RequestParam("name") String name);  
}  

服务类(UserService.java):

import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.stereotype.Service;  @Service  
public class UserService {  private final UserServiceClient userServiceClient;  @Autowired  public UserService(UserServiceClient userServiceClient) {  this.userServiceClient = userServiceClient;  }  public String fetchUserByName(String name) {  return userServiceClient.getUserByName(name);  }  
}  

注意事项
Feign的配置:可以通过application.yml或application.properties配置Feign的超时、编码等。
服务发现:如果使用服务发现工具(如Eureka),可以将url参数省略,程序会自动根据服务名称进行调用。
错误处理:请考虑使用Feign提供的错误解码器或自定义的异常处理机制。

WebClient
WebClient是Spring WebFlux提供的非阻塞式HTTP客户端,适用于异步调用。

示例代码:

import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.stereotype.Service;  
import org.springframework.web.reactive.function.client.WebClient;  
import reactor.core.publisher.Mono;  @Service  
public class WebClientService {  private final WebClient webClient;  @Autowired  public WebClientService(WebClient.Builder webClientBuilder) {  this.webClient = webClientBuilder.baseUrl("http://USER-SERVICE").build();  }  public Mono<String> getUser(String username) {  return webClient.get()  .uri("/user?name={username}", username)  .retrieve()  .bodyToMono(String.class);  }  
}  

配置:
在@Configuration类中配置WebClient bean:

import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Configuration;  
import org.springframework.web.reactive.function.client.WebClient;  @Configuration  
public class AppConfig {  @Bean  public WebClient.Builder webClientBuilder() {  return WebClient.builder();  }  
}  

使用hutool

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import java.net.URLEncoder;  
import java.nio.charset.StandardCharsets;  
import java.util.Map;  public class ApiClient {  public String sendPostRequest(String code, String appAccessToken, SocialDetails socialDetails) {  String url = formatUrl(socialDetails.getUrl(), appAccessToken);  String jsonBody = createRequestBody(code);  return executePost(url, jsonBody);  }  private String formatUrl(String baseUrl, String token) {  try {  return String.format(baseUrl, URLEncoder.encode(token, StandardCharsets.UTF_8.toString()));  } catch (Exception e) {  throw new RuntimeException("Error encoding URL", e);  }  }  private String createRequestBody(String code) {  Map<String, String> requestBody = Map.of("code", code);  return JSONUtil.toJsonStr(requestBody);  }  private String executePost(String url, String jsonBody) {  try {  return HttpUtil.post(url, jsonBody);  } catch (Exception e) {  throw new RuntimeException("Failed to execute POST request", e);  }  }  
}
  1. 创建一个 RestTemplate Bean
    在你的 Spring Boot 应用中创建一个 RestTemplate 的 Bean,通常在主类或配置类中:
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Configuration;  
import org.springframework.web.client.RestTemplate;  @Configuration  
public class AppConfig {  @Bean  public RestTemplate restTemplate() {  return new RestTemplate();  }  
}  

创建 RestTemplate 示例
以下是一个简单的服务类,展示如何使用 RestTemplate 发送 GET 和 POST 请求:

import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.stereotype.Service;  
import org.springframework.web.client.RestTemplate;  @Service  
public class ApiService {  @Autowired  private RestTemplate restTemplate;  // 发送 GET 请求  public String getExample() {  String url = "https://baidu.com/posts/1";  return restTemplate.getForObject(url, String.class);  }  // 发送 POST 请求  public String postExample() {  String url = "https://baidu.com/posts";  Post post = new Post("foo", "bar");  return restTemplate.postForObject(url, post, String.class);  }  static class Post {  private String title;  private String body;  public Post(String title, String body) {  this.title = title;  this.body = body;  }  // Getters and Setters (如果需要)  }  
}  

调用示例
通常在一个控制器中调用这个服务:

import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.PostMapping;  
import org.springframework.web.bind.annotation.RestController;  @RestController  
public class ApiController {  @Autowired  private ApiService apiService;  @GetMapping("/get")  public String get() {  return apiService.getExample();  }  @PostMapping("/post")  public String post() {  return apiService.postExample();  }  
}  

http://www.mrgr.cn/news/37470.html

相关文章:

  • 电子版文件怎么盖章
  • Linux当中的权限问题
  • 打造高质量软件架构 - 9大质量属性
  • 新手答疑 | 零基础该怎么学习嵌入式?嵌入式Linux学习路线是什么?嵌入式开发板推荐?
  • SOMEIP_ETS_138: SD_Options_Array_longer_than_message_allows
  • 【Linux】图解详谈HTTPS的安全传输
  • 【数据库】Java 中 MongoDB 使用指南:步骤与方法介绍
  • 程序员成长第一步,从成为开源社区贡献者开始!
  • 【深度学习基础模型】Autoencoders (AE) 详细理解并附实现代码。
  • Postman接口测试工具详解
  • 【AI大模型-文心-思维树解读-仓颉精通之路-1】
  • 助力申报“山东省首台套技术装备”,安畅检测提供第三方检测服务
  • 【C++】STL标准模板库容器set
  • 本地Docker部署高颜值跨平台照片管理软件lmmich并远程上传图片
  • vue2中使用tailwindCss 详细教程
  • 微信网页授权获取用户openid
  • Vue可视化大屏模板
  • 中级职称评审到底需要准备什么材料?
  • 关于液氮罐的液氮补给方式
  • ThreeJs创建球体