🏗 系统构建
一、分层架构核心(附代码对抗模式)
1. 启动与运行时分离
// ===== 罪案现场 =====
public class OrderService {
private DB db = new MySQL(); // 犯罪证据:构造即绑定
void process() {
db.insert(...); // 墓碑上刻着"此处无法单元测试"
}
}
// ===== 正义实现 =====
// 启动阶段(造车工厂)
public class AppFactory {
public static OrderService createOrderService() {
return new OrderService(new MySQL());
}
}
// 运行时(开车老司机)
OrderService service = AppFactory.createOrderService();
service.process(); // 随时可替换为Mock数据库
2. 依赖注入三流派对比
| 流派 | 示例 | 适用场景 | 坑点 |
|---|---|---|---|
| 构造函数注入 | new Service(db) | 强依赖项 | 参数过多时发臭 |
| Setter注入 | service.setDB(db) | 可选依赖 | 可能遗漏初始化 |
| 框架注入 | @Autowired DB db | 大型应用 | 隐藏了耦合度 |
3. 插件式架构实战(Python版)
# 动态加载支付模块(无需改主系统代码)
class PaymentSystem:
def __init__(self):
self.plugins = {}
def load_plugin(self, name, plugin):
self.plugins[name] = plugin
def pay(self, method, amount):
return self.plugins[method].execute(amount)
# 支付宝插件(独立开发)
class AlipayPlugin:
def execute(self, amount):
return f"支付宝支付{amount}元"
system = PaymentSystem()
system.load_plugin("alipay", AlipayPlugin())
system.pay("alipay", 100) # 输出: 支付宝支付100元
二、扩容设计模式详解
1. 代理模式 vs 门面模式
// 代理模式(控制访问)
class ExpensiveDB {
query() { /* 耗时操作 */ }
}
class DBProxy {
constructor(db) {
this.db = db;
this.cache = new Map();
}
query(sql) {
if (!this.cache.has(sql)) {
this.cache.set(sql, this.db.query(sql));
}
return this.cache.get(sql);
}
}
// 门面模式(简化接口)
class OrderSystemFacade {
constructor(payment, inventory) {
this.payment = payment;
this.inventory = inventory;
}
placeOrder(order) {
this.inventory.check();
return this.payment.charge();
// 隐藏了复杂的调用链
}
}
2. 事件总线的威力
// 解决循环依赖的核武器
class EventBus {
private listeners: Map<string, Function[]> = new Map();
on(event: string, callback: Function) {
if (!this.listeners.has(event)) {
this.listeners.set(event, []);
}
this.listeners.get(event)!.push(callback);
}
emit(event: string, data?: any) {
this.listeners.get(event)?.forEach(cb => cb(data));
}
}
// 模块A(不再直接导入模块B)
const bus = new EventBus();
bus.on('ORDER_CREATED', (order) => {
// 处理订单逻辑
});
三、测试策略矩阵
| 测试类型 | 覆盖目标 | 工具链 | 黄金法则 |
|---|---|---|---|
| 契约测试 | 服务接口 | Pact + Spring Cloud | 验证请求/响应结构 |
| 切片测试 | 组件集成 | @SpringBootTest | Mock外围依赖 |
| 故障注入测试 | 系统容错 | Chaos Monkey | 必须自动化 |
| 压力测试 | 性能瓶颈 | JMeter + Grafana | 关注95分位值 |
四、12-Factor应用 checklist
-
基准代码 ✅ 一个代码库对应多环境部署 ❌ 不同环境用不同分支
-
依赖 ✅ 显式声明所有依赖(requirements.txt/pom.xml) ❌ 假设系统已安装某些包
-
配置 ✅ 环境变量存储敏感信息 ❌ 配置文件提交到Git
-
后端服务 ✅ 把数据库当作附加资源 ❌ 硬编码AWS RDS连接字符串
-
构建发布运行 ✅ 严格分离构建和运行阶段 ❌ 在生产服务器上执行编译