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.mzph.cn/diannao/54918.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Redis篇(应用案例 - 商户查询缓存)

目录 一、什么是缓存? 二、为什么要使用缓存 三、如何使用缓存 四、添加商户缓存 1. 缓存模型和思路 2. 代码如下 五、缓存更新策略 1. 内存淘汰 2. 超时剔除 3. 主动更新 六、数据库缓存不一致解决方案 1. 数据库缓存不一致解决方案 2. 数据库和缓存不一致采用什…

《关于浔川 AI 翻译 v3.0 延迟上线的通告》——浔川社团官方

尊敬的用户&#xff1a; 您好&#xff01; 首先&#xff0c;我们要向一直以来期待浔川 AI 翻译 v3.0 上线的各位用户致以最诚挚的歉意。原定于 [2024.9.19] 上线的浔川 AI 翻译 v3.0&#xff0c;由于 [安装失败原因]&#xff0c;将再次延迟至 2024 年 10 月 2 日上线。 我们…

AMD ROCm™ 安装指南

AMD ROCm™ installation — ROCm Blogs 注意: 本文之前是 AMD 实验笔记博客系列的一部分。 AMD ROCm™ 是第一个面向 HPC/超大规模级 GPU 计算的开源软件开发平台。AMD ROCm™ 将 UNIX 的选择权、极简主义和模块化软件开发哲学引入 GPU 计算领域。有关更多信息&#xff0c;请参…

【MySQL】函数及存储过程

MySQL函数和存储过程 函数 数据库中的函数是一种可重复使用的命名代码块&#xff0c;用于在数据库中执行特定的操作或计算。 在MySQL中提供了很多函数&#xff0c;为我们的SQL提供了便利 内置函数 mysql> select count(r_id),max(r_id),min(r_id),avg(r_id) from resume…

docker build 有时候不展示命令的输出情况,怎么办?

来源&#xff1a;https://stackoverflow.com/questions/64804749/why-is-docker-build-not-showing-any-output-from-commands docker build 有时候不展示命令的输出情况&#xff0c;不方便我们 debug&#xff0c;怎么办&#xff1f; 可以加上 docker build --progressplain …

C++和OpenGL实现3D游戏编程【连载10】——纹理的半透明显示

1、本节实现的内容 上一节课我们讲到了图片的镂空显示,它能在显示图片时去除指定颜色的背景,那么这节课我们来说一下图片的半透明显示效果,半透明效果能给画面带来更高质量的提升,使图片显示的更自然,产生更真实的效果。下面是一个气泡向上漂浮的效果。 气泡效果 2、非纹…

2024华为OD机试E卷-判断一组不等式是否满足约束并输出最大差-(C++/Java/Python)

2024华为OD机试最新E卷题库-(C卷+D卷+E卷)-(JAVA、Python、C++) 目录 题目描述 输入描述 输出描述 用例1 用例2 考点分析 题目解析 代码 c++ python java 题目描述 给定一组不等式,判断是否成立并输出不等式的最大差(输出浮点数的整数部分) 要求: 不等式系数为…

搜索引擎简介

搜索引擎架构 整个搜索引擎分为三个系统 爬虫系统 索引系统 线上搜素服务 爬虫系统 爬虫分为两个阶段&#xff1a; 第一阶段&#xff1a;根据目标网站的列表页&#xff0c;爬对应的文档 URL 第二阶段&#xff1a;根据文档 URL&#xff0c;下载文档内容 触发器&#xff1…

【行业报告】AI大模型对我国劳动力市场潜在影响研究报告(2024),附PDF下载!!

前言 9月13日&#xff0c;北京大学国家发展研究院联合智联招聘在中国国际服务贸易交易会上发布的《AI大模型对我国劳动力市场潜在影响研究&#xff1a;2024》&#xff08;以下简称“报告”&#xff09;显示&#xff0c;2024年上半年&#xff0c;招聘职位数同比增速前五的人工智…

数据结构——二叉树的性质和存储结构

二叉树的抽象类型定义 基本操作&#xff1a; CreateBiTree(&T&#xff0c;definition) 初始条件&#xff1a;definition给出二叉树T的定义。 操作结果:按definition构造二叉树T。 PreOrderTraverse(T) 初始条件:二叉树T存在。 操作结果:先序遍历T&#xff0c;对每个结…

