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();  
    }  
}  
相关推荐
远望樱花兔14 分钟前
【d54_2】【Java】【力扣】142.环形链表
java·leetcode·链表
IT学长编程15 分钟前
计算机毕业设计 助农产品采购平台的设计与实现 Java实战项目 附源码+文档+视频讲解
java·spring boot·毕业设计·课程设计·毕业论文·计算机毕业设计选题·助农产品采购平台
2401_8572979120 分钟前
2025校招内推-招联金融
java·前端·算法·金融·求职招聘
编啊编程啊程22 分钟前
一文上手Kafka【下】
java·分布式·中间件·kafka
誓则盟约37 分钟前
基于Spring框架的分层解耦详解
java·后端·spring
旺旺碎冰冰、1 小时前
Java之多态
java·开发语言
今天不coding1 小时前
今年Java回暖了吗
java·开发语言
IT学长编程1 小时前
计算机毕业设计 智能旅游推荐平台的设计与实现 Java实战项目 附源码+文档+视频讲解
java·spring boot·毕业设计·旅游·毕业论文·计算机毕业设计选题·协同过滤推荐算法
清晨细雨~1 小时前
使用 Spring Boot 和 EasyExcel 进行动态表头导出 Excel
java·开发语言
wht65871 小时前
C++--IO流
java·c语言·开发语言·数据结构·c++