# CLAUDE.md This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. ## 始终使用中文回复 - 在所有沟通和代码注释中,必须使用中文进行交流 - 保持语言的专业性和技术准确性 ## mcp 工具使用 - 当涉及到相关库的使用时,应该用 context7 查询相关文档 ## Project Overview FlashSaleSystem is a high-concurrency flash sale (秒杀) system built with Spring Boot and Redis Cluster. The system implements distributed architecture with anti-overselling mechanisms, rate limiting, and distributed locking using Redis and Lua scripts. **Project Completion**: 90% ## Core Architecture ### Technology Stack - **Backend**: Spring Boot 2.7.6, Java 1.8 - **Database**: MySQL 5.7+ with JPA/Hibernate - **Cache**: Redis 6.0+ Cluster (6 nodes) with Redisson 3.24.3 - **Frontend**: JSP + JSTL + Bootstrap 5 + jQuery - **Build Tool**: Maven 3.6+ - **API Documentation**: Knife4j 4.1.0 (Swagger) ### Key Components - **Controllers**: Handle HTTP requests for different modules (flash sales, cart, orders, admin) - **Services**: Business logic layer with Redis-based caching and distributed operations - **Repositories**: JPA data access layer for MySQL operations - **DTOs**: Data transfer objects for API communication - **Entities**: JPA entities mapping to database tables ### Package Structure ``` com.org.flashsalesystem/ ├── controller/ # REST controllers and web endpoints ├── service/ # Business logic and Redis operations ├── repository/ # JPA repositories for data access ├── entity/ # JPA entities (User, Product, Order, FlashSale) ├── dto/ # Data transfer objects ├── config/ # Configuration classes (Redis, Swagger, Web) └── util/ # Utility classes and JSP functions ``` ### Redis Integration - **Multiple Modes Supported**: Single node, Cluster (6 nodes), Sentinel - **Mode Selection**: Automatic based on configuration in application.yml - **Default Mode**: Single node (localhost:6379) for development - **Cluster Configuration**: 6-node Redis cluster at 42.192.62.91:7000-7005 via RedissonConfig - **Data Types**: String (locks, sessions), Hash (user/product info, cart), List (order queues), Set (successful users), ZSet (rankings) - **Lua Scripts**: Atomic operations for flash sales, distributed locks, rate limiting, cart operations - **Message Queues**: Pub/Sub channels - order:status:change, stock:change, flashsale:result ### Redis Key Prefixes - `flashsale:` - Flash sale activity data - `flashsale_stock:` - Real-time stock information - `flashsale_lock:` - Distributed locks for flash sales - `flashsale_success:` - Successful user sets - `user:` - User information cache - `product:` - Product information cache - `cart:` - Shopping cart data - `rate_limit:` - API rate limiting counters ## Common Development Commands ### Build and Run ```bash # 编译项目 mvn clean compile # 运行应用(默认单节点Redis) mvn spring-boot:run # 运行应用(开发环境,单节点Redis) mvn spring-boot:run -Dspring.profiles.active=dev # 运行应用(生产环境,Redis集群) mvn spring-boot:run -Dspring.profiles.active=cluster # 打包应用 mvn clean package # 跳过测试打包 mvn clean package -DskipTests # 运行打包后的jar(默认配置) java -jar target/FlashSaleSystem-0.0.1-SNAPSHOT.jar # 运行打包后的jar(指定profile) java -jar target/FlashSaleSystem-0.0.1-SNAPSHOT.jar --spring.profiles.active=cluster ``` ### Testing ```bash # 运行所有测试(目前无测试类,需要创建) mvn test # 运行特定测试类 mvn test -Dtest=FlashSaleServiceTest mvn test -Dtest=RedisServiceTest # 运行集成测试 mvn verify ``` ### Database Setup ```bash # 创建数据库 mysql -u root -p CREATE DATABASE flash_sale_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; # 导入表结构(JPA会自动创建,但也可以手动导入) mysql -u root -p flash_sale_db < src/main/resources/sql/schema.sql # 导入测试数据 mysql -u root -p flash_sale_db < src/main/resources/sql/test-data.sql # 导入演示用户(包含预设密码) mysql -u root -p flash_sale_db < src/main/resources/sql/demo-users.sql ``` ## Application Configuration ### Key Configuration Files - `application.yml`: Main application configuration including Redis cluster, database, and custom flash sale settings - `pom.xml`: Maven dependencies and build configuration - `src/main/resources/lua/`: Lua scripts for Redis atomic operations ### Important Configuration Sections - **Redis Mode**: Supports Single node (default), Cluster (6 nodes), Sentinel modes - **Redis Single Node**: localhost:6379 (default for development) - **Redis Cluster**: 6-node cluster with password authentication (6HU3cw1drNjfQ0zo1Uyx) - **Flash Sale Settings**: Rate limiting (10 requests/minute), max quantity per user (1), stock preload (30min advance) - **Cache TTL**: User info (30min), product info (60min), flash sale data (10min) - **Database**: HikariCP connection pool (max 20, min 5) - **Cart Settings**: Expire after 7 days, max 20 items ### Redis Mode Switching 1. **Single Node Mode** (Default): - Edit `application.yml` and ensure cluster configuration is commented out - Or use profile: `mvn spring-boot:run -Dspring.profiles.active=dev` 2. **Cluster Mode**: - Use profile: `mvn spring-boot:run -Dspring.profiles.active=cluster` - Or uncomment cluster configuration in `application.yml` 3. **Environment Variable Override**: ```bash export SPRING_REDIS_HOST=your-redis-host export SPRING_REDIS_CLUSTER_NODES=node1:7000,node2:7001 ``` ## Development Guidelines ### Service Layer Patterns - All Redis operations use Redisson for cluster support - Critical operations (stock deduction, cart updates) use Lua scripts for atomicity - Distributed locks prevent overselling using Redisson's RLock with timeout - Rate limiting implemented via sliding window algorithm in Lua - Use RedisPipelineService for batch operations to improve performance ### Key Services - **FlashSaleService**: Core flash sale logic with distributed locking and Lua scripts - **RedisService**: Generic Redis operations wrapper with TTL support - **DistributedLockService**: Distributed locking abstraction with auto-renewal - **RateLimitService**: API rate limiting using Redis sliding window - **CartService**: Shopping cart operations with Redis Hash storage - **RedisPipelineService**: Batch Redis operations using pipeline - **MessageListenerService**: Redis Pub/Sub message handling ### Flash Sale Process Flow 1. **Stock Preload**: FlashSaleService.preloadStock() loads stock to Redis 30min before 2. **Rate Limit Check**: RateLimitService.isAllowed() checks request frequency 3. **Distributed Lock**: DistributedLockService.tryLock() prevents concurrent access 4. **Stock Check**: Lua script atomically checks and deducts stock 5. **Order Creation**: Creates order in database and publishes result 6. **Cache Update**: Updates user success set and publishes notifications ### Testing Approach - Unit tests should be created for core services (FlashSaleService, RedisService, CartService) - Integration tests should verify Redis cluster connectivity and database operations - Load testing recommended using JMeter for flash sale scenarios - Mock Redis operations in unit tests using Mockito ## Lua Script Usage The system includes 5 Lua scripts in `src/main/resources/lua/`: - `flashsale.lua`: Atomic stock deduction with overselling prevention (returns: remaining stock or negative error codes) - `distributed_lock.lua`: Distributed lock acquisition with expiry - `unlock.lua`: Safe distributed lock release with owner verification - `rate_limit.lua`: Sliding window rate limiting (returns: 1 if allowed, 0 if blocked) - `cart_operation.lua`: Atomic shopping cart operations (add/update/remove items) ### Lua Script Error Codes - `-1`: Key not exists or invalid - `-2`: Insufficient stock - `-3`: Invalid parameter ## API Documentation - **Swagger UI**: http://localhost:8080/doc.html (Knife4j enhanced UI) - **API Docs**: http://localhost:8080/v3/api-docs - **Test Endpoints**: TestController provides Redis connection and data verification endpoints ## Monitoring and Health - **Actuator Endpoints**: /actuator/health, /actuator/metrics, /actuator/prometheus - **Log Files**: logs/flash-sale-system.log with detailed Redis and SQL logging - **Debug Level**: Enabled for com.org.flashsalesystem, org.springframework.data.redis, org.hibernate.SQL - **Metrics Export**: Prometheus metrics enabled for monitoring ## Security Considerations - **Redis Authentication**: Cluster uses password authentication - **Database Connection**: Uses HikariCP with SSL disabled (enable for production) - **Password Encoding**: BCrypt with strength 10 for user passwords - **Rate Limiting**: Built-in rate limiting to prevent abuse - **Session Management**: Redis-based session storage with 30min timeout ## Performance Optimization - **Connection Pooling**: HikariCP (20 max) for DB, Jedis pool (20 max) for Redis - **Pipeline Operations**: Use RedisPipelineService for batch operations - **Cache Strategy**: Multi-level caching with appropriate TTL - **Lua Scripts**: Reduce network round trips for atomic operations - **Stock Preload**: Warm up cache before flash sale starts ## Common Issues and Solutions 1. **Redis Connection Failed**: Check cluster nodes accessibility and password 2. **Stock Overselling**: Ensure Lua scripts are loaded and distributed locks work 3. **High Latency**: Use pipeline for batch operations, check network latency 4. **Memory Issues**: Monitor Redis memory usage, adjust cache TTL if needed