# Generate Cursor Rules - 实际案例示例

> 本文档展示了使用 `/generate rules` 命令自动生成项目规则的完整过程和结果
> 
> **项目背景：** 微服务架构的停车管理系统（Spring Boot + Spring Cloud）  
> **生成时间：** 2025年6月27日  
> **Cursor版本：** 1.1.4

## 使用场景

这是一个真实的 `/generate rules` 命令使用案例，展示了如何为复杂的多模块Java项目快速生成全面的开发规则。该项目包含4个微服务模块，使用Spring Cloud技术栈，集成了MQTT、Redis、Kafka等多种技术。

## 生成过程

---

**用户输入：**

```
/Generate Cursor Rules 
```

**Cursor响应：**

I'll analyze the codebase structure and create comprehensive Cursor Rules to help with navigation and understanding of this microservices project. Let me first examine some key files to understand the architecture better.

Now let me check a few more key files to understand the other services:

Now I'll create comprehensive Cursor Rules for this microservices project. Let me create the rules directory and add the rule file:

```plaintext
# Microservices Architecture Guide

## Project Overview

This is a microservices-based parking management system built with Spring Boot 1.5.13 and Spring Cloud Edgware.SR4. The project consists of 4 main microservices organized as Maven modules under the parent POM [pom.xml](mdc:pom.xml).

## Project Structure

### Parent Project
- **Root**: [pom.xml](mdc:pom.xml) - Main Maven parent POM with shared dependencies
- **Architecture**: Multi-module Maven project with Spring Cloud microservices
- **Version**: 1.1.0 with Java 8 and custom framework version 1.1.0

### Microservices Overview

#### 1. micro-cloud-adapter
- **Purpose**: MQTT Gateway and IoT Device Adapter
- **Entry Point**: [micro-cloud-adapter/src/main/java/com/zhht/BootstrapApplication.java](mdc:micro-cloud-adapter/src/main/java/com/zhht/BootstrapApplication.java)
- **Key Features**: MQTT message handling, device communication, IoT gateway functionality
- **Documentation**: [micro-cloud-adapter/MQTT_SOLUTION_GUIDE.md](mdc:micro-cloud-adapter/MQTT_SOLUTION_GUIDE.md)
- **Configuration**: [micro-cloud-adapter/src/main/resources/application-template.yml](mdc:micro-cloud-adapter/src/main/resources/application-template.yml)

#### 2. micro-cprs 
- **Purpose**: Core Processing and Routing Service
- **Entry Point**: [micro-cprs/src/main/java/com/zhht/BootstrapApplication.java](mdc:micro-cprs/src/main/java/com/zhht/BootstrapApplication.java)
- **Key Features**: Main business logic processing, service orchestration
- **Configuration**: [micro-cprs/src/main/resources/application-template.yml](mdc:micro-cprs/src/main/resources/application-template.yml)

#### 3. micro-dts
- **Purpose**: Data Transfer and Synchronization Service
- **Entry Point**: [micro-dts/src/main/java/com/zhht/BootstrapApplication.java](mdc:micro-dts/src/main/java/com/zhht/BootstrapApplication.java)
- **Key Features**: Third-party data synchronization, external system integration
- **Note**: Excludes DataSourceAutoConfiguration and HibernateJpaAutoConfiguration
- **Configuration**: [micro-dts/src/main/resources/application-template.yml](mdc:micro-dts/src/main/resources/application-template.yml)

#### 4. micro-edrs
- **Purpose**: External Data Routing Service
- **Entry Point**: [micro-edrs/src/main/java/com/zhht/BootstrapApplication.java](mdc:micro-edrs/src/main/java/com/zhht/BootstrapApplication.java)
- **Key Features**: External data routing, third-party integrations
- **Database**: [micro-edrs/micro-edrs.sql](mdc:micro-edrs/micro-edrs.sql)
- **Configuration**: [micro-edrs/src/main/resources/application-template.yml](mdc:micro-edrs/src/main/resources/application-template.yml)

## Common Architecture Patterns

### Spring Boot Configuration
All services follow standard Spring Boot patterns:
- **@SpringBootApplication** - Main application annotation
- **@EnableEurekaClient** - Service discovery with Eureka
- **@EnableFeignClients** - Feign client for inter-service communication
- **@EnableSwagger2** - API documentation

### Package Structure Convention
Each service follows the pattern: `com.zhht.{component}`
- **controller/** - REST API endpoints
- **service/** - Business logic layer
- **entity/** - Data entities and DTOs
- **config/** - Configuration classes
- **feign/** - Feign client interfaces
- **utils/** - Utility classes

### Key Dependencies
- **Spring Cloud**: Service discovery, configuration, circuit breakers
- **Redis**: Caching with `spring-boot-starter-data-redis`
- **Kafka**: Message queuing and event streaming
- **MyBatis**: Database ORM with custom starter
- **Zipkin**: Distributed tracing
- **Hystrix**: Circuit breaker pattern
- **Lombok**: Code generation

## Configuration Management

### Application Configuration
Each service has template configurations:
- `application-template.yml` - Template configuration file
- `application.yml` - Environment-specific configuration
- `bootstrap.yml` - Bootstrap configuration for Spring Cloud

### Assembly Configuration
Each service includes assembly configuration:
- `src/assembly/conf/assembly-config.xml` - Maven assembly descriptor
- `src/assembly/bin/bootstrap.sh` - Startup script

## Inter-Service Communication

### Feign Clients
Services communicate via Feign clients located in `feign/` packages:
- Declarative REST clients
- Circuit breaker integration with Hystrix
- Fallback implementations in `feign/fallback/`

### Message Queues
- **Kafka**: Event-driven communication
- **MQTT**: IoT device communication (cloud-adapter)

## Database and Persistence

### MyBatis Integration
- Custom MyBatis starter from framework
- Mapper XML files in `src/main/resources/mapper/`
- DAO interfaces following naming convention

### Redis Caching
- `RedisCacheTemplate` - Common caching utility
- Cache keys defined in constant classes

## Development and Deployment

### Build Configuration
- Maven multi-module project
- Assembly plugin for packaging
- Resource filtering with UTF-8 encoding
- Hot deployment with spring-boot-devtools

### Health Monitoring
- Spring Boot Actuator endpoints
- Custom health check controllers
- Spring Boot Admin integration

## Key Files to Reference

### Configuration
- [pom.xml](mdc:pom.xml) - Parent POM with all dependencies
- Service-specific POMs in each module
- `application-template.yml` files for service configuration

### Entry Points
- [micro-cloud-adapter/src/main/java/com/zhht/BootstrapApplication.java](mdc:micro-cloud-adapter/src/main/java/com/zhht/BootstrapApplication.java)
- [micro-cprs/src/main/java/com/zhht/BootstrapApplication.java](mdc:micro-cprs/src/main/java/com/zhht/BootstrapApplication.java)
- [micro-dts/src/main/java/com/zhht/BootstrapApplication.java](mdc:micro-dts/src/main/java/com/zhht/BootstrapApplication.java)
- [micro-edrs/src/main/java/com/zhht/BootstrapApplication.java](mdc:micro-edrs/src/main/java/com/zhht/BootstrapApplication.java)

### Documentation
- [micro-cloud-adapter/MQTT_SOLUTION_GUIDE.md](mdc:micro-cloud-adapter/MQTT_SOLUTION_GUIDE.md) - MQTT implementation guide
- [readme.txt](mdc:readme.txt) - Project overview

## Development Guidelines

### Adding New Features
1. Identify the appropriate service based on responsibility
2. Follow the package structure convention
3. Add necessary Feign clients for inter-service communication
4. Update configuration templates as needed

### Service Communication
- Use Feign clients for synchronous communication
- Use Kafka for asynchronous event processing
- Use MQTT for IoT device communication (cloud-adapter only)

### Configuration
- All environment-specific values should be externalized
- Use Spring Cloud Config for centralized configuration
- Follow the `application-template.yml` pattern for new configurations
```

