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

news/2024/9/28 9:17:38 标签: spring boot, 后端, java

使用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.niftyadmin.cn/n/5680801.html

相关文章

基于Hive和Hadoop的电信流量分析系统

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

DOM元素导出图片与PDF:多种方案对比与实现

背景 在日常前端开发中&#xff0c;经常会有把页面的 DOM 元素作为 PNG 或者 PDF 下载到本地的需求。例如海报功能&#xff0c;简历导出功能等等。在我们自家的产品「代码小抄」中&#xff0c;就使用了 html2canvas 来实现代码片段导出为图片&#xff1a; 是不是还行&#xff…

vue仿chatGpt的AI聊天功能--大模型通义千问(阿里云)

vue仿chatGpt的AI聊天功能–大模型通义千问&#xff08;阿里云&#xff09; 通义千问是由阿里云自主研发的大语言模型&#xff0c;用于理解和分析用户输入的自然语言。 1. 创建API-KEY并配置环境变量 打开通义千问网站进行登录&#xff0c;登陆之后创建api-key&#xff0c;右…

C++-list使用学习

###list&#xff08;链表&#xff09;是C里面的一种容器&#xff0c;底层是双向的&#xff1b; 这就决定了它的迭代器使用的场景和能够使用的算法&#xff1b;双向&#xff08;例如list&#xff09;不能像随机&#xff08;例如vector&#xff09;那样用迭代器任意加上几去使用&…

Harbor使用

文章目录 1、上传镜像1.1、在Harbor上创建一个项目1.2、docker添加安全访问权限1.3、推送docker镜像到该项目中1.3.1、登录到Harbor1.3.2、给镜像重新打一个标签1.3.3、推送镜像到Harbor中 2、拉取镜像2.1、先删掉原来的镜像2.2、执行拉取命令 1、上传镜像 需求&#xff1a;将…

[论文精读]Polarized Graph Neural Networks

论文网址&#xff1a;Polarized Graph Neural Networks | Proceedings of the ACM Web Conference 2022 英文是纯手打的&#xff01;论文原文的summarizing and paraphrasing。可能会出现难以避免的拼写错误和语法错误&#xff0c;若有发现欢迎评论指正&#xff01;文章偏向于…

java日志门面之JCL和SLF4J

文章目录 前言一、JCL1、JCL简介2、快速入门3、 JCL原理 二、SLF4J1、SLF4J简介2、快速入门2.1、输出动态信息2.2、异常信息的处理 3、绑定日志的实现3.1、slf4j实现slf4j-simple和logback3.2、slf4j绑定适配器实现log4j3.2、Slf4j注解 4、桥接旧的日志框架4.1、log4j日志重构为…

InternVL 微调实践

任务 follow 教学文档和视频使用QLoRA进行微调模型&#xff0c;复现微调效果&#xff0c;并能成功讲出梗图. 复现过程 参考教程部署&#xff1a;https://github.com/InternLM/Tutorial/blob/camp3/docs/L2/InternVL/joke_readme.md 训练 合并权重&&模型转换 pyth…