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.xdnf.cn/news/1548760.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

IDEA 系列产品 下载

准备工作 下载 下载链接&#xff1a;https://www.123865.com/ps/EF7OTd-mbHnH 仅供参考 环境 演示环境&#xff1a; 操作系统&#xff1a;windows10 产品&#xff1a;IntelliJ IDEA 版本&#xff1a;2024.1.2 注意&#xff1a;如果需要其他产品或者版本可以自行下载&#xff0…

虚幻引擎UE5如何云渲染,教程来了

​步骤一&#xff1a;获取云渲染权限 访问渲染101官网&#xff0c;使用云渲码6666进行注册。 下载并安装渲染客户端。 步骤二&#xff1a;设置渲染环境 确保云渲染环境与您的本地环境一致&#xff0c;避免出错。 步骤三&#xff1a;任务提交 完成环境配置后&#xff0c;解析…

【LeetCode】每日一题 2024_9_27 每种字符至少取 K 个(双指针)

前言 每天和你一起刷 LeetCode 每日一题~ LeetCode 启动&#xff01; 题目&#xff1a;每种字符至少取 K 个 代码与解题思路 func takeCharacters(s string, k int) int {// 核心思路&#xff1a;// 题目要求字符串 s 中&#xff0c;每种字符都取至少 k 个// 而且可以从头取…

腾讯一面-LRU缓存

为了设计一个满足LRU&#xff08;最近最少使用&#xff09;缓存约束的数据结构&#xff0c;我们可以使用哈希表&#xff08;HashMap&#xff09;来存储键值对&#xff0c;以便在O(1)时间复杂度内访问任意键。同时&#xff0c;我们还需要一个双向链表&#xff08;Doubly Linked …

excel统计分析(3): 一元线性回归分析

简介 用途&#xff1a;研究两个具有线性关系的变量之间的关系。 一元线性回归分析模型&#xff1a; ab参数由公式可得&#xff1a; 判定系数R2&#xff1a;评估回归模型的拟合效果。值越接近1&#xff0c;说明拟合效果越好&#xff1b;值越接近0&#xff0c;说明拟合效果越…

DC00020基于springboot新闻网站系统java web项目MySQL新闻管理系统

1、项目功能演示 DC00020基于springboot新闻网站系统java web项目MySQL 2、项目功能描述 基于springbootvue新闻网站包括用户和系统管理员两个角色。 2.1 用户功能 1、用户登录、用户注册 2、新闻信息&#xff1a;点赞、点踩、收藏、查看 3、用户分享&#xff1a;点赞、点踩…

一键降重:芝士AI如何简化论文查重过程?

大家写论文时“旁征博引”是常规操作&#xff0c;所以重复率就成了投稿前的“噩梦”。自己降重&#xff0c;发现怎么改写都无法下降重复率&#xff0c;可能一天改下来下降3%&#xff0c;让人抓狂。 但今天开始&#xff0c;你不用再苦恼啦&#xff0c;更不用自己抓耳挠腮一整天…

【计算机网络 - 基础问题】每日 3 题(二十七)

✍个人博客&#xff1a;Pandaconda-CSDN博客 &#x1f4e3;专栏地址&#xff1a;http://t.csdnimg.cn/fYaBd &#x1f4da;专栏简介&#xff1a;在这个专栏中&#xff0c;我将会分享 C 面试中常见的面试题给大家~ ❤️如果有收获的话&#xff0c;欢迎点赞&#x1f44d;收藏&…

使用FFmpeg压缩MP3格式音频

FFmpeg简介 FFmpeg 是一个开源的多媒体框架&#xff0c;能够录制、转换数字音频和视频&#xff0c;并将其转码到流行的格式。它被广泛应用于音视频处理领域&#xff0c;支持几乎所有的音视频格式和编解码器。以下是 FFmpeg 的一些关键特点和功能&#xff1a; 主要特点 跨平台…

微服务Redis解析部署使用全流程

1、什么是Redis Redis&#xff08;Remote Dictionary Server &#xff09;&#xff0c;即远程字典服务&#xff0c;是一个开源的使用ANSIC语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库&#xff0c;并提供多种语言的API。 可以理解成一个大容量的map。…

