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. 数据库和缓存不一致采用什…

AMD ROCm™ 安装指南

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

搜索引擎简介

搜索引擎架构 整个搜索引擎分为三个系统 爬虫系统 索引系统 线上搜素服务 爬虫系统 爬虫分为两个阶段&#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 为核…

Java五子棋

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

通过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;每个时钟周期只传…

每日论文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;因此一定程度…

echarts 导出pdf空白原因

问题阐述 页面样式&#xff1a; 导出pdf: 导出pdf&#xff0c;统计图部分为空白。 问题原因 由于代码中进行了dom字符串的复制&#xff0c;而echarts用canvas绘制&#xff0c;canvas内部内容不会进行复制&#xff0c;只会复制canvas节点&#xff0c;因此导出pdf空白。 解决…

C语言VS实用调试技巧

文章目录 一、什么是bug?二、什么是调试&#xff1f;三、Debug和Release四、VS调试快捷键4.1环境准备4.2调试快捷键 五、监视和内存观察5.1监视5.2内存 六、调试举例七、编程常见错误归类7.1编译型错误7.2链接型错误7.3运行时错误 一、什么是bug? &#x1f34e;bug本意是 “…

【珠海一号卫星】

珠海一号卫星 珠海一号卫星星座是由珠海欧比特宇航科技股份有限公司发射并运营的商业遥感微纳卫星星座&#xff0c;是中国首家由民营上市公司建设并运营的卫星星座。以下是对珠海一号卫星的详细介绍&#xff1a; 一、基本概况 组成&#xff1a;整个星座由34颗卫星组成&…

Solidity——抽象合约和接口详解

&#x1f680;本系列文章为个人学习笔记&#xff0c;目的是巩固知识并记录我的学习过程及理解。文笔和排版可能拙劣&#xff0c;望见谅。 Solidity中的抽象合约和接口详解 目录 什么是抽象合约&#xff1f;抽象合约的语法接口&#xff08;Interface&#xff09;的定义接口的语…

通过 OBD Demo 体验 OceanBase 4.3 社区版

本文作者&#xff1a;马顺华 引言 OceanBase 4.3 是一个专为实时分析 AP 业务设计的重大更新版本。它基于LSM-Tree架构&#xff0c;引入了列存引擎&#xff0c;实现了行存与列存数据存储的无缝整合。这一版本不仅显著提升了AP场景的查询性能&#xff0c;同时也确保了TP业务场景…

uniapp云打包

ios打包 没有mac电脑,使用香蕉云编 先登录香蕉云编这个工具,新建csr文件——把csr文件下载到你电脑本地: 然后,登录苹果开发者中心 生成p12证书 1、点击+号创建证书 创建证书的时候一定要选择ios distribution app store and ad hoc类型的证书 2、上传刚才从本站生成的…

【设计模式-策略】

定义 策略模式&#xff08;Strategy Pattern&#xff09;是一种行为型设计模式&#xff0c;定义了一系列算法&#xff0c;将每个算法封装起来&#xff0c;并使它们可以互相替换。策略模式让算法独立于使用它的客户端而变化&#xff0c;使得算法的变化不会影响到使用它的客户端…

Java读取YAML文件

&#x1f49d;&#x1f49d;&#x1f49d;欢迎莅临我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐&#xff1a;「storm…

Metasploit渗透测试之服务端漏洞利用

简介 在之前的文章中&#xff0c;我们学习了目标的IP地址&#xff0c;端口&#xff0c;服务&#xff0c;操作系统等信息的收集。信息收集过程中最大的收获是服务器或系统的操作系统信息。这些信息对后续的渗透目标机器非常有用&#xff0c;因为我们可以快速查找系统上运行的服…