java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot  RestClient使用

Spring Boot 3 RestClient使用实战案例

作者:李昊哲小课

本文详细介绍了SpringBoot3中RestClient的使用方法,从基础到高级,涵盖了各种常见场景和最佳实践,通过本教程,读者可以理解RestClient的核心概念和优势,感兴趣的朋友跟随小编一起看看吧

Spring Boot 3 RestClient 完整教程

1. RestClient 简介与环境准备

1.1 RestClient 简介

RestClient 是 Spring Framework 6 引入的新的 HTTP 客户端。

作为 RestTemplate 的现代替代方案,提供了更简洁的 API、更好的响应式支持和函数式编程风格。

在 Spring Boot 3 中,RestClient 成为了推荐的 HTTP 客户端选择。

相比 RestTemplate,RestClient 具有以下优势:

1.2 环境准备

1.2.1 开发环境
1.2.2 创建项目与依赖配置

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <!-- 父项目依赖 -->
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.5.7</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>com.lihaozhe</groupId>
  <artifactId>restclient-tutorial</artifactId>
  <version>0.0.1</version>
  <name>restclient-tutorial</name>
  <description>Spring Boot 3 RestClient Tutorial</description>
  <!-- 属性配置 -->
  <properties>
    <java.version>25</java.version>
  </properties>
  <!-- 依赖配置 -->
  <dependencies>
    <!-- Spring Boot Web 依赖,包含 RestClient -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- JSON 处理 -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.datatype</groupId>
      <artifactId>jackson-datatype-jsr310</artifactId>
    </dependency>
    <!-- 读取配置文件 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-configuration-processor</artifactId>
      <optional>true</optional>
    </dependency>
    <!-- Lombok 简化代码 -->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>
    <!-- 测试依赖 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <annotationProcessorPaths>
            <path>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-configuration-processor</artifactId>
            </path>
            <path>
              <groupId>org.projectlombok</groupId>
              <artifactId>lombok</artifactId>
            </path>
          </annotationProcessorPaths>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
          <excludes>
            <exclude>
              <groupId>org.projectlombok</groupId>
              <artifactId>lombok</artifactId>
            </exclude>
          </excludes>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
1.2.3 RestClient 配置

创建一个配置类,用于配置 RestClient 实例:

RestClientConfig.java

package com.lihaozhe.restclienttutorial.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.JdkClientHttpRequestFactory;
import org.springframework.web.client.RestClient;
@Configuration
public class RestClientConfig {
  // 配置默认的 RestClient 实例
  @Bean
  public RestClient restClient() {
    // 创建 RestClient 构建器
    return RestClient.builder()
      // 设置默认基础 URL
      .baseUrl("https://jsonplaceholder.typicode.com")
      // 设置请求工厂,这里使用 JDK 自带的 HttpClient
      .requestFactory(new JdkClientHttpRequestFactory())
      // 构建 RestClient 实例
      .build();
  }
}
1.2.4 启动类

RestclientTutorialApplication.java

package com.lihaozhe.restclienttutorial;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RestclientTutorialApplication {
  public static void main(String[] args) {
    SpringApplication.run(RestclientTutorialApplication.class, args);
  }
}

2. RestClient 基础使用

2.1 数据模型定义

首先定义一个示例数据模型,用于后续的 API 调用:

User.java

package com.lihaozhe.restclienttutorial.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
// 使用 Lombok 注解简化代码
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
  private Long id;
  private String name;
  private String username;
  private String email;
  private Address address;
  private String phone;
  private String website;
  private Company company;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
