Java企业级开发实战:基于Spring Boot 3的高性能REST API设计与实现
一、现代REST API架构设计
高性能API核心组件:
- Spring Boot 3:基础框架
- Spring Security:认证授权
- Spring Data JPA:数据持久化
- Redis:缓存与速率限制
- OpenAPI:API文档生成
二、项目初始化与配置
1. 使用Spring Initializr创建项目
// 选择依赖:
// - Spring Web
// - Spring Data JPA
// - Spring Security
// - Lombok
// - H2 Database
// - Redis
// - OpenAPI
// application.yml配置示例
spring:
datasource:
url: jdbc:h2:mem:testdb
driver-class-name: org.h2.Driver
username: sa
password: password
jpa:
hibernate:
ddl-auto: update
show-sql: true
cache:
type: redis
redis:
host: localhost
port: 6379
三、核心功能实现
1. 领域模型设计
// 用户实体
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String username;
@Column(nullable = false)
private String password;
@Enumerated(EnumType.STRING)
private Role role;
@CreationTimestamp
private LocalDateTime createdAt;
}
// 产品实体
@Entity
@Data
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
private String description;
@Column(nullable = false)
private BigDecimal price;
@ManyToOne
private User createdBy;
}
2. 安全配置
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final JwtAuthenticationFilter jwtAuthFilter;
private final AuthenticationProvider authenticationProvider;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()
.requestMatchers("/api/products/**").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated()
)
.sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}
四、业务逻辑实现
1. JWT认证服务
@Service
@RequiredArgsConstructor
public class AuthService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final JwtService jwtService;
private final AuthenticationManager authenticationManager;
public AuthResponse register(RegisterRequest request) {
var user = User.builder()
.username(request.getUsername())
.password(passwordEncoder.encode(request.getPassword()))
.role(Role.USER)
.build();
userRepository.save(user);
var jwtToken = jwtService.generateToken(user);
return AuthResponse.builder()
.token(jwtToken)
.build();
}
public AuthResponse authenticate(AuthRequest request) {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
request.getUsername(),
request.getPassword()
)
);
var user = userRepository.findByUsername(request.getUsername())
.orElseThrow();
var jwtToken = jwtService.generateToken(user);
return AuthResponse.builder()
.token(jwtToken)
.build();
}
}
2. 产品服务实现
@Service
@RequiredArgsConstructor
public class ProductService {
private final ProductRepository productRepository;
private final UserRepository userRepository;
private final CacheManager cacheManager;
@Cacheable(value = "products", key = "#id")
public ProductDto getProductById(Long id) {
Product product = productRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Product not found"));
return mapToDto(product);
}
@CacheEvict(value = "products", allEntries = true)
public ProductDto createProduct(ProductRequest request, String username) {
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new ResourceNotFoundException("User not found"));
Product product = Product.builder()
.name(request.getName())
.description(request.getDescription())
.price(request.getPrice())
.createdBy(user)
.build();
Product savedProduct = productRepository.save(product);
return mapToDto(savedProduct);
}
private ProductDto mapToDto(Product product) {
return ProductDto.builder()
.id(product.getId())
.name(product.getName())
.description(product.getDescription())
.price(product.getPrice())
.createdBy(product.getCreatedBy().getUsername())
.createdAt(product.getCreatedAt())
.build();
}
}
五、API设计与文档
1. REST控制器
@RestController
@RequestMapping("/api/products")
@RequiredArgsConstructor
@Tag(name = "Product", description = "Product management APIs")
public class ProductController {
private final ProductService productService;
@GetMapping("/{id}")
@Operation(summary = "Get product by ID")
public ResponseEntity getProductById(@PathVariable Long id) {
return ResponseEntity.ok(productService.getProductById(id));
}
@PostMapping
@Operation(summary = "Create new product")
public ResponseEntity createProduct(
@RequestBody @Valid ProductRequest request,
@AuthenticationPrincipal UserDetails userDetails) {
return ResponseEntity
.status(HttpStatus.CREATED)
.body(productService.createProduct(request, userDetails.getUsername()));
}
}
2. OpenAPI配置
@Configuration
public class OpenApiConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("Product API")
.version("1.0")
.description("API for product management")
.license(new License().name("Apache 2.0")))
.externalDocs(new ExternalDocumentation()
.description("Spring Boot Documentation")
.url("https://spring.io/projects/spring-boot"))
.addSecurityItem(new SecurityRequirement().addList("bearerAuth"))
.components(new Components()
.addSecuritySchemes("bearerAuth", new SecurityScheme()
.name("bearerAuth")
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")));
}
}