基于Hive和Hadoop的白酒分析系统

本项目是一个基于大数据技术的白酒分析系统&#xff0c;旨在为用户提供全面的白酒市场信息和深入的价格分析。系统采用 Hadoop 平台进行大规模数据存储和处理&#xff0c;利用 MapReduce 进行数据分析和处理&#xff0c;通过 Sqoop 实现数据的导入导出&#xff0c;以 Spark 为核…

LLM | Ollama WebUI 安装使用(pip 版)

Open WebUI (Formerly Ollama WebUI) 也可以通过 docker 来安装使用 1. 详细步骤 1.1 安装 Open WebUI # 官方建议使用 python3.11&#xff08;2024.09.27&#xff09;&#xff0c;conda 的使用参考其他文章 conda create -n open-webui python3.11 conda activate open-web…

Java五子棋

目录 一&#xff1a;案例要求&#xff1a; 二&#xff1a;代码&#xff1a; 三&#xff1a;结果&#xff1a; 一&#xff1a;案例要求&#xff1a; 实现一个控制台下五子棋的程序。用一个二维数组模拟一个15*15路的五子棋棋盘&#xff0c;把每个元素赋值位“┼”可以画出棋…

不夸张、我就是这样考过PMP~

&#x1f335;方法虽然有点笨&#xff0c;但是按照这个方法认真学&#xff0c;60天过PMP真的来得及&#xff01;PMP是通过性考试&#xff0c;只要拿下及格分就行&#xff0c;选对学习方法两个月3A上岸稳稳的&#xff01;&#x1f53a;24年11月PMP考试时间&#xff1a;11月30日&…

通过OpenScada在ARMxy边缘计算网关上实现数字化转型

随着工业4.0概念的普及&#xff0c;数字化转型已成为制造业升级的关键路径之一。在此背景下&#xff0c;边缘计算技术因其能够有效处理大量数据、减少延迟并提高系统响应速度而受到广泛关注。ARMxy边缘计算网关&#xff0c;特别是BL340系列&#xff0c;凭借其强大的性能和灵活的…

SQL高可用优化-优化SQL中distinct和Where条件对索引字段进行非空检查语句

最近做一个需求&#xff0c;关于SQL高可用优化&#xff0c;需要优化项目中的SQL&#xff0c;提升查询效率。 SQL高可用优化 一、优化SQL包含distinct场景二、优化SQL中Where条件中索引字段是否为NULL三、代码验证1. NodeMapper2. NodeService3. NodeController4.数据库数据5.项…

SPI总结

1.前言 1.1 SPI简介 SPI全称Serial Peripheral Interface&#xff0c;串行外设接口&#xff0c;是一种用于连接外设的全双工通信总线。主机和从机支持一对一或一对多通讯连接。 图1 SPI物理层通讯连接 表1 Signal description 1.2 SPI特征 串行&#xff0c;每个时钟周期只传…

RM服务器研究(一)

客户端默认端口是10100&#xff1a; MultiPort.dll BOOL sub_10001070() { UINT v0; // esi BOOL result; // eax CHAR KeyName; // [espCh] [ebp-10Ch] DWORD flOldProtect; // [esp10h] [ebp-108h] CHAR Buffer; // [esp14h] [ebp-104h] char v5; // [esp15h] [e…

每日论文6—16ISCAS一种新型低电流失配和变化电流转向电荷泵

《A Novel Current Steering Charge Pump with Low Current Mismatch and Variation》16ISCAS 本文首先介绍了传统的current steering charge pump&#xff0c;如下图&#xff1a; 比起最简单的电荷泵&#xff0c;主要好处是UP和DN开关离输出节点较远&#xff0c;因此一定程度…

linux中怎么一次提交多条命令

在Linux上&#xff0c;如果你想要多条命令一起运行&#xff0c;有几种方式可以实现&#xff0c;但具体使用哪种方式取决于你希望这两条命令如何并行或顺序执行。 1、顺序执行&#xff1a;如果你希望第一条命令执行完毕后&#xff0c;再执行第二条命令&#xff0c;你可以简单地…