Spring Cloud提供了多种方式来发送请求到其他服务。以下是一些常见的方法

1. RestTemplate

使用RestTemplate,需要在pom.xml文件中添加以下依赖:

xmlCopy code<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

示例代码:

javaCopy codeRestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject("http://service-url/api/resource", String.class);

2. WebClient

WebClient通常与Spring WebFlux一起使用,需要添加以下依赖:

xmlCopy code<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

示例代码:

javaCopy codeWebClient webClient = WebClient.create("http://service-url");
Mono<String> resultMono = webClient.get()
    .uri("/api/resource")
    .retrieve()
    .bodyToMono(String.class);
String result = resultMono.block();

3. Feign

使用Feign,需要添加spring-cloud-starter-openfeign依赖:

xmlCopy code<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

这里主要讲一下fegin。

首先看一下fegin调用内部已经注册到同一个注册中心上的服务互相调用方式

3.1 内部微服务互相调用

@FeignClient(contextId = "remoteUserService", value = ServiceNameConstants.SYSTEM_SERVICE, fallbackFactory = RemoteUserFallbackFactory.class)
public interface RemoteUserService
{
    /**
     * 通过用户名查询用户信息
     *
     * @param username 用户名
     * @param source 请求来源
     * @return 结果
     */
    @GetMapping("/user/info/{username}")
    public R<LoginUser> getUserInfo(@PathVariable("username") String username, @RequestHeader(SecurityConstants.FROM_SOURCE) String source);
}

需要指定value为已注册的服务的id

3.2 调用外部第三方系统

@FeignClient(name = "test",url = "https://timor.tech", fallbackFactory = RemoteVideoFallbackFactory.class,configuration = FeignConfig.class)
public interface RemoteTestService
{

    @GetMapping(value = "/api/holiday/year/{year}")
    public String test1(@PathVariable(name = "year") String year);
}

3.2.1 指定请求时默认的请求头

@Configuration
public class FeignConfig implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        requestTemplate.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
    }
}

添加配置后在@FeignClient注解中指定使用此配置类,configuration = FeignConfig.class

4. HttpClient

对于直接使用HttpClient,可以添加以下依赖:

xmlCopy code<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version> <!-- 版本号可能会有更新 -->
</dependency>

示例代码:

javaCopy codeCloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://service-url/api/resource");
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        String result = EntityUtils.toString(entity);
        // 使用结果
    }
}