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

使用Feign进行服务消费是一种简化HTTP调用的方式,可以通过声明式的接口定义来实现。下面是一个使用Feign的示例,包括设置Feign客户端和调用服务的方法。

添加依赖

首先,请确保你的项目中已经添加了Feign的依赖。如果你使用的是Maven,可以在pom.xml中添加以下依赖(如果使用Spring Boot,通常已经包含了这些依赖):

bash 复制代码
<dependency>  
    <groupId>org.springframework.cloud</groupId>  
    <artifactId>spring-cloud-starter-openfeign</artifactId>  
</dependency>  

以下是完整示例的结构:

主应用类(YourApplication.java):

bash 复制代码
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):

bash 复制代码
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):

bash 复制代码
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客户端,适用于异步调用。

示例代码:

bash 复制代码
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:

bash 复制代码
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

bash 复制代码
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,通常在主类或配置类中:
bash 复制代码
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 请求:

bash 复制代码
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 (如果需要)  
    }  
}  

调用示例

通常在一个控制器中调用这个服务:

bash 复制代码
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();  
    }  
}  
相关推荐
稚辉君.MCA_P8_Java4 分钟前
DeepSeek Java 单例模式详解
java·spring boot·微服务·单例模式·kubernetes
洛_尘12 分钟前
数据结构--4:栈和队列
java·数据结构·算法
疯癫的老码农18 分钟前
【小白入门docker】创建Spring Boot Hello World应用制作Docker镜像并运行
java·spring boot·分布式·docker·微服务
Mr.Entropy26 分钟前
Hibernate批量查询方法全面解析
java·后端·hibernate
绝顶少年42 分钟前
Spring 框架中 RestTemplate 的使用方法
java·后端·spring
小趴菜822744 分钟前
安卓人机验证View
android·java·前端
信安成长日记1 小时前
golang 写路由的时候要注意
开发语言·后端·golang
Lojarro1 小时前
GO学习2:基本数据类型 与 转换
后端·学习·golang
观望过往1 小时前
【Java SE 运算符】全面解析与实践指南
java
没有bug.的程序员1 小时前
分布式架构初识:为什么需要分布式
java·分布式·架构·php