PCI数据采集卡500K频率32路模拟量采集 DIO各16路 DAQ卡——PCI8735

品牌&#xff1a;阿尔泰科技 型号&#xff1a;PCI8735 概述&#xff1a; 产品应用&#xff1a; 板卡图片&#xff1a; 指标参数&#xff1a; 模拟量输入 通道数 单端32路/差分16路 精度 12位 采样频率 500KHz 通道切换方式 首末通道顺序切换 AD量程 10V&#xff0c;5V&#x…

Mbox物联网关:驱动工业数据汇聚与智能处理的核心引擎

在数字化转型的汹涌浪潮中&#xff0c;Mbox物联网关作为工业物联网领域的佼佼者&#xff0c;正引领着制造业向智能化、高效化方向迈进&#xff0c;深刻重塑着传统工业的生产生态与效率边界。作为连接物理世界与数字世界的智能桥梁&#xff0c;明达技术自主研发的Mbox物联网关在…

大数据新视界 --大数据大厂之数据压缩算法比较与应用:节省存储空间

&#x1f496;&#x1f496;&#x1f496;亲爱的朋友们&#xff0c;热烈欢迎你们来到 青云交的博客&#xff01;能与你们在此邂逅&#xff0c;我满心欢喜&#xff0c;深感无比荣幸。在这个瞬息万变的时代&#xff0c;我们每个人都在苦苦追寻一处能让心灵安然栖息的港湾。而 我的…

mysql---索引类型及索引方法使用

mysql索引类型 Normal、Full Text、Unique 在 MySQL 中&#xff0c;索引的类型主要有以下几种&#xff1a; Normal Index&#xff08;普通索引&#xff09;&#xff1a; 这是最基本的索引类型&#xff0c;没有唯一性要求。允许重复值&#xff0c;可以加速查询性能。用法&#…

容器编排工具Docker Compose

目录 一、Docker Compose概述 1、主要功能 2、工作原理 二、常用命令参数 1、服务管理 2、构建和重新构建服务 三、Docker Compose的yml文件 1、服务 2、网络 3、存储卷 四、容器编排实现haproxy和nginx负载均衡 一、Docker Compose概述 1、主要功能 定义服务&#xf…

又一条地铁无人线开通!霞智科技智能清洁机器人正式“上岗”

2024年9月26日12时&#xff0c;又一条无人线开通运营&#xff0c;这是陕西省首条全自动无人驾驶地铁线路。该线路作为北跨战略的先行工程&#xff0c;是连接主城区与渭北地区的轨道交通快线&#xff0c;对优化城市总体空间布局、推动区域融合发展、促进沿线产业升级具有十分重要…

HBuilder X中搭建vue-cli项目(一)

一、前端项目结构 传统结构&#xff1a;一个项目中有很多HTML文件,一个HTML文件就是一个网页。他们之间彼此独立,互相没有联系,我们每次导入其它前端文件时,需要给每一个HTML文件都导入,需要导入的文件一旦过多,就会很麻烦,并且整体看来很乱。 现代结构&#xff1a;在一个nod…

相关数据库类型介绍

数据库类型可以根据不同的维度进行分类&#xff0c;但最常见的分类方式是将其分为关系型数据库&#xff08;Relational Databases&#xff09;和非关系型数据库&#xff08;Non-Relational Databases&#xff09;&#xff0c;也称为NoSQL数据库。下面我将详细介绍这两种类型的数…

5.3 克拉默法则、逆矩阵和体积

本节是使用代数而不是消元法来求解 A x b A\boldsymbol x\boldsymbol b Axb 和 A − 1 A^{-1} A−1。所有的公式都会除以 det ⁡ A \det A detA&#xff0c; A − 1 A^{-1} A−1 和 A − 1 b A^{-1}\boldsymbol b A−1b 中的每个元素都是一个行列式除以 A A A 的行列式。…

机器学习-模型集成

文章目录 模型集成为什么要集成&#xff1f;模型集成要解决的问题主要的集成思想 Committees多个模型的结果进行融合。BaggingBagging 特点 BoostingAdaBoost算法过程 GBDT负梯度拟合 XGBoostXGBoost 参数通用参数booster 参数学习目标参数 模型保存 模型集成 三个臭皮匠顶一个…