Now let me create a second rule file that focuses on specific coding patterns and conventions used in this project:

```plaintext
# Coding Patterns and Conventions

## Package Structure Patterns

### Standard Package Layout
Each microservice follows this package structure under `com.zhht`:
```
├── BootstrapApplication.java          # Main application entry point
├── config/                           # Configuration classes
├── controller/                       # REST API controllers
├── service/                         # Business logic layer
│   └── impl/                        # Service implementations
├── entity/                          # Data entities
│   ├── dto/                         # Data Transfer Objects
│   └── bo/                          # Business Objects
├── dao/                             # Data Access Objects
├── feign/                           # Feign client interfaces
│   └── fallback/                    # Feign fallback implementations
├── utils/                           # Utility classes
├── constant/                        # Constants and enums
├── cache/                           # Cache key definitions
├── aop/                             # Aspect-Oriented Programming
└── handler/                         # Message/Event handlers
```

## Spring Boot Configuration Patterns

### Application Entry Point
All services use consistent annotations:
```java
@SpringBootApplication
@EnableEurekaClient          // Service discovery
@EnableFeignClients          // Inter-service communication
@EnableSwagger2              // API documentation
@EnableAspectJAutoProxy      // AOP support (where needed)
```

### Configuration Classes
- **Config classes**: Located in `config/` package
- **Redis Configuration**: `RedissonConfig`, `RedissonConfigProperty`
- **Cache Templates**: `RedisCacheTemplate` for standardized caching
- **Service-specific configs**: MQTT, DTS, etc.

## Controller Patterns

### Health Check Controllers
Every service includes: `CheckAliveController.java`
- Standard health check endpoint
- Service availability monitoring
- Consistent across all microservices

### REST Controller Conventions
- Controllers in `controller/` package
- Use `@RestController` annotation
- Follow RESTful naming conventions
- Include proper HTTP status codes

## Service Layer Patterns

### Service Interface Pattern
- Interfaces in `service/` package
- Implementations in `service/impl/` package
- Use `@Service` annotation on implementations

### Inter-Service Communication
- **Feign Clients**: Located in `feign/` package
- **Fallback Pattern**: Implementations in `feign/fallback/`
- **Circuit Breaker**: Hystrix integration for resilience

## Data Access Patterns

### MyBatis Integration
- **DAO Interfaces**: Located in `dao/` package
- **Mapper XML**: Located in `src/main/resources/mapper/`
- **Naming Convention**: `{Entity}Dao.java` and `{Entity}Mapper.xml`

### Entity Structure
- **DTOs**: Data Transfer Objects in `entity/dto/`
- **BOs**: Business Objects in `entity/bo/`
- **VOs**: Value Objects in service-specific `vo/` packages

## Caching Patterns

### Redis Integration
- **Cache Template**: Use `RedisCacheTemplate` utility class
- **Cache Keys**: Define in constant classes (e.g., `CacheKey.java`)
- **Key Conventions**: Use descriptive, hierarchical key names

### Cache Key Management
Example cache key classes:
- `micro-cprs`: `CacheKey.java`, `MsTerminalCacheKey.java`
- `micro-cloud-adapter`: `CcaCacheKey.java`
- `micro-dts`: `AcgCacheKey.java`

## Message Queue Patterns

### MQTT Implementation (micro-cloud-adapter)
Key classes for MQTT:
- `MqttConfig.java` - Configuration with fixed ClientId
- `MqttMessageHandler.java` - Message processing
- `MqttHealthMonitor.java` - Connection monitoring
- **Fixed ClientId Pattern**: Use hostname-based IDs for reconnection
- **Session Persistence**: `cleanSession=false` for reliability

### Kafka Integration
- **Consumer Listeners**: `*ConsumerListener.java` classes
- **Message Handlers**: Located in `handler/` package
- **Configuration**: `MQConfiguration.java`

## Configuration Management

### Application Configuration
Standard configuration files in each service:
- `application-template.yml` - Template with placeholders
- `application.yml` - Environment-specific values
- `bootstrap.yml` - Bootstrap configuration for Spring Cloud

### Environment Variable Pattern
Use `${variable.name}` syntax in YAML files for externalization:
```yaml
mqtt:
  broker: ${mqtt.server.ws.url}
  username: ${mqtt.server.username}
  password: ${mqtt.server.password}
