[Java实战]Spring Boot 3构建 RESTful 风格服务(二十)

[Java实战]Spring Boot 3构建 RESTful 风格服务(二十)

一. 环境准备
  • openJDK 17+:Spring Boot 3 要求 Java 17 及以上。
  • Spring Boot 3.4.5:使用最新稳定版。
  • Ehcache 3.10+:支持 JSR-107 标准,兼容 Spring Cache 抽象。
  • 构建工具:Maven 或 Gradle(本文以 Maven 为例)。
二、RESTful 架构的六大核心原则
  1. 无状态(Stateless)
    每个请求必须包含处理所需的所有信息,服务端不保存客户端会话状态。
    示例:JWT Token 代替 Session 传递身份信息。

  2. 统一接口(Uniform Interface)

    • 资源标识(URI)
    • 自描述消息(HTTP 方法 + 状态码)
    • 超媒体驱动(HATEOAS)
  3. 资源导向(Resource-Based)
    使用名词表示资源,避免动词。
    Bad/getUser?id=1
    GoodGET /users/1

  4. 分层系统(Layered System)
    客户端无需感知是否直接连接终端服务器(如通过网关代理)。

  5. 缓存友好(Cacheable)
    利用 HTTP 缓存头(Cache-Control, ETag)优化性能。

  6. 按需编码(Code-On-Demand)
    可选原则,允许服务器临时扩展客户端功能(如返回可执行脚本)。

三、Spring Boot 快速构建 RESTful API
1. 基础 CRUD 实现
@RestController
@RequestMapping("/api/v1/users")
public class UserController {
    @Autowired
    private UserService userService;

    // 创建用户
    @PostMapping
    public ResponseEntity<User> createUser(@Validated @RequestBody User user) {
        User savedUser = userService.save(user);
        URI location = ServletUriComponentsBuilder.fromCurrentRequest()
                .path("/{id}")
                .buildAndExpand(savedUser.getId())
                .toUri();
        return ResponseEntity.created(location).body(savedUser);
    }

    // 获取单个用户
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.findById(id);

    }

    // 更新用户
    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(@PathVariable Long id, @Validated @RequestBody User user) {
        return ResponseEntity.ok(userService.update(id, user));
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        userService.deleteById(id);
        return ResponseEntity.noContent().build();
    }
}
2. 标准化响应格式
@Data
public class ApiResponse<T> {
    private int code;
    private String message;
    private T data;
    private Instant timestamp;

    // 构造函数
    public ApiResponse(int code, String message, T data, Instant timestamp) {
        this.code = code;
        this.message = message;
        this.data = data;
        this.timestamp = timestamp;
    }

    // 成功响应快捷方法
    public static <T> ApiResponse<T> success(T data) {
        return new ApiResponse<>(200, "Success", data, Instant.now());
    }

    // 失败响应快捷方法
    public static <T> ApiResponse<T> failure(int code, String message) {
        return new ApiResponse<>(code, message, null, Instant.now());
    }

   
}

// 控制器统一返回 ApiResponse
 @GetMapping("/{id}")
    public ApiResponse<User> getUser1(@PathVariable Long id) {
        // 尝试从服务层获取用户
        User user = userService.findById(id);
        if (user != null) {
            // 如果用户存在,返回成功响应
            return ApiResponse.success(user);
        } else {
            // 如果用户不存在,返回失败响应
            return ApiResponse.failure(404, "User not found");
        }
    }

在这里插入图片描述

四、高级特性与最佳实践
1. 全局异常处理