class Address {
  private String street;
  private String suite;
  private String city;
  private String zipcode;
  private Geo geo;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
class Geo {
  private String lat;
  private String lng;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
class Company {
  private String name;
  private String catchPhrase;
  private String bs;
}

Post.java

package com.lihaozhe.restclienttutorial.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Post {
  private Long id;
  private Long userId;
  private String title;
  private String body;
}

2.2 基本 HTTP 方法使用

创建一个服务类,演示 RestClient 的基本用法:

ApiService.java

package com.lihaozhe.restclienttutorial.service;
import com.lihaozhe.restclienttutorial.model.Post;
import com.lihaozhe.restclienttutorial.model.User;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
import java.util.List;
@Service
// 构造函数注入所需依赖
@RequiredArgsConstructor
public class ApiService {
  // 注入 RestClient 实例
  private final RestClient restClient;
  /**
   * 使用 GET 方法获取单个用户
   */
  public User getUserById(Long id) {
    // 发送 GET 请求并返回 User 对象
    return restClient.get()
      // 指定请求路径
      .uri("/users/{id}", id)
      // 发送请求并将响应体转换为 User 类型
      .retrieve()
      // 处理 HTTP 状态码 404 的情况
      .onStatus(HttpStatus.NOT_FOUND, (request, response) -> {
        throw new RuntimeException("User not found with id: " + id);
      })
      // 将响应体转换为 User 对象
      .body(User.class);
  }
  /**
   * 使用 GET 方法获取所有用户
   */
  public List<User> getAllUsers() {
    // 发送 GET 请求并返回用户列表
    return restClient.get()
      .uri("/users")
      .retrieve()
      // 由于返回的是数组,使用参数化类型
      .body(User[].class);
  }
  /**
   * 使用 POST 方法创建新帖子
   */
  public Post createPost(Post post) {
    // 发送 POST 请求创建新资源
    return restClient.post()
      .uri("/posts")
      // 设置请求体
      .body(post)
      .retrieve()
      // 处理 201 Created 状态码
      .onStatus(HttpStatus.CREATED, (request, response) -> {
        System.out.println("Post created successfully");
      })
      .body(Post.class);
  }
  /**
   * 使用 PUT 方法更新帖子
   */
  public Post updatePost(Long id, Post post) {
    // 发送 PUT 请求更新资源
    return restClient.put()
      .uri("/posts/{id}", id)
      .body(post)
      .retrieve()
      .body(Post.class);
  }
  /**
   * 使用 DELETE 方法删除帖子
   */
  public void deletePost(Long id) {
    // 发送 DELETE 请求删除资源
    restClient.delete()
      .uri("/posts/{id}", id)
      .retrieve()
      // 检查响应状态码是否为 200 OK
      .toBodilessEntity();
  }
}

2.3 测试 RestClient 基础功能

创建测试类验证上述功能:

ApiServiceTest.java

package com.lihaozhe.restclienttutorial.service;
import com.lihaozhe.restclienttutorial.model.Post;
import com.lihaozhe.restclienttutorial.model.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class ApiServiceTest {
  @Autowired
  private ApiService apiService;
  @Test
  void shouldGetUserById() {
    // 测试获取单个用户
    User user = apiService.getUserById(1L);
    assertNotNull(user);
    assertEquals(1L, user.getId());
    assertEquals("Leanne Graham", user.getName());
  }
  @Test
  void shouldGetAllUsers() {
    // 测试获取所有用户
    List<User> users = apiService.getAllUsers();
    assertNotNull(users);
    assertFalse(users.isEmpty());
    assertTrue(users.size() > 0);
  }
  @Test
  void shouldCreatePost() {
    // 测试创建帖子
    Post post = new Post(null, 1L, "Test Title", "Test Body");
    Post createdPost = apiService.createPost(post);
    assertNotNull(createdPost);
    assertNotNull(createdPost.getId());
    assertEquals(post.getTitle(), createdPost.getTitle());
    assertEquals(post.getBody(), createdPost.getBody());
  }
  @Test
  void shouldUpdatePost() {
    // 测试更新帖子
    Long postId = 1L;
    Post post = new Post(postId, 1L, "Updated Title", "Updated Body");
    Post updatedPost = apiService.updatePost(postId, post);
    assertNotNull(updatedPost);
    assertEquals(postId, updatedPost.getId());
    assertEquals(post.getTitle(), updatedPost.getTitle());
  }
  @Test
  void shouldDeletePost() {
    // 测试删除帖子
    assertDoesNotThrow(() -> apiService.deletePost(1L));
  }
}

3. RestClient 高级特性

3.1 请求参数与 headers 设置

ApiService.java (扩展)

/**
 * 演示请求参数和 headers 设置
 */
public List<Post> getPostsByUserId(Long userId) {
  // 设置请求参数和 headers
  return restClient.get()
    // 使用 uri 方法设置查询参数
    .uri(uriBuilder -> uriBuilder
      .path("/posts")
      .queryParam("userId", userId)
      .build())
    // 设置请求头
    .header("Accept", "application/json")
    .header("Authorization", "Bearer token123")
    .retrieve()
    .body(Post[].class);
}

3.2 拦截器使用

创建一个自定义拦截器,用于日志记录:

LoggingInterceptor.java

package com.lihaozhe.restclienttutorial.interceptor;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.StreamUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class LoggingInterceptor implements ClientHttpRequestInterceptor {
  @Override
  public ClientHttpResponse intercept(
    HttpRequest request, 
    byte[] body, 
    ClientHttpRequestExecution execution
  ) throws IOException {
    // 记录请求信息
    logRequest(request, body);
    // 执行请求
    ClientHttpResponse response = execution.execute(request, body);
    // 记录响应信息
    logResponse(response);
    return response;
  }
  private void logRequest(HttpRequest request, byte[] body) {
    System.out.println("=== Request ===");
    System.out.println("Method: " + request.getMethod());
    System.out.println("URI: " + request.getURI());
    System.out.println("Headers: " + request.getHeaders());
    System.out.println("Body: " + new String(body, StandardCharsets.UTF_8));
    System.out.println("===============");
  }
  private void logResponse(ClientHttpResponse response) throws IOException {
    System.out.println("=== Response ===");
    System.out.println("Status code: " + response.getStatusCode());
    System.out.println("Headers: " + response.getHeaders());
    System.out.println("Body: " + StreamUtils.copyToString(response.getBody(), StandardCharsets.UTF_8));
    System.out.println("===============");
  }
}

更新 RestClient 配置,添加拦截器:

RestClientConfig.java (扩展)

// 配置带有拦截器的 RestClient
@Bean
public RestClient restClientWithInterceptor() {
  return RestClient.builder()
    .baseUrl("https://jsonplaceholder.typicode.com")
    .requestFactory(new JdkClientHttpRequestFactory())
    // 添加自定义拦截器
    .interceptors(new LoggingInterceptor())
    .build();
}

3.3 错误处理

ApiService.java (扩展)

/**
 * 演示高级错误处理
 */
public User getUserWithErrorHandling(Long id) {
  try {
    return restClient.get()
      .uri("/users/{id}", id)
      .retrieve()
      // 处理 4xx 客户端错误
      .onStatus(HttpStatus::is4xxClientError, (request, response) -> {
        String errorBody = StreamUtils.copyToString(response.getBody(), StandardCharsets.UTF_8);
        throw new RuntimeException("Client error: " + response.getStatusCode() + ", Body: " + errorBody);
      })
      // 处理 5xx 服务器错误
      .onStatus(HttpStatus::is5xxServerError, (request, response) -> {
        throw new RuntimeException("Server error: " + response.getStatusCode());
      })
      .body(User.class);
  } catch (RestClientException e) {
    // 捕获并处理 RestClient 异常
    System.err.println("Error fetching user: " + e.getMessage());
    // 可以根据需要返回默认值或重新抛出
    return new User();
  }
}

3.4 超时设置

更新 RestClient 配置,添加超时设置:

RestClientConfig.java (扩展)

// 配置带有超时设置的 RestClient
@Bean
public RestClient restClientWithTimeout() {
  // 创建 HTTP 客户端工厂并设置超时
  JdkClientHttpRequestFactory requestFactory = new JdkClientHttpRequestFactory();
  // 设置连接超时
  requestFactory.setConnectTimeout(Duration.ofSeconds(5));
  // 设置读取超时
  requestFactory.setReadTimeout(Duration.ofSeconds(10));
  return RestClient.builder()
    .baseUrl("https://jsonplaceholder.typicode.com")
    .requestFactory(requestFactory)
    .build();
}

4. 实战案例:RESTful API 客户端实现

4.1 案例说明

我们将实现一个完整的 RESTful API 客户端,用于管理"任务"资源,包括以下功能:

4.2 数据模型

Task.java

package com.lihaozhe.restclienttutorial.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Task {
  private Long id;
  private String title;
  private String description;
  private boolean completed;
  private LocalDateTime createdAt;
  private LocalDateTime updatedAt;
}

4.3 服务接口

TaskService.java

package com.lihaozhe.restclienttutorial.service;
import com.lihaozhe.restclienttutorial.model.Task;
import java.util.List;
public interface TaskService {
  List<Task> getAllTasks();
  Task getTaskById(Long id);
  Task createTask(Task task);
  Task updateTask(Long id, Task task);
  void deleteTask(Long id);
  List<Task> getTasksByStatus(boolean completed);
}

4.4 服务实现

TaskServiceImpl.java

package com.lihaozhe.restclienttutorial.service;
import com.lihaozhe.restclienttutorial.model.Task;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
import java.util.List;
@Service
@RequiredArgsConstructor
public class TaskServiceImpl implements TaskService {
  private final RestClient restClient;
  // 任务 API 的基础路径
  private static final String TASKS_BASE_URL = "/tasks";
  @Override
  public List<Task> getAllTasks() {
    return restClient.get()
      .uri(TASKS_BASE_URL)
      .retrieve()
      .body(Task[].class);
  }
  @Override
  public Task getTaskById(Long id) {
    return restClient.get()
      .uri(TASKS_BASE_URL + "/{id}", id)
      .retrieve()
      .onStatus(HttpStatus.NOT_FOUND, (request, response) -> {
        throw new RuntimeException("Task not found with id: " + id);
      })
      .body(Task.class);
  }
  @Override
  public Task createTask(Task task) {
    // 设置创建时间
    task.setCreatedAt(LocalDateTime.now());
    task.setUpdatedAt(LocalDateTime.now());
    return restClient.post()
      .uri(TASKS_BASE_URL)
      .body(task)
      .retrieve()
      .onStatus(HttpStatus.CREATED, (request, response) -> {
        System.out.println("Task created successfully");
      })
      .body(Task.class);
  }
  @Override
  public Task updateTask(Long id, Task task) {
    // 设置更新时间
    task.setUpdatedAt(LocalDateTime.now());
    return restClient.put()
      .uri(TASKS_BASE_URL + "/{id}", id)
      .body(task)
      .retrieve()
      .body(Task.class);
  }
  @Override
  public void deleteTask(Long id) {
    restClient.delete()
      .uri(TASKS_BASE_URL + "/{id}", id)
      .retrieve()
      .toBodilessEntity();
  }
  @Override
  public List<Task> getTasksByStatus(boolean completed) {
    return restClient.get()
      .uri(uriBuilder -> uriBuilder
        .path(TASKS_BASE_URL)
        .queryParam("completed", completed)
        .build())
      .retrieve()
      .body(Task[].class);
  }
}

4.5 控制器层

TaskController.java

package com.lihaozhe.restclienttutorial.controller;
import com.lihaozhe.restclienttutorial.model.Task;
import com.lihaozhe.restclienttutorial.service.TaskService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/tasks")
@RequiredArgsConstructor
public class TaskController {
  private final TaskService taskService;
  @GetMapping
  public List<Task> getAllTasks() {
    return taskService.getAllTasks();
  }
  @GetMapping("/{id}")
  public ResponseEntity<Task> getTaskById(@PathVariable Long id) {
    try {
      Task task = taskService.getTaskById(id);
      return ResponseEntity.ok(task);
    } catch (RuntimeException e) {
      return ResponseEntity.notFound().build();
    }
  }
  @PostMapping
  public ResponseEntity<Task> createTask(@RequestBody Task task) {
    Task createdTask = taskService.createTask(task);
    return new ResponseEntity<>(createdTask, HttpStatus.CREATED);
  }
  @PutMapping("/{id}")
  public ResponseEntity<Task> updateTask(
    @PathVariable Long id, 
    @RequestBody Task task
  ) {
    Task updatedTask = taskService.updateTask(id, task);
    return ResponseEntity.ok(updatedTask);
  }
  @DeleteMapping("/{id}")
  public ResponseEntity<Void> deleteTask(@PathVariable Long id) {
    taskService.deleteTask(id);
    return ResponseEntity.noContent().build();
  }
  @GetMapping("/filter")
  public List<Task> getTasksByStatus(@RequestParam boolean completed) {
    return taskService.getTasksByStatus(completed);
  }
}

4.6 测试用例

TaskServiceImplTest.java

package com.lihaozhe.restclienttutorial.service;
import com.lihaozhe.restclienttutorial.model.Task;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.web.client.RestClient;
import java.time.LocalDateTime;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class TaskServiceImplTest {
  @Autowired
  private TaskService taskService;
  // 注入带有拦截器的 RestClient 用于测试
  @Autowired
  @Qualifier("restClientWithInterceptor")
  private RestClient restClient;
  @Test
  void shouldPerformCrudOperations() {
    // 创建任务
    Task task = new Task(
      null, 
      "Test Task", 
      "Test Description", 
      false, 
      null, 
      null
    );
    Task createdTask = taskService.createTask(task);
    assertNotNull(createdTask);
    assertNotNull(createdTask.getId());
    assertEquals(task.getTitle(), createdTask.getTitle());
    assertNotNull(createdTask.getCreatedAt());
    // 获取任务
    Long taskId = createdTask.getId();
    Task fetchedTask = taskService.getTaskById(taskId);
    assertNotNull(fetchedTask);
    assertEquals(taskId, fetchedTask.getId());
    // 更新任务
    fetchedTask.setCompleted(true);
    fetchedTask.setTitle("Updated Task Title");
    Task updatedTask = taskService.updateTask(taskId, fetchedTask);
    assertNotNull(updatedTask);
    assertTrue(updatedTask.isCompleted());
    assertEquals("Updated Task Title", updatedTask.getTitle());
    assertTrue(updatedTask.getUpdatedAt().isAfter(createdTask.getCreatedAt()));
    // 按状态筛选任务
    List<Task> completedTasks = taskService.getTasksByStatus(true);
    assertFalse(completedTasks.isEmpty());
    // 删除任务
    assertDoesNotThrow(() -> taskService.deleteTask(taskId));
    // 验证任务已删除
    assertThrows(RuntimeException.class, () -> taskService.getTaskById(taskId));
  }
}

5. 最佳实践与性能优化

5.1 最佳实践