```

## Error Handling and Resilience

### Circuit Breaker Pattern
- **Hystrix Integration**: Enabled in all services
- **Fallback Methods**: Implement in `feign/fallback/` classes
- **Timeout Configuration**: Set appropriate timeouts for service calls

### Aspect-Oriented Programming
- **Logging Aspects**: `*LoggingAspect.java` classes
- **Controller Aspects**: `ControllerAspect.java` for cross-cutting concerns

## Utility Patterns

### Common Utilities
Standard utility classes across services:
- `ByteUtils.java` - Byte manipulation utilities
- `CrcUtil.java` - CRC calculation utilities
- `IPUtil.java` - IP address utilities
- `SpringContextUtils.java` - Spring context access

### Date and Time Handling
- Use consistent date/time patterns across services
- Handle timezone considerations for multi-region deployment

## Testing Patterns

### Test Structure
- **Test Classes**: Mirror main package structure
- **Base Test Classes**: `BaseControllerTest.java` for common test setup
- **Service-Specific Tests**: Focus on business logic validation

## Assembly and Deployment

### Assembly Configuration
Each service includes:
- `src/assembly/conf/assembly-config.xml` - Maven assembly descriptor
- `src/assembly/bin/bootstrap.sh` - Startup script

### Build Patterns
- **Multi-module Maven**: Parent POM manages dependencies
- **Resource Filtering**: UTF-8 encoding and property substitution
- **Hot Deployment**: Development support with spring-boot-devtools

## Naming Conventions

### Class Naming
- **Controllers**: `*Controller.java`
- **Services**: `*Service.java` (interface), `*ServiceImpl.java` (implementation)
- **DAOs**: `*Dao.java`
- **DTOs**: `*DTO.java`
- **Configurations**: `*Config.java` or `*Configuration.java`
- **Constants**: `Constants.java` or specific constant classes

### Method Naming
- **Service Methods**: Use descriptive business action names
- **Controller Methods**: Follow REST conventions (get, post, put, delete)
- **DAO Methods**: Use standard CRUD naming (insert, select, update, delete)

## Logging Patterns

### Logging Configuration
- **Logback**: Standard logging framework
- **Configuration**: `logback-spring.xml` in each service
- **Structured Logging**: Use consistent log formats across services

### Log Levels
- **DEBUG**: Detailed application flow
- **INFO**: General application events
- **WARN**: Unexpected but recoverable situations
- **ERROR**: Error conditions that don't stop the application
```

