新增易方达接口以及添加claude技能

This commit is contained in:
2026-02-26 15:57:50 +08:00
parent c8418c7d4b
commit 167aae2164
21 changed files with 3031 additions and 24 deletions
@@ -0,0 +1,509 @@
# API接口测试指南
接口开发完成后,需要进行系统化测试。本指南提供完整的测试流程和脚本组织方式。
## 测试脚本目录结构
在 `projects/fangjia-script/src/main/groovy/com/fangjia/script/` 下创建专门的测试包:
```
opentest/ # 接口测试脚本专用包
├── [InterfaceName]TestDataExtractor.groovy # 数据提取脚本
├── [InterfaceName]InterfaceTest.groovy # 接口测试脚本
└── data/ # 测试数据目录
├── [interface]_test_data.xlsx # 测试数据(自动生成,单Sheet)
└── [interface]_test_result.xlsx # 测试结果(自动生成,多Sheet)
# - Sheet1: 测试结果(详细数据)
# - Sheet2: 统计数据(汇总信息)
```
**示例**:E基金地址匹配接口测试
```
opentest/
├── EfundTestDataExtractor.groovy
├── EfundInterfaceTest.groovy
└── data/
├── efund_test_data.xlsx # 测试数据
└── efund_test_result.xlsx # 测试结果
├── Sheet1: 测试结果 # 1000行详细数据
└── Sheet2: 统计数据 # 汇总统计信息
```
## 第一步:编写数据提取脚本
**目的**:从生产环境提取真实测试数据
**关键技术**:
### 1. 使用 Mongo3Utils 连接MongoDB(推荐)
```groovy
import com.fangjia.core.Constants
import com.fangjia.core.util.Mongo3Utils
import com.mongodb.client.MongoCollection
import org.bson.Document
// 连接206服务器
MongoCollection<Document> coll = Mongo3Utils.getDbCollection(
Constants.SEAWATER_MONGO_URI, // 已配置好的连接URI
"business", // 数据库
"open_uri_log" // 集合
)
```
### 2. 使用 projection 优化查询
```groovy
// 只查询需要的字段,减少网络传输
Document query = new Document("user_id", "xxx")
.append("request_uri", "/api/xxx")
Document projection = new Document("parameter_map", 1).append("_id", 0)
MongoCursor<Document> cursor = coll.find(query)
.projection(projection) // 只返回 parameter_map
.limit(1000)
.iterator()
```
### 3. 提取测试参数
```groovy
List<List<Object>> excelData = []
excelData << ["序号", "参数1", "参数2", "参数3"] // 表头
int index = 0
while (cursor.hasNext()) {
Document doc = cursor.next()
Document paramMap = doc.get("parameter_map", Document.class)
String param1 = paramMap?.getString("param1") ?: ""
String param2 = paramMap?.getString("param2") ?: ""
excelData << [++index, param1, param2]
}
```
### 4. 保存到Excel
```groovy
import com.fangjia.script.util.ExcelUtils
// 自动确定脚本所在目录
String scriptDir = new File(getClass().protectionDomain.codeSource.location.path).parent
String dataDir = new File(scriptDir, "data").absolutePath
new File(dataDir).mkdirs()
String outputFile = "${dataDir}${File.separator}test_data.xlsx"
ExcelUtils.write(outputFile, excelData, "测试数据")
```
## 第二步:编写接口测试脚本
**目的**:多线程调用接口,记录结果和性能指标
**推荐方法**:使用 `ExcelUtils.multiThreadingModify` 工具类(自动管理线程池和进度监控)
### 方法一:使用 ExcelUtils.multiThreadingModify(推荐)
**优势**:
- ✅ 自动管理线程池(CPU核心数×4)
- ✅ 自动处理线程安全
- ✅ 自动进度监控(每1000条打印进度和百分比)
- ✅ 代码简洁,专注业务逻辑
- ✅ 超长等待时间(30天),适合大批量测试
**完整示例**:
```groovy
import com.fangjia.core.util.HttpRequest
import com.fangjia.script.util.ExcelUtils
import net.sf.json.JSONObject
// 1. 准备测试数据和结果Excel
String scriptDir = new File(getClass().protectionDomain.codeSource.location.path).parent
String dataDir = new File(scriptDir, "data").absolutePath
String inputFile = "${dataDir}${File.separator}test_data.xlsx"
String outputFile = "${dataDir}${File.separator}test_result.xlsx"
// 2. 读取所有数据(包括表头)
List<List<Object>> allData = ExcelUtils.read(inputFile, 0, 0)
// 3. 修改表头,添加结果列
allData[0] = ["序号", "参数1", "参数2", "返回字段1", "返回字段2",
"返回字段3", "耗时(ms)", "异常信息"]
// 4. 为每行数据添加空的结果列
for (int i = 1; i < allData.size(); i++) {
List row = allData[i]
(3..7).each { row << "" } // 添加5个结果列
}
// 5. 写入初始结果文件
ExcelUtils.write(outputFile, allData, "测试结果")
// 6. 使用 multiThreadingModify 多线程调用接口
ExcelUtils.multiThreadingModify(outputFile, { List row ->
HttpRequest request = new HttpRequest()
long startTime = System.currentTimeMillis()
try {
// 提取参数(row[0]=序号, row[1]=参数1, row[2]=参数2)
String param1 = row[1]?.toString() ?: ""
String param2 = row[2]?.toString() ?: ""
// 调用接口
Map<String, String> params = ["param1": param1, "param2": param2]
String response = request.get("http://localhost:9180/api/xxx", params, "UTF-8")
long duration = System.currentTimeMillis() - startTime
// 解析响应
JSONObject json = JSONObject.fromObject(response)
Integer code = json.optInt("code")
JSONObject result = json.optJSONObject("result")
if (code == 200 && result != null) {
// 成功:填充结果列(直接修改row,工具类自动处理线程安全)
row[3] = result.optString("field1", "")
row[4] = result.optString("field2", "")
row[5] = result.optString("field3", "")
row[6] = duration
row[7] = "" // 无异常
} else {
// 失败:记录错误信息
row[6] = duration
row[7] = "接口返回错误(code=${code}): ${json.optString('msg', '')}"
}
} catch (Exception e) {
// 异常:记录异常信息
long duration = System.currentTimeMillis() - startTime
row[6] = duration
row[7] = "异常: ${e.class.simpleName} - ${e.message}"
}
}, 0, "测试结果")
// 7. 读取结果并统计
List<List<Object>> finalData = ExcelUtils.read(outputFile, 0, 0)
int totalCount = finalData.size() - 1
int successCount = 0
int failCount = 0
long totalTime = 0
// 耗时分布统计
Map<String, Integer> timeDist = [
"<100ms": 0,
"100-200ms": 0,
"200-500ms": 0,
"500-1000ms": 0,
">1000ms": 0
]
for (int i = 1; i < finalData.size(); i++) {
List row = finalData[i]
String errorMsg = row[7]?.toString() ?: ""
if (errorMsg == "") {
successCount++
// 统计耗时
if (row[6] instanceof Number) {
int duration = ((Number)row[6]).intValue()
totalTime += duration
if (duration < 100) timeDist["<100ms"]++
else if (duration < 200) timeDist["100-200ms"]++
else if (duration < 500) timeDist["200-500ms"]++
else if (duration < 1000) timeDist["500-1000ms"]++
else timeDist[">1000ms"]++
}
} else {
failCount++
}
}
// 8. 保存统计数据到新Sheet
List<List<Object>> statsData = []
statsData << ["统计项", "数值"]
statsData << ["测试时间", new Date().format("yyyy-MM-dd HH:mm:ss")]
statsData << ["", ""]
statsData << ["总测试数", totalCount]
statsData << ["成功数", successCount]
statsData << ["失败数", failCount]
statsData << ["成功率", totalCount > 0 ? String.format('%.2f%%', successCount * 100.0 / totalCount) : '0.00%']
if (successCount > 0) {
int avgTime = (totalTime / successCount).intValue()
statsData << ["", ""]
statsData << ["平均耗时(ms)", avgTime]
// 耗时分布
statsData << ["", ""]
statsData << ["耗时分布", "数量"]
timeDist.each { range, count ->
statsData << [range, count]
}
}
// 添加统计Sheet
ExcelUtils.write(outputFile, statsData, "统计数据")
// 9. 控制台输出统计结果
println "\n========== 测试完成 =========="
println "总测试数:${totalCount}"
println "成功数:${successCount}"
println "失败数:${failCount}"
println "成功率:${totalCount > 0 ? String.format('%.2f%%', successCount * 100.0 / totalCount) : '0.00%'}"
if (successCount > 0) {
int avgTime = (totalTime / successCount).intValue()
println "平均耗时:${avgTime} ms"
println "\n耗时分布:"
timeDist.each { range, count ->
if (count > 0) {
println " ${range}: ${count} 条"
}
}
}
println "\n结果文件:${outputFile}"
println " - Sheet1: 测试结果(详细数据)"
println " - Sheet2: 统计数据(汇总信息)"
```
### 方法二:手动管理线程池(适合需要自定义控制的场景)
<details>
<summary>点击展开手动管理线程池的示例代码</summary>
```groovy
import java.util.concurrent.*
import java.util.concurrent.atomic.AtomicInteger
import com.fangjia.core.util.HttpRequest
import net.sf.json.JSONObject
// 1. 读取测试数据
List<List<Object>> testData = ExcelUtils.read(inputFile, 0, 1) // 跳过表头
// 2. 准备结果数据
List<List<Object>> resultData = []
resultData << ["序号", "参数1", "参数2", "返回字段1", "返回字段2", "耗时(ms)", "异常信息"]
testData.each { row ->
List newRow = [row[0], row[1], row[2]]
(3..6).each { newRow << "" }
resultData << newRow
}
// 3. 配置线程池
int nThread = Runtime.getRuntime().availableProcessors() * 4
ExecutorService executorService = Executors.newFixedThreadPool(nThread)
AtomicInteger counter = new AtomicInteger(0)
AtomicInteger successCounter = new AtomicInteger(0)
// 4. 提交任务
testData.eachWithIndex { List testRow, int i ->
final int rowIndex = i + 1
executorService.submit({
HttpRequest request = new HttpRequest()
long startTime = System.currentTimeMillis()
try {
String param1 = testRow[1]?.toString() ?: ""
String response = request.get("http://localhost:9180/api/xxx",
["param1": param1], "UTF-8")
long duration = System.currentTimeMillis() - startTime
JSONObject json = JSONObject.fromObject(response)
JSONObject result = json.optJSONObject("result")
synchronized(resultData) {
if (json.optInt("code") == 200 && result != null) {
resultData[rowIndex][3] = result.optString("field1", "")
resultData[rowIndex][4] = result.optString("field2", "")
resultData[rowIndex][5] = duration
successCounter.incrementAndGet()
} else {
resultData[rowIndex][5] = duration
resultData[rowIndex][6] = "错误: ${json.optString('msg')}"
}
}
} catch (Exception e) {
synchronized(resultData) {
resultData[rowIndex][6] = "异常: ${e.message}"
}
}
if (counter.incrementAndGet() % 100 == 0) {
println "进度: ${counter.get()}/${testData.size()}"
}
} as Runnable)
}
// 5. 等待完成并保存结果
executorService.shutdown()
executorService.awaitTermination(30, TimeUnit.MINUTES)
ExcelUtils.write(outputFile, resultData, "测试结果")
```
</details>
## 第三步:运行测试流程
### 1. 构建项目
```bash
cd deliverables/script
mvn clean package -Dmaven.test.skip=true
```
### 2. 提取测试数据
```bash
groovy -cp "target/classes;target/classes/lib/*" \
projects/fangjia-script/src/main/groovy/com/fangjia/script/opentest/XXXTestDataExtractor.groovy
```
### 3. 启动fangjia-open服务
```bash
cd deliverables/fangjiaopen
mvn tomcat7:run
```
### 4. 运行接口测试
```bash
groovy -cp "target/classes;target/classes/lib/*" \
projects/fangjia-script/src/main/groovy/com/fangjia/script/opentest/XXXInterfaceTest.groovy
```
## Excel结果文件结构
### 测试数据Excel(单Sheet)
| 列 | 字段 | 说明 |
|----|------|------|
| A | 序号 | 1-N |
| B | 参数1 | 接口输入参数 |
| C | 参数2 | 接口输入参数 |
| ... | ... | 更多参数 |
### 测试结果Excel(多Sheet)
#### 📄 Sheet1: 测试结果(详细数据)
| 列 | 字段 | 说明 |
|----|------|------|
| A | 序号 | 同测试数据 |
| B | 参数1 | 同测试数据 |
| C | 参数2 | 同测试数据 |
| D | 返回字段1 | 接口返回结果 |
| E | 返回字段2 | 接口返回结果 |
| ... | ... | 更多返回字段 |
| N | 耗时(ms) | 接口调用耗时 |
| N+1 | 异常信息 | 错误时记录 |
#### 📊 Sheet2: 统计数据(汇总信息)
| 列 | 字段 | 说明 |
|----|------|------|
| A | 统计项 | 统计项名称 |
| B | 数值 | 统计值 |
统计内容包括:
- 测试时间(测试执行的时间戳)
- 总测试数、成功数、失败数、成功率
- 平均耗时(仅统计成功的请求)
- 耗时分布(<100ms、100-200ms、200-500ms、500-1000ms、>1000ms)
示例:
```
| 统计项 | 数值 |
|----------------|----------------------|
| 测试时间 | 2026-02-26 14:30:15 |
| | |
| 总测试数 | 1000 |
| 成功数 | 980 |
| 失败数 | 20 |
| 成功率 | 98.00% |
| | |
| 平均耗时(ms) | 245 |
| | |
| 耗时分布 | 数量 |
| <100ms | 120 |
| 100-200ms | 350 |
| 200-500ms | 480 |
| 500-1000ms | 30 |
| >1000ms | 0 |
```
## 测试脚本最佳实践
### ✅ 推荐做法
1. **MongoDB查询优化**
- 使用 `Mongo3Utils` 而非旧版 `MongoUtils`
- 使用 `projection` 只查询需要的字段
- 使用 `Constants` 中的预定义URI
2. **路径处理**
- 使用相对路径而非硬编码
- 脚本自动识别所在目录:`new File(getClass().protectionDomain.codeSource.location.path).parent`
3. **多线程测试(强烈推荐)**
- **优先使用** `ExcelUtils.multiThreadingModify` 工具方法
- 自动管理线程池(CPU核心数×4)
- 自动处理线程安全(无需手动 synchronized)
- 自动进度监控(每1000条打印进度和百分比)
- 代码简洁,专注业务逻辑
4. **进度监控**
- 使用工具类自动监控(推荐)
- 或手动实现:每100条打印进度,包含时间戳
5. **异常处理**
- 捕获所有异常
- 记录到Excel而非终止程序
- 异常信息包含类型和消息
6. **统计数据保存**
- 使用 `ExcelUtils.write(outputFile, statsData, "统计数据")` 创建统计Sheet
- 统计内容包括:测试时间、成功率、平均耗时、耗时分布
- 方便后续分析和生成测试报告
### ❌ 避免做法
1. ❌ 硬编码文件路径(如 `D:\test\data.xlsx`)
2. ❌ 查询所有字段而不使用 projection
3. ❌ 使用旧版 MongoDB API(`DBObject`、`BasicDBObject`)
4. ❌ 单线程测试大量数据
5. ❌ 异常时终止整个测试
6. ❌ 手动管理线程池(除非有特殊需求,否则用工具类)
7. ❌ 忘记处理线程安全问题(使用工具类可避免)
## 测试完成后的分析
测试完成后,Excel文件包含两个Sheet,便于多维度分析:
### 📊 使用统计数据Sheet快速分析
1. **成功率分析**:查看成功率是否 >95%
- 低于95%需要排查失败原因
- 在"测试结果"Sheet中过滤"异常信息"列查看失败详情
2. **性能分析**:查看平均耗时和耗时分布
- 平均耗时应 <500ms(根据业务要求调整)
- 耗时分布帮助识别性能瓶颈
- 如果 >1000ms 的数量较多,需优化接口性能
3. **异常分析**:在"测试结果"Sheet中
- 使用Excel筛选功能查看所有失败记录
- 统计异常类型(如超时、参数错误、业务异常等)
- 针对高频异常进行优化
4. **数据质量分析**:在"测试结果"Sheet中
- 检查返回字段的完整性(是否有大量空值)
- 检查价格、匹配级别等核心字段的填充率
- 对比不同匹配级别的数据分布
### 💡 建议
- 将统计数据Sheet制作成Excel图表(饼图、柱状图)便于可视化分析
- 保存多次测试结果,对比性能变化趋势
- 将测试报告作为接口验收的依据
@@ -0,0 +1,201 @@
# OpenAPI 接口开发代码模板
## Controller 模板
```java
package com.fangjia.open.controllers;
import com.fangjia.open.model.*;
import com.fangjia.service.{业务模块}.{Service名称};
import com.fangjia.open.interceptors.Authority;
import com.fangjia.open.interceptors.Role;
import org.apache.commons.lang.StringUtils;
@Authority(role = Role.USER)
public class {Controller名称}Controller {
private {Service名称} {service实例名};
// Spring依赖注入(约定大于配置)
public void set{Service名称}({Service名称} {service实例名}) {
this.{service实例名} = {service实例名};
}
/**
* {接口功能描述}
* URL: /{controller路径}/{方法名}
*/
@Authority(role = Role.USER)
public Object {方法名}Action({Model名称} model) {
RestfulModelAndView mav = new RestfulModelAndView();
// 参数校验
if (StringUtils.isBlank(model.get{必填字段}())) {
mav.setModel(BasicModel.buildBadRequestModel("{字段}不能为空"));
return mav;
}
// 调用Service
{Result类型} result = {service实例名}.{service方法}(model);
// 封装返回结果
if (result != null) {
// 情况1: 有专用DTO类
mav.setModel(BasicModel.buildOKModel().setResult(result));
// 情况2: 使用UniversalDto
// UniversalDto dto = UniversalDto.newDto();
// dto.append("fieldName1", result.getValue1());
// dto.append("fieldName2", result.getValue2());
// mav.setModel(BasicModel.buildOKModel().setResult(dto));
} else {
mav.setModel(BasicModel.buildBadRequestModel("未找到数据"));
}
return mav;
}
}
```
## Service 接口模板
```java
package com.fangjia.service.{业务模块};
import com.fangjia.open.model.{Model名称};
import {Result类的包路径}.{Result类名};
/**
* {Service功能描述}
*/
public interface {Service名称} {
/**
* {方法功能描述}
* @param model 输入参数
* @return {返回值描述}
*/
{Result类型} {方法名}({Model名称} model);
}
```
## Service 实现类模板
```java
package com.fangjia.service.{业务模块};
import com.fangjia.dal.{DAO包路径}.{DAO名称};
import com.fangjia.open.model.{Model名称};
import {Result类的包路径}.{Result类名};
/**
* {Service功能描述}实现类
*/
public class {Service名称}Impl implements {Service名称} {
private {DAO名称} {dao实例名};
// Spring依赖注入
public void set{DAO名称}({DAO名称} {dao实例名}) {
this.{dao实例名} = {dao实例名};
}
@Override
public {Result类型} {方法名}({Model名称} model) {
// 业务逻辑实现
// 示例:从DAO查询数据
{Result类型} result = {dao实例名}.findBy{查询条件}(
model.get{字段1}(),
model.get{字段2}()
);
// 数据处理
if (result != null) {
// 可以进行额外的业务处理
// result.setXxx(...);
}
return result;
}
}
```
## Model 类模板
```java
package com.fangjia.open.model;
/**
* {接口名称}输入参数Model
*/
public class {Model名称} {
private String {字段1};
private String {字段2};
private Integer {字段3};
// ... 其他字段
// Getter和Setter方法
public String get{字段1}() {
return {字段1};
}
public void set{字段1}(String {字段1}) {
this.{字段1} = {字段1};
}
public String get{字段2}() {
return {字段2};
}
public void set{字段2}(String {字段2}) {
this.{字段2} = {字段2};
}
public Integer get{字段3}() {
return {字段3};
}
public void set{字段3}(Integer {字段3}) {
this.{字段3} = {字段3};
}
// ... 其他getter/setter
}
```
## 使用 UniversalDto 封装示例
```java
// 当没有专用的Result DTO类时,使用UniversalDto
UniversalDto dto = UniversalDto.newDto();
dto.append("communityName", "陆家嘴花园");
dto.append("city", "上海市");
dto.append("district", "浦东新区");
dto.append("referencePrice", 126000);
dto.append("updateTime", "2026-01-31");
mav.setModel(BasicModel.buildOKModel().setResult(dto));
```
## 常见返回格式
```java
// 成功返回(有数据)
mav.setModel(BasicModel.buildOKModel().setResult(result));
// 成功返回(无数据)
mav.setModel(BasicModel.buildOKModel());
// 参数错误
mav.setModel(BasicModel.buildBadRequestModel("参数错误信息"));
// 未授权
mav.setModel(BasicModel.buildUnAuthorizedModel());
// 服务器错误
mav.setModel(BasicModel.buildServerErrorModel());
// 自定义错误码
mav.setModel(BasicModel.buildModel(错误码, "错误信息"));
```
@@ -0,0 +1,304 @@
# 常用数据表参考
本文档记录开发OpenAPI接口时常用的数据表结构和用途,便于快速查询和复用。
## 数据库命名规范
### @Table 注解格式
在 `fangjia-dal` 的实体类中,MongoDB 集合通过 JPA 的 `@Table` 注解来指定:
```java
@Entity
@Table(name = "database.collection")
public class YourEntity implements MongoEntity {
// ...
}
```
**重要规则**:
- **点之前**(`.`前):**数据库名**(database)
- **点之后**(`.`后):**集合名**(collection)
- 不同的数据库对应不同的 MongoDB URI 常量
### 数据库与 URI 常量的对应关系
| 数据库名 | MongoDB URI 常量 | 服务器地址 | 用途 |
|---------|-----------------|-----------|------|
| `business` | `Constants.SEAWATER_MONGO_URI` | 192.168.0.206:27020 | 业务日志、开放平台相关 |
| `fangjia` | `Constants.FANGJIA_MONGO_URI` | mongo.db.fangjia.com:28017 | 核心业务数据 |
| `fangjia_stat` | `Constants.FANGJIA_MONGO_URI` | mongo.db.fangjia.com:28017 | 统计数据 |
| `address_analytics` | `Constants.FANGJIA_MONGO_URI` | mongo.db.fangjia.com:28017 | 地址分析数据 |
**示例**:
```java
// business.open_uri_log → business 数据库 → 使用 SEAWATER_MONGO_URI
@Table(name = "business.open_uri_log")
// fangjia_stat.district_stat → fangjia_stat 数据库 → 使用 FANGJIA_MONGO_URI
@Table(name = "fangjia_stat.district_stat")
// fangjia.seaweed → fangjia 数据库,seaweed 集合 → 使用 FANGJIA_MONGO_URI
@Table(name = "fangjia.seaweed")
```
---
## MongoDB数据表
### 1. business.open_uri_log
**服务器**:192.168.0.206 (通过 `Constants.SEAWATER_MONGO_URI` 连接)
**作用**:记录所有开放平台API的调用日志,包含请求参数、返回结果等
**常用字段**:
| 字段名 | 类型 | 说明 |
|-------|------|------|
| `user_id` | String | 调用用户ID |
| `request_uri` | String | 请求的API路径(如 `/address/risk`) |
| `parameter_map` | Document | 请求参数(嵌套文档) |
| `res_map` | Document | 返回结果(嵌套文档) |
| `c_date` | Date | 创建时间 |
**连接方式**:
```groovy
import com.fangjia.core.Constants
import com.fangjia.core.util.Mongo3Utils
MongoCollection<Document> coll = Mongo3Utils.getDbCollection(
Constants.SEAWATER_MONGO_URI,
"business",
"open_uri_log"
)
```
**典型查询**:
```groovy
// 查询特定用户的API调用记录
Document query = new Document("user_id", "1007569")
.append("request_uri", "/address/risk")
// 使用projection优化查询
Document projection = new Document("parameter_map", 1).append("_id", 0)
MongoCursor<Document> cursor = coll.find(query)
.projection(projection)
.limit(1000)
.iterator()
```
**使用场景**:
- 提取历史调用数据用于接口测试
- 分析API调用量和参数分布
- 排查接口调用问题
---
### 2. fangjia_stat.district_stat
**数据库**:fangjia_stat (通过 `Constants.FANGJIA_MONGO_URI` 连接)
**集合名**:district_stat
**作用**:存储小区级别的价格统计数据
**常用字段**:
| 字段名 | 类型 | 说明 |
|-------|------|------|
| `city` | String | 城市 |
| `region` | String | 区域 |
| `name` | String | 小区名称 |
| `avg_price_2b` | Integer | 均价(优先使用,元/平米) |
| `avgPrice` | Integer | 均价(备选,元/平米) |
| `weekend` | Date | 数据更新时间 |
**典型查询**:
```groovy
// 通过DistrictStatService查询
DistrictStat latestStat = districtStatService.findOneDistrictStatsSort(
city, region, name, null
)
// 优先使用avg_price_2b
Integer avgPrice = null
if (latestStat.getAvg_price_2b() != null && latestStat.getAvg_price_2b() > 0) {
avgPrice = latestStat.getAvg_price_2b()
} else if (latestStat.getAvgPrice() > 0) {
avgPrice = latestStat.getAvgPrice()
}
```
**使用场景**:
- 查询小区参考均价
- E基金地址匹配接口返回参考价格
- 房价评估相关接口
---
### 3. fangjia.deal_price
**数据库**:fangjia (通过 `Constants.FANGJIA_MONGO_URI` 连接)
**集合名**:deal_price
**作用**:存储房产成交记录
**常用字段**:
| 字段名 | 类型 | 说明 |
|-------|------|------|
| `city` | String | 城市 |
| `region` | String | 区域 |
| `name` | String | 小区名称 |
| `avgPrice` | Integer | 成交单价(元/平米) |
| `totalPrice` | Integer | 成交总价(万元) |
| 成交时间 | Date | 成交日期 |
**典型查询**:
```groovy
// 通过DealPriceService查询近半年成交记录
Date halfYearAgo = new Date(System.currentTimeMillis() - 180L * 24 * 60 * 60 * 1000)
Date now = new Date()
List<DealPrice> dealPrices = dealPriceService.findDealPriceList(
city, region, name, halfYearAgo, now
)
// 找到单价最接近参考均价的成交记录
DealPrice closestDeal = null
int minDiff = Integer.MAX_VALUE
for (DealPrice deal : dealPrices) {
if (deal.getAvgPrice() != null && deal.getTotalPrice() != null) {
int diff = Math.abs(deal.getAvgPrice() - referencePrice)
if (diff < minDiff) {
minDiff = diff
closestDeal = deal
}
}
}
```
**使用场景**:
- 查询成交记录
- 计算典型总价(最接近参考均价的成交总价)
- 成交数据分析
---
### 4. fangjia_stat.region_sell_stat
**数据库**:fangjia_stat (通过 `Constants.FANGJIA_MONGO_URI` 连接)
**集合名**:region_sell_stat
**作用**:存储区域级别的销售价格统计
**常用字段**:
| 字段名 | 类型 | 说明 |
|-------|------|------|
| `city` | String | 城市(简称格式) |
| `region` | String | 区域(简称格式) |
| `avgPrice` | Integer | 区域均价(元/平米) |
| `date` | Integer | 数据日期(yyyyMM格式) |
| `updateDate` | Date | 更新时间 |
**典型查询**:
```groovy
// 需要先格式化城市和区域为简称
String formattedCity = RegionData.formatCity(city)
String formattedRegion = RegionData.formatRegion(formattedCity, district)
// 通过RegionSellStatService查询最新区域价格
RegionSellStat regionSellStat = regionSellStatService.findNewestRegionPrice(
formattedCity, formattedRegion
)
if (regionSellStat != null && regionSellStat.getAvgPrice() != null) {
Integer avgPrice = regionSellStat.getAvgPrice()
// 格式化日期
String updateTime = DateUtil.formatByPattern(
DateUtil.parseDate(regionSellStat.getDate().toString(), "yyyyMM"),
"yyyy-MM-dd"
)
}
```
**使用场景**:
- 查询区域级别参考价格
- 地址匹配失败时返回区域价格
- 区域价格趋势分析
---
### 5. fangjia.seaweed
**数据库**:fangjia (通过 `Constants.FANGJIA_MONGO_URI` 连接)
**集合名**:seaweed (实体类为 District,通过 @DatastoreCategory("district") 标识)
**作用**:存储小区、写字楼等建筑的基础信息(权威数据源)
**常用字段**:
| 字段名 | 类型 | 说明 |
|-------|------|------|
| `_id` | ObjectId | 小区唯一标识 |
| `city` | String | 城市 |
| `region` | String | 区域 |
| `name` | String | 小区/建筑名称 |
| `cat` | String | 分类(district=小区, office=写字楼) |
| `estate_type2` | String | 物业类型 |
**典型查询**:
```groovy
// 通过DistrictService根据ID查询
District district = districtService.findById(id)
if (district != null) {
String city = district.getCity()
String region = district.getRegion()
String name = district.getName()
}
```
**使用场景**:
- 根据ID查询小区权威信息
- 获取小区的城市、区域、名称用于后续查询
- 验证POI信息的准确性
---
## 如何记录新数据表
**遇到新数据表时,请主动询问用户是否需要记录,格式如下:**
> 我在开发过程中用到了数据表 `XXX.YYY`,是否需要记录到技能文档中供以后复用?
>
> 如果需要,请告诉我:
> 1. 这个表的主要作用
> 2. 常用的查询场景
> 3. 是否有特殊的查询方式或注意事项
**记录模板**:
```markdown
### N. database.table_name
**服务器/数据库**:服务器地址或数据库类型
**作用**:简要说明表的用途
**常用字段**:
| 字段名 | 类型 | 说明 |
|-------|------|------|
| `field1` | Type | 说明 |
| `field2` | Type | 说明 |
**连接方式**:(如果有特殊连接方式)
```groovy
// 代码示例
```
**典型查询**:
```groovy
// 常用查询示例
```
**使用场景**:
- 场景1
- 场景2
```
@@ -0,0 +1,190 @@
# OpenAPI 开发规范
## 项目结构
### Controller层
- **位置**: `projects/fangjia-open/src/main/java/com/fangjia/open/controllers/`
- **命名**: `{业务名}Controller.java`
- **方法命名**: `{方法名}Action`
- **URL映射**: `/{controller路径}/{方法名}`
- 示例: `PropertyController.priceQueryAction` → `/property/priceQuery`
### Service层
- **位置**: `projects/fangjia-service/src/main/java/com/fangjia/service/{业务模块}/`
- **命名**:
- 接口: `{Service名}.java`
- 实现: `{Service名}Impl.java`
- **结构**: 必须有接口 + 实现类
### Model层
- **位置**: `projects/fangjia-open/src/main/java/com/fangjia/open/model/`
- **命名**: `{功能名}Model.java`
- **内容**: 输入参数的POJO类,包含getter/setter方法
### DAO层
- **位置**: `projects/fangjia-dal/src/main/java/com/fangjia/dal/`
- **原则**: 优先使用已有DAO,需要时再新建
- **基类**:
- MongoDB: `AbstractMongoDao`
- MySQL: `AbstractSqlDao`
- JPA: `AbstractJpaCompatibleDao`
## 依赖注入规范
### 约定大于配置
- **不需要**使用注解(@Service, @Autowired等)
- **不需要**手动配置Spring Bean XML
- **只需要**提供setter方法,Spring会自动注入
### 示例
```java
public class PropertyController {
private PropertyService propertyService;
// 提供setter方法即可,无需注解
public void setPropertyService(PropertyService propertyService) {
this.propertyService = propertyService;
}
}
```
## 参数校验
### 手动代码校验
- 使用 `StringUtils.isBlank()` 检查字符串
- 使用 `if` 语句进行逻辑判断
- **不使用** `@Valid` 注解或 JSR303 校验
### 示例
```java
// 必填参数校验
if (StringUtils.isBlank(model.getCity())) {
mav.setModel(BasicModel.buildBadRequestModel("城市不能为空"));
return mav;
}
// 数值范围校验
if (model.getSize() != null && model.getSize() <= 0) {
mav.setModel(BasicModel.buildBadRequestModel("面积必须大于0"));
return mav;
}
```
## 异常处理
### 统一异常处理
- **不需要**手动 try-catch
- 框架已有统一异常处理机制
- 直接调用Service方法即可
```java
// 正确 - 不需要try-catch
PropertyResult result = propertyService.queryPrice(model);
// 错误 - 不要这样写
// try {
// PropertyResult result = propertyService.queryPrice(model);
// } catch (Exception e) {
// ...
// }
```
## 返回值规范
### 统一返回格式
所有接口返回 `RestfulModelAndView` 对象:
```java
RestfulModelAndView mav = new RestfulModelAndView();
```
### 设置返回内容
使用 `BasicModel` 构建返回对象:
```java
// 成功 - 返回数据
mav.setModel(BasicModel.buildOKModel().setResult(data));
// 成功 - 无数据
mav.setModel(BasicModel.buildOKModel());
// 失败 - 参数错误
mav.setModel(BasicModel.buildBadRequestModel("错误描述"));
```
### JSON格式
返回的JSON格式:
```json
{
"code": 200,
"msg": "ok",
"result": {
// 实际数据
}
}
```
## 编码规范
| 项目 | 规范 |
|-----|------|
| **字符编码** | UTF-8 |
| **命名风格** | 驼峰命名法(camelCase) |
| **参数大小写** | 大小写敏感 |
| **URL大小写** | 大小写敏感 |
## 认证授权
### Token认证
- 所有接口方法需要添加 `@Authority(role = Role.USER)`
- 调用时必须传递 `token` 参数
- Token有效期:2小时
```java
@Authority(role = Role.USER)
public class PropertyController {
@Authority(role = Role.USER)
public Object priceQueryAction(PropertyQueryModel model) {
// ...
}
}
```
## 本地测试(可选)
```bash
cd deliverables/fangjiaopen
mvn tomcat7:run
```
访问地址:`http://localhost:8032/{controller}/{action}?param1=value1&token=xxx`
## 构建打包
```bash
cd deliverables/fangjiaopen
mvn clean package -Dmaven.test.skip=true
```
产物位置:`deliverables/fangjiaopen/target/fangjia-open.war`
## 部署流程
1. **构建**: Maven打包生成WAR文件
2. **Docker**: Jenkins Pipeline构建Docker镜像
3. **推送**: 推送到镜像仓库 `192.168.0.19:9011`
4. **部署**: K8S自动部署
## 不需要的功能
- ❌ 不需要限流
- ❌ 不需要缓存配置(除非特殊说明)
- ❌ 不需要写日志(有统一日志处理)
- ❌ 不需要手动try-catch
- ❌ 不需要配置Spring Bean XML