  1. 单一职责原则:每个 RestClient 实例专注于特定的 API 或服务
  2. 异常处理:始终处理可能的异常,提供有意义的错误信息
  3. 连接池管理:合理配置连接池大小和超时时间
  4. 避免重复创建:RestClient 实例应该是单例的,避免频繁创建和销毁
  5. 日志记录:使用拦截器记录关键请求和响应信息,便于调试
  6. 配置外部化:将基础 URL、超时时间等配置放在配置文件中
  7. 使用 Builders:利用 RestClient 的构建器模式创建客户端实例

5.2 性能优化

  1. 连接池配置
@Bean
public RestClient restClientWithPool() {
  // 配置 HTTP 客户端连接池
  HttpClient httpClient = HttpClient.newBuilder()
    .connectTimeout(Duration.ofSeconds(5))
    .connectionPool(new ConnectionPool(10, 30, TimeUnit.SECONDS))
    .build();
  JdkClientHttpRequestFactory requestFactory = new JdkClientHttpRequestFactory(httpClient);
  return RestClient.builder()
    .baseUrl("https://api.lihaozhe.com")
    .requestFactory(requestFactory)
    .build();
}
  1. 响应压缩:启用请求和响应压缩
@Bean
public RestClient restClientWithCompression() {
  HttpClient httpClient = HttpClient.newBuilder()
    .connectTimeout(Duration.ofSeconds(5))
    .build();
  JdkClientHttpRequestFactory requestFactory = new JdkClientHttpRequestFactory(httpClient);
  return RestClient.builder()
    .baseUrl("https://api.lihaozhe.com")
    .requestFactory(requestFactory)
    .defaultHeader("Accept-Encoding", "gzip, deflate")
    .build();
}
  1. 异步请求:对于非阻塞场景,使用异步请求
@Bean
public AsyncRestClient asyncRestClient() {
  return AsyncRestClient.builder()
    .baseUrl("https://api.lihaozhe.com")
    .build();
}
// 使用示例
public CompletableFuture<User> getUserAsync(Long id) {
  return asyncRestClient.get()
    .uri("/users/{id}", id)
    .retrieve()
    .bodyToMono(User.class)
    .toFuture();
}
  1. 缓存策略:对于频繁访问且不常变化的资源,实现缓存机制
private final Cache<String, User> userCache = CacheBuilder.newBuilder()
  .expireAfterWrite(10, TimeUnit.MINUTES)
  .maximumSize(100)
  .build();
public User getCachedUser(Long id) {
  try {
    return userCache.get(id.toString(), () -> {
      // 缓存未命中时,从 API 获取
      return restClient.get()
        .uri("/users/{id}", id)
        .retrieve()
        .body(User.class);
    });
  } catch (ExecutionException e) {
    throw new RuntimeException("Error fetching user", e.getCause());
  }
}

5.3 配置外部化

application.properties

# API 基础 URL
api.base-url=https://jsonplaceholder.typicode.com
# 连接超时(毫秒)
api.connection-timeout=5000
# 读取超时(毫秒)
api.read-timeout=10000
# 连接池大小
api.connection-pool-size=10

配置类

@Configuration
@ConfigurationProperties(prefix = "api")
@Data
public class ApiProperties {
  private String baseUrl;
  private int connectionTimeout;
  private int readTimeout;
  private int connectionPoolSize;
}
@Configuration
public class ConfiguredRestClientConfig {
  @Bean
  public RestClient configuredRestClient(ApiProperties apiProperties) {
    HttpClient httpClient = HttpClient.newBuilder()
      .connectTimeout(Duration.ofMillis(apiProperties.getConnectionTimeout()))
      .connectionPool(new ConnectionPool(
        apiProperties.getConnectionPoolSize(), 
        30, 
        TimeUnit.SECONDS
      ))
      .build();
    JdkClientHttpRequestFactory requestFactory = new JdkClientHttpRequestFactory(httpClient);
    requestFactory.setReadTimeout(Duration.ofMillis(apiProperties.getReadTimeout()));
    return RestClient.builder()
      .baseUrl(apiProperties.getBaseUrl())
      .requestFactory(requestFactory)
      .interceptors(new LoggingInterceptor())
      .build();
  }
}

总结

本教程详细介绍了 Spring Boot 3 中 RestClient 的使用方法,从基础到高级,涵盖了各种常见场景和最佳实践。RestClient 作为 RestTemplate 的现代替代方案,提供了更简洁、更灵活的 API,是开发 RESTful 客户端的理想选择。

通过本教程,你应该能够:

RestClient 结合了 Spring 的强大功能和现代 Java 的特性,为开发者提供了高效、可靠的 HTTP 客户端解决方案。在实际项目中,应根据具体需求选择合适的配置和功能,以获得最佳的性能和可维护性。

到此这篇关于Spring Boot 3 RestClient使用实战案例的文章就介绍到这了,更多相关SpringBoot RestClient使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文