Perfect! I've created two comprehensive Cursor Rules files for your microservices project:

## 📋 Generated Cursor Rules

### 1. **Microservices Architecture Guide** (`.cursor/rules/microservices-architecture.mdc`)
This rule provides a high-level overview of your project structure including:
- **Project Overview**: Spring Boot 1.5.13 + Spring Cloud microservices architecture
- **Service Breakdown**: Detailed description of all 4 microservices (cloud-adapter, cprs, dts, edrs)
- **Key Technologies**: Spring Cloud, Redis, Kafka, MQTT, MyBatis, etc.
- **Configuration Management**: Template files and environment setup
- **Development Guidelines**: Best practices for adding features and service communication

### 2. **Coding Patterns and Conventions** (`.cursor/rules/coding-patterns.mdc`)
This rule focuses on implementation details and coding standards:
- **Package Structure**: Standardized layout across all services
- **Spring Boot Patterns**: Consistent annotations and configuration approaches
- **Service Communication**: Feign clients, circuit breakers, and message queues
- **Data Access**: MyBatis integration and entity patterns
- **Caching**: Redis patterns and key management
- **Naming Conventions**: Class and method naming standards

## 🎯 Key Benefits

These rules will help you and your team:
- **Navigate** the codebase more efficiently with direct file references
- **Understand** the architecture and service responsibilities
- **Follow** established patterns when adding new features
- **Maintain** consistency across the microservices
- **Troubleshoot** issues by understanding the system structure

The rules include direct file links using the `[filename](mdc:filename)` format, making it easy to jump to relevant files when working on specific features or debugging issues.

Your Cursor IDE will now have comprehensive context about this parking management microservices system, including the MQTT gateway functionality, core processing services, data synchronization, and external routing capabilities.

---

## 使用效果总结

### 生成内容概览

通过 `/generate rules` 命令，Cursor自动生成了两个详细的规则文档：

1. **microservices-architecture.mdc** - 架构指南
   - 项目整体架构说明
   - 4个微服务的职责和入口点
   - 技术栈和依赖管理
   - 服务间通信方式

2. **coding-patterns.mdc** - 编码规范
   - 包结构和命名约定
   - Spring Boot配置模式
   - 数据访问和缓存模式
   - 错误处理和部署规范

### 关键价值

✅ **自动化分析**：无需手动整理复杂的项目结构  
✅ **全面覆盖**：涵盖架构、编码、配置、部署各层面  
✅ **实用性强**：包含具体的文件路径和代码示例  
✅ **团队协作**：新成员快速理解项目规范  
✅ **持续更新**：随项目演进不断完善规则  

### 最佳实践建议

1. **定期更新**：项目结构变化时重新运行命令
2. **团队共享**：将生成的规则加入项目文档
3. **定制化**：根据团队需求调整和补充规则
4. **版本控制**：将规则文件纳入Git管理

### 适用场景

- ✅ 多模块/微服务项目
- ✅ 复杂技术栈集成
- ✅ 团队协作开发
- ✅ 新成员培训
- ✅ 代码规范统一

这个案例完美展示了Cursor首席设计师第1条黄金法则的实际应用价值。

