Commit 5ec5029c by 岳建彬

add 12 gold suggestions

parent ace6cbf5
# Cursor首席设计师12条黄金法则:高质量代码生成技巧
> 来源:Cursor首席设计师Ryo Lu分享的AI编程最佳实践
## 核心理念
使用Cursor得当 = 快速、干净的代码
使用不当 = AI意大利面,你得收拾一整周
## 12条黄金法则
![image-20250627175927166](..\assets\images\RyoLu-cursor-usage-suggestion-12.png)
### 中英文对照表
| 序号 | 原文 | 翻译 |
|------|----------|----------|
| 1 | Set 5-10 clear project rules upfront so Cursor knows your structure and constraints. Try /generate rules for existing codebases. | 预先设定5-10条明确的项目规则,让Cursor了解你的结构和限制。对于现有代码库,可以尝试使用/generate rules命令。 |
| 2 | Be specific in prompts. Spell out tech stack, behavior, and constraints like a mini spec. | 在提示中要具体明确。像写一份微型规格书一样,详细说明技术栈、行为和约束条件。 |
| 3 | Work file by file; generate, test, and review in small, focused chunks. | 逐文件处理;以小而专注的模块为单位进行生成、测试和审查。 |
| 4 | Write tests first, lock them, and generate code until all tests pass. | 先写测试,锁定它们,然后生成代码直到所有测试通过。 |
| 5 | Always review AI output and hard‑fix anything that breaks, then tell Cursor to use them as examples. | 始终审查AI的输出,对任何出错的地方进行硬性修复,然后告诉Cursor以这些修复作为示例。 |
| 6 | Use @ file, @ folders, @ git to scope Cursor's attention to the right parts of your codebase. | 使用@file、@folders、@git来限定Cursor对代码库中正确部分的注意力范围。 |
| 7 | Keep design docs and checklists in .cursor/ so the agent has full context on what to do next. | 将设计文档和检查清单保存在.cursor/目录下,这样代理就能全面了解下一步该做什么。 |
| 8 | If code is wrong, just write it yourself. Cursor learns faster from edits than explanations. | 如果代码有误,直接自己动手修改。Cursor从编辑中学习的速度比解释更快。 |
| 9 | Use chat history to iterate on old prompts without starting over. | 利用聊天记录迭代旧提示,无需从头开始。 |
| 10 | Choose models intentionally. Gemini for precision, Claude for breadth. | 有意识地选择模型。Gemini用于精确性,Claude用于广度。 |
| 11 | In new or unfamiliar stacks, paste in link to documentation. Make Cursor explain all errors and fixes line by line. | 在新的或不熟悉的技术栈中,粘贴文档链接。让Cursor逐行解释所有错误和修复。 |
| 12 | Let big projects index overnight and limit context scope to keep performance snappy. | 让大项目过夜索引,并限制上下文范围以保持性能敏捷。 |
### 1. 设定明确的项目规则
**核心:** 预先设定5-10条明确的项目规则,让Cursor了解你的结构和限制
**操作:**
- 对于现有代码库,使用 `/generate rules` 命令
- 在项目根目录创建 `.cursorrules` 文件
- 定义代码风格、架构约束、命名规范
**基础示例:**
```
- 使用Spring Boot 1.5.13 + Spring Cloud Edgware.SR4架构
- 所有微服务遵循com.zhht包结构规范
- Controller必须继承BaseController并包含健康检查
- Feign客户端必须实现fallback降级处理
- 数据库操作统一使用MyBatis,禁用JPA
- Redis缓存键必须在CacheKey常量类中定义
- MQTT连接使用固定ClientId,cleanSession=false
```
**实际案例:`/generate rules` 命令生成的完整项目规则**
通过在项目根目录运行 `/generate rules` 命令,Cursor自动分析了一个微服务停车管理系统并生成了详细的项目规则文档。这个案例展示了如何为复杂的多模块项目建立全面的开发规范。
**生成的规则文档包含:**
- **项目概览**:4个微服务的职责划分和技术栈
- **架构模式**:Spring Cloud服务发现、Feign客户端、断路器等
- **包结构约定**:统一的代码组织规范
- **配置管理**:环境配置和部署规范
- **编码规范**:命名约定、错误处理、缓存模式等
**完整示例文档:** [`cursor_generate_cursor_rules.md`](cursor_generate_cursor_rules.md)
**关键收益:**
1. **自动化分析**:无需手动梳理项目结构
2. **全面覆盖**:涵盖架构、编码、配置、部署各个层面
3. **标准化**:确保团队遵循统一的开发规范
4. **可维护性**:新成员可快速理解项目架构
这个实际案例证明了 `/generate rules` 命令的强大功能,能够为复杂项目快速建立完整的开发指南。
### 2. 精准提示词设计
**公式:** 技术栈 + 行为规范 + 约束条件
**对比:**
-**模糊提示:** "写一个设备管理功能。"
-**精准提示:** "在micro-cloud-adapter服务中用Spring Boot实现MQTT设备管理Controller,继承CheckAliveController模式,实现设备状态监控和命令下发,使用RedisCacheTemplate缓存设备信息,包含Feign客户端调用其他服务,添加完整的异常处理和日志记录。"
**要点:**
- 详细说明技术栈
- 明确行为规范
- 列出约束条件
- 像写技术规格书一样详细
### 3. 文件级迭代:小步快跑
**策略:**
- 单文件生成:每个文件独立生成、测试、审查
- 避免全局失控,逐步集成
- 小而专注的模块化开发
**流程:**
1. 选择单个文件进行生成
2. 立即测试该文件功能
3. 审查代码质量
4. 确认无误后集成到项目
**案例:** 开发停车管理系统时,先独立生成"DeviceCmdController",测试MQTT消息处理通过后再集成到micro-cloud-adapter服务。
### 4. 测试驱动开发(TDD)
**流程:**
1. 人工编写测试用例(如JUnit单元测试)
2. 锁定测试,让Cursor生成代码直至测试通过
3. 若失败,将错误日志提供给AI修正
**优势:**
- 解决AI"逻辑正确但功能错误"的问题
- 确保代码质量和功能正确性
- 提供明确的成功标准
**示例:**
```java
// 先写测试
@Test
public void testMqttMessageHandler() {
// 准备测试数据
String deviceId = "DEVICE_001";
String message = "{\"cmd\":\"heartbeat\",\"data\":{\"status\":\"online\"}}";
// 执行测试
MqttMessageHandler handler = new MqttMessageHandler();
boolean result = handler.handleDeviceMessage(deviceId, message);
// 验证结果
assertTrue(result);
verify(redisCacheTemplate).set(CcaCacheKey.getDeviceStatusKey(deviceId), "online");
}
// 然后让Cursor生成MqttMessageHandler实现代码
```
### 5. 人工审查与反馈
**原则:**
- 始终审查AI的输出
- 手动修正错误代码
- 将修正作为示例反馈给Cursor
**操作:**
- 修复后用 `@fixed` 标记并说明原因
- 训练AI适应你的编码风格
- 建立持续改进的反馈循环
**案例:** AI生成的DeviceCmdController漏了@EnableEurekaClient注册,手动补全后提示:"所有Controller都需要继承CheckAliveController,并添加统一的异常处理@ControllerAdvice"。
### 6. 注意力锚定:精准定位
**命令:**
- `@file` - 限定到特定文件
- `@folder` - 限定到特定文件夹
- `@git` - 对比分支差异
**场景应用:**
- 修复Bug时:`@file:micro-cloud-adapter/src/main/java/com/zhht/adapter/MqttMessageHandler.java` 锁定文件
- 重构时:`@micro-cprs/src/main/java/com/zhht/controller` 限定修改范围
- 版本对比:`@git#px_1.0_20250218` 避免误改
**好处:** 防止AI"走神",避免修改无关代码
### 7. 设计文档管理
**方法:**
-`.cursor/` 目录存放设计文档和检查清单
- 包含架构图、接口文档、开发规范
- 更新代码时同步更新文档
**文档结构:**
```
.cursor/
├── docs/
│ ├── microservices-architecture.md
│ ├── mqtt-integration-guide.md
│ └── deployment-checklist.md
└── rules/
├── microservices-architecture.mdc
└── coding-patterns.mdc
```
**作用:** 确保AI有完整的上下文信息,知道下一步该做什么
### 8. 直接修改代码
**真相:** AI从你的编辑中学习的速度,比听解释快10倍!
**操作:**
- 发现错误直接重写
- 添加注释说明修改原因
- 让AI从你的编辑中学习
**案例:** AI生成的MQTT重连逻辑过于复杂,直接重写并注释:"使用固定ClientId + cleanSession=false,让MQTT协议自动处理重连,无需复杂逻辑"。
### 9. 聊天历史利用
**技巧:**
- 使用 `/history` 调取历史对话
- 迭代和优化旧提示词
- 对高频问题保存为模板
**应用:**
- 复用成功的提示词模式
- 避免重复解释相同问题
- 建立个人提示词库
### 10. 智能模型选择
**推荐:**
- **高精度任务:** 使用Gemini
- **创意性任务:** 使用Claude 3.5
- **通用编程任务:** 使用GPT-4
**任务类型详解:**
**高精度任务** - 需要精确计算、严格逻辑、零容错
- 算法实现和优化
- 数学计算和公式推导
- 性能分析和复杂度计算
- 数据结构设计
- 精确的参数配置
**创意性任务** - 需要创新思维、综合分析、多方案比较
- 系统架构设计和重构
- 复杂问题诊断和解决方案
- 技术选型和方案评估
- 业务逻辑抽象和建模
- 代码审查和优化建议
**通用编程任务** - 标准化、重复性、遵循既定模式
- CRUD操作和API开发
- 常见业务功能实现
- 标准组件和模板代码
- 配置文件和脚本编写
- 日常功能开发
**策略:** 根据任务特点选择最适合的模型,而非一概而论
### 11. 新技术学习
**操作:**
- 粘贴官方文档链接
- 让AI逐行解释错误
- 结合实际项目进行学习
**示例:**
```
@https://spring.io/projects/spring-cloud 请解释Eureka服务发现的原理,
并结合当前项目的@EnableEurekaClient配置,提供完整的服务注册和发现解决方案
```
### 12. 大项目优化
**策略:**
- **过夜索引:** 提前做好全项目索引,提升响应速度
- **上下文裁剪:** 使用 `@micro-cloud-adapter` 限定AI仅关注MQTT适配器模块
- **资源管理:** 避免AI分析target/目录等构建文件浪费资源
**适用场景:**
- 微服务架构重构
- MQTT连接问题排查
- 跨服务Feign调用优化
## 实战技巧总结
### 提示词模板
```
技术栈:[Spring Boot 1.5.13 + Spring Cloud Edgware.SR4 + MyBatis]
任务:[实现MQTT设备管理功能]
约束:[使用RedisCacheTemplate缓存,实现Feign降级,包含完整异常处理]
文件范围:[@micro-cloud-adapter/src/main/java/com/zhht/controller]
测试要求:[包含JUnit单元测试,Mock Redis和MQTT客户端]
```
### 工作流程
1. **准备阶段:** 设定项目规则 + 准备测试用例
2. **生成阶段:** 精准提示 + 文件级迭代
3. **审查阶段:** 人工检查 + 直接修改
4. **优化阶段:** 利用历史 + 模型选择
### 注意事项
- ✅ 始终先写测试,后写实现
- ✅ 保持提示词的具体性和完整性
- ✅ 及时审查和修正AI输出
- ✅ 建立并维护项目规则文档
- ❌ 避免一次性生成大量文件
- ❌ 不要忽略AI输出的审查环节
- ❌ 不要在提示词中含糊其辞
# 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条黄金法则的实际应用价值。
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment