锋盈数科-知识库 Logo
首页
软件开发
计算机基础
Hello Halo
新手必读
关于本知识库
登录 →
锋盈数科-知识库 Logo
首页 软件开发 计算机基础 Hello Halo 新手必读 关于本知识库
登录
  1. 首页
  2. 软件开发
  3. JAVA
  4. Spring Boot 调用外部接口的常用方式!

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

0
  • JAVA
  • 发布于 2024-09-28
  • 10 次阅读
黄健
黄健

使用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();  
    }  
}  

原文链接: https://blog.csdn.net/weimeilayer/article/details/142588955

标签: #JAVA 991 #Spring Boot 173
相关文章

Spring 实现 3 种异步接口 2024-10-18 09:07

大家好,我是苏三~ 如何处理比较耗时的接口? 这题我熟,直接上异步接口,使用 Callable、WebAsyncTask 和 DeferredResult、CompletableFuture等均可实现。 但这些方法有局限性,处理结果仅返回单个值。在某些场景下,如果需要接口异步处理的同时,还持续不断地

重学SpringBoot3-集成Redis(五)之布隆过滤器 2024-10-08 11:24

更多SpringBoot3内容请关注我的专栏:《SpringBoot3》 期待您的点赞👍收藏⭐评论✍ 重学SpringBoot3-集成Redis(五)之布隆过滤器 1. 什么是布隆过滤器? * 基本概念 适用场景 2. 使用 Redis 实现布隆过滤器 * 项目依赖 Redis 配置

SpringBoot整合异步任务执行 2024-10-08 11:24

同步任务: 同步任务是在单线程中按顺序执行,每次只有一个任务在执行,不会引发线程安全和数据一致性等 并发问题 同步任务需要等待任务执行完成后才能执行下一个任务,无法同时处理多个任务,响应慢,影响用 户体验 异步任务: 异步任务是在多线程中同时执行,多个任务可以并发执行,同时处理多个请求,响应快,资源

springboot kafka多数据源,通过配置动态加载发送者和消费者 2024-10-08 11:24

前言 最近做项目,需要支持kafka多数据源,实际上我们也可以通过代码固定写死多套kafka集群逻辑,但是如果需要不修改代码扩展呢,因为kafka本身不处理额外逻辑,只是起到削峰,和数据的传递,那么就需要对架构做一定的设计了。 准备test kafka本身非常容易上手,如果我们需要单元测试,引入ja

SpringBoot 集成 Redis 2024-10-08 11:24

一:SpringBoot 集成 Redis ①Redis是一个 NoSQL(not only)数据库, 常作用缓存 Cache 使用。 ②Redis是一个中间件、是一个独立的服务器;常用的数据类型: string , hash ,set ,zset , list ③通过Redis客户端可以使用多种语

SpringBoot整合QQ邮箱 2024-10-08 11:24

SpringBoot可以通过导入依赖的方式集成多种技术,这当然少不了我们常用的邮箱,现在本章演示SpringBoot整合QQ邮箱发送邮件…. 下面按步骤进行: 1.获取QQ邮箱授权码 1.1 登录QQ邮箱 1.2 开启SMTP服务 找到下图中的SMTP服务区域,如果当前账号未开启的话自己手动开启。

目录

IT 外包服务商

  • 意见投递
  • zyf6619

软件开发应用

主菜单

  • 首页
  • 软件开发
  • 计算机基础
  • Hello Halo
  • 新手必读
  • 关于本知识库
Copyright © 2024 your company All Rights Reserved. Powered by Halo.