/**
 * GlobalExceptionHandler - 类功能描述
 *
 * @author csdn:曼岛_
 * @version 1.0
 * @date 2025/5/13 15:50
 * @since OPENJDK 17
 */

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    
    // 处理参数校验异常 (422)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
    public ApiResponse<Map<String, String>> handleValidation(MethodArgumentNotValidException ex) {
        Map<String, String> errors = ex.getBindingResult()
                .getFieldErrors()
                .stream()
                .collect(Collectors.toMap(
                        FieldError::getField,
                        FieldError::getDefaultMessage,
                        (existing, replacement) -> existing + ", " + replacement
                ));

        log.warn("Validation failed: {}", errors);
        return new ApiResponse<>(
                HttpStatus.UNPROCESSABLE_ENTITY.value(),
                "Validation failed",
                errors
        );
    }

    // 处理通用异常 (500)
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResponse<?> handleGlobalException(Exception ex) {
        log.error("Unexpected error occurred: {}", ex.getMessage(), ex);
        return new ApiResponse<>(
                HttpStatus.INTERNAL_SERVER_ERROR.value(),
                "Internal server error"
        );
    }

    // 统一响应结构(示例)
    @Data
    public static class ApiResponse<T> {
        private final Instant timestamp = Instant.now();
        private int status;
        private String message;
        private T data;

        public ApiResponse(int status, String message) {
            this(status, message, null);
        }

        public ApiResponse(int status, String message, T data) {
            this.status = status;
            this.message = message;
            this.data = data;
        }
    }
}
2. API 版本控制

方式一:URI 路径版本

@RestController
@RequestMapping("/api/v2/users")
public class UserControllerV2 { ... }

方式二:请求头版本

@GetMapping(headers = "X-API-Version=2")
public ResponseEntity<User> getUserV2(...) { ... }
3. 安全防护
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/**").authenticated()
                .anyRequest().permitAll()
            )
            .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
        return http.build();
    }
}
五、RESTful API 设计规范
HTTP 方法语义幂等性安全
GET获取资源
POST创建资源
PUT全量更新资源
PATCH部分更新资源
DELETE删除资源

状态码使用规范

  • 200 OK:常规成功响应
  • 201 Created:资源创建成功
  • 204 No Content:成功无返回体
  • 400 Bad Request:客户端请求错误
  • 401 Unauthorized:未认证
  • 403 Forbidden:无权限
  • 404 Not Found:资源不存在
  • 429 Too Many Requests:请求限流
六、开发工具与测试
1. API 文档生成(Swagger)
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.1.0</version>
</dependency>

访问 http://localhost:8080/swagger-ui.html 查看文档。

2. 单元测试(MockMVC)
@SpringBootTest
@AutoConfigureMockMvc
class UserControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void getUser_Returns200() throws Exception {
        mockMvc.perform(get("/api/v1/users/1")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.name").value("John"));
    }
}
3. 性能测试(JMeter)
  • 创建线程组模拟并发请求
  • 添加 HTTP 请求采样器
  • 使用聚合报告分析吞吐量
七、企业级优化策略
  1. 分页与过滤
@GetMapping
public Page<User> getUsers(
        @RequestParam(required = false) String name,
        @PageableDefault(sort = "id", direction = DESC) Pageable pageable) {
    return userService.findByName(name, pageable);
}
  1. 缓存优化
@Cacheable(value = "users", key = "#id")
public User getUser(Long id) { ... }
  1. 请求限流
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .requestMatchers("/api/**").access(
            new WebExpressionAuthorizationManager(
                "@rateLimiter.tryConsume(request, 10, 60)" // 每分钟10次
            )
        );
}
八、常见错误与解决方案
错误现象原因修复方案
415 Unsupported Media Type未设置 Content-Type请求头添加 Content-Type: application/json
406 Not Acceptable客户端不支持服务端返回格式添加 Accept: application/json
跨域请求失败未配置 CORS添加 @CrossOrigin 或全局配置
九、总结

通过 Spring Boot 构建 RESTful API 需遵循六大设计原则,结合 HATEOAS、全局异常处理、版本控制等特性,可打造高效、易维护的企业级接口。关键注意点:

  1. 语义明确:合理使用 HTTP 方法和状态码
  2. 安全可靠:集成 OAuth2、请求限流
  3. 文档完善:结合 Swagger 生成实时文档

附录

希望本教程对您有帮助,请点赞❤️收藏⭐关注支持!欢迎在评论区留言交流技术细节!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

曼岛_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值