十三、系统构建

52 阅读2分钟

🏗 系统构建

一、分层架构核心(附代码对抗模式)

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验证请求/响应结构
切片测试组件集成@SpringBootTestMock外围依赖
故障注入测试系统容错Chaos Monkey必须自动化
压力测试性能瓶颈JMeter + Grafana关注95分位值

四、12-Factor应用 checklist

  1. 基准代码 ✅ 一个代码库对应多环境部署 ❌ 不同环境用不同分支

  2. 依赖 ✅ 显式声明所有依赖(requirements.txt/pom.xml) ❌ 假设系统已安装某些包

  3. 配置 ✅ 环境变量存储敏感信息 ❌ 配置文件提交到Git

  4. 后端服务 ✅ 把数据库当作附加资源 ❌ 硬编码AWS RDS连接字符串

  5. 构建发布运行 ✅ 严格分离构建和运行阶段 ❌ 在生产服务器上执行编译