后端系统架构设计:从单体到微服务的演进之路

引言 随着业务规模的不断扩大,后端系统架构需要不断演进以应对日益增长的挑战。从单体应用到微服务架构,从单机部署到分布式集群,每一次架构演进都是为了解决特定的痛点。本文将深入探讨后端系统架构设计的核心原则、模式与实践。 一、架构演进历程 1.1 架构演进路径 单体应用 → 分层架构 → SOA → 微服务 → Serverless 演进阶段对比 架构类型 特点 优势 挑战 适用场景 单体应用 单一代码库、单一部署 开发简单、部署容易 扩展性差、技术栈固定 小型项目、初创期 分层架构 MVC/MVP分层 职责清晰、易于维护 层间耦合强 中小型项目 SOA 服务化、ESB总线 服务复用、松耦合 ESB单点、复杂度高 企业级应用 微服务 独立服务、自治部署 独立扩展、技术自由 运维复杂、分布式事务 大型复杂系统 Serverless 函数级、按需付费 极致弹性、成本优化 厂商锁定、冷启动 事件驱动、波峰明显 1.2 单体架构的局限性 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 # 单体应用的典型问题 # 问题1: 代码耦合严重 # 一个请求的处理流程涉及多个模块 class OrderService: def create_order(self, user_id, items): # 直接依赖多个模块 user = UserService().get_user(user_id) inventory = InventoryService().check_stock(items) payment = PaymentService().process_payment(items) shipping = ShippingService().calculate_shipping(user.address) notification = NotificationService().send_confirmation(user.email) # 如果任何一个模块出错,整个订单创建失败 return Order(user=user, items=items, payment=payment) # 问题2: 难以独立扩展 # 当订单服务压力大时,必须整体扩展 # 无法针对特定瓶颈服务单独扩容 # 问题3: 技术栈锁定 # 整个应用必须使用相同的语言和框架 # 无法为新服务选择更适合的技术 # 问题4: 部署风险高 # 任何小的修改都需要重新部署整个应用 # 一处bug可能影响整个系统 二、微服务架构设计 2.1 核心设计原则 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 # ========== 服务拆分原则 ========== # 1. 单一职责原则 # 每个服务专注于一个业务领域 class UserService: """用户服务 - 只负责用户相关的业务""" def create_user(self, data): pass def get_user(self, user_id): pass def update_user(self, user_id, data): pass class OrderService: """订单服务 - 只负责订单相关的业务""" def create_order(self, data): pass def get_order(self, order_id): pass def cancel_order(self, order_id): pass # 2. 限界上下文原则 # 按照业务领域边界拆分服务 # DDD (Domain-Driven Design) 战术模式 # 3. 数据独立性原则 # 每个服务拥有独立的数据库 class UserDatabase: """用户服务的数据库""" def __init__(self): self.db = PostgreSQL('users_db') class OrderDatabase: """订单服务的数据库""" def __init__(self): self.db = MongoDB('orders_db') # 4. API网关原则 # 统一入口,路由转发 class APIGateway: """API网关 - 服务统一入口""" def __init__(self): self.routes = { '/api/users/*': UserService(), '/api/orders/*': OrderService(), '/api/products/*': ProductService(), '/api/payments/*': PaymentService() } def route(self, request): # 路由匹配 for pattern, service in self.routes.items(): if request.path.match(pattern): return service.handle(request) # 聚合多个服务的响应 if request.path == '/api/dashboard': return self.aggregate_dashboard(request) def aggregate_dashboard(self, request): """聚合多个服务的数据""" user_data = self.call_service('/api/users/me', request) order_data = self.call_service('/api/orders/recent', request) notification_data = self.call_service('/api/notifications', request) return { 'user': user_data, 'orders': order_data, 'notifications': notification_data } 2.2 服务通信模式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 # ========== 同步通信: REST/gRPC ========== import requests from typing import Protocol # REST API调用 class OrderClient: """订单服务客户端""" BASE_URL = "http://order-service:8080" def create_order(self, order_data: dict) -> dict: response = requests.post( f"{self.BASE_URL}/api/orders", json=order_data, timeout=5 # 超时控制 ) response.raise_for_status() return response.json() def get_order(self, order_id: str) -> dict: response = requests.get( f"{self.BASE_URL}/api/orders/{order_id}", timeout=3 ) response.raise_for_status() return response.json() # gRPC调用 (性能更高) import grpc from generated import order_pb2, order_pb2_grpc class OrderGRPCClient: """订单服务gRPC客户端""" def __init__(self): self.channel = grpc.insecure_channel('order-service:9090') self.stub = order_pb2_grpc.OrderServiceStub(self.channel) def create_order(self, order_data: dict) -> order_pb2.OrderResponse: request = order_pb2.CreateOrderRequest( user_id=order_data['user_id'], items=[ order_pb2.OrderItem( product_id=item['product_id'], quantity=item['quantity'] ) for item in order_data['items'] ] ) return self.stub.CreateOrder(request, timeout=5) # ========== 异步通信: 消息队列 ========== import asyncio from aio_pika import connect, Message class EventBus: """事件总线 - 异步消息传递""" def __init__(self, amqp_url: str): self.connection = None self.channel = None self.amqp_url = amqp_url async def connect(self): """建立连接""" self.connection = await connect(self.amqp_url) self.channel = await self.connection.channel() # 声明交换机 await self.channel.declare_exchange( 'domain-events', 'topic', durable=True ) async def publish(self, event_type: str, event_data: dict): """发布事件""" exchange = await self.get_exchange() message = Message( json.dumps(event_data).encode(), content_type='application/json', delivery_mode=2 # 持久化 ) await exchange.publish( message, routing_key=event_type ) async def subscribe(self, event_pattern: str, handler): """订阅事件""" exchange = await self.get_exchange() # 声明队列 queue = await self.channel.declare_queue( f'{event_pattern}-queue', durable=True ) # 绑定交换机 await queue.bind(exchange, routing_key=event_pattern) async with queue.iterator() as queue_iter: async for message in queue_iter: try: event_data = json.loads(message.body.decode()) await handler(event_data) await message.ack() except Exception as e: await message.nack() # 事件驱动架构示例 class OrderCreatedEvent: """订单创建事件""" def __init__(self, order_id, user_id, items): self.event_type = 'order.created' self.data = { 'order_id': order_id, 'user_id': user_id, 'items': items, 'timestamp': datetime.now().isoformat() } # 订单服务发布事件 async def create_order_with_event(order_data): # 创建订单 order = await order_repository.create(order_data) # 发布事件 event_bus = EventBus() await event_bus.publish( 'order.created', OrderCreatedEvent( order.id, order.user_id, order.items ).data ) return order # 库存服务监听事件 async def handle_order_created(event_data): """处理订单创建事件 - 扣减库存""" order_id = event_data['order_id'] items = event_data['items'] for item in items: await inventory_service.deduct_stock( item['product_id'], item['quantity'] ) await event_bus.publish( 'inventory.deducted', {'order_id': order_id, 'status': 'completed'} ) # 通知服务监听事件 async def handle_inventory_deducted(event_data): """处理库存扣减完成事件 - 发送通知""" order_id = event_data['order_id'] order = await order_repository.get(order_id) await notification_service.send_order_confirmation( order.user_email, order_id ) 2.3 服务发现与注册 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 # ========== 服务注册中心 ========== import asyncio from typing import Dict, List, Optional from datetime import datetime, timedelta class ServiceInstance: """服务实例""" def __init__(self, service_id: str, address: str, port: int): self.service_id = service_id self.address = address self.port = port self.last_heartbeat = datetime.now() @property def url(self) -> str: return f"http://{self.address}:{self.port}" def is_alive(self, timeout: int = 10) -> bool: """检查实例是否存活""" return (datetime.now() - self.last_heartbeat).seconds < timeout class ServiceRegistry: """服务注册中心""" def __init__(self): self.services: Dict[str, List[ServiceInstance]] = {} def register(self, service_name: str, instance: ServiceInstance): """注册服务实例""" if service_name not in self.services: self.services[service_name] = [] # 检查是否已存在 existing = next( (i for i in self.services[service_name] if i.service_id == instance.service_id), None ) if existing: # 更新心跳时间 existing.last_heartbeat = datetime.now() else: # 新注册 self.services[service_name].append(instance) print(f"Registered: {service_name} - {instance.url}") def deregister(self, service_name: str, service_id: str): """注销服务实例""" if service_name in self.services: self.services[service_name] = [ i for i in self.services[service_name] if i.service_id != service_id ] def discover(self, service_name: str) -> Optional[ServiceInstance]: """服务发现 - 负载均衡""" if service_name not in self.services: return None # 过滤掉失效的实例 alive_instances = [ i for i in self.services[service_name] if i.is_alive() ] if not alive_instances: return None # 轮询负载均衡 return alive_instances[hash(service_name) % len(alive_instances)] # 或者使用随机选择 # return random.choice(alive_instances) def heartbeat(self, service_name: str, service_id: str): """接收心跳""" if service_name in self.services: for instance in self.services[service_name]: if instance.service_id == service_id: instance.last_heartbeat = datetime.now() # ========== 服务客户端 ========== class ServiceClient: """服务客户端 - 带服务发现""" def __init__(self, registry: ServiceRegistry): self.registry = registry self.cache = {} # 缓存服务地址 async def call(self, service_name: str, endpoint: str, **kwargs): """调用服务""" # 从缓存或注册中心获取服务地址 instance = self.cache.get(service_name) if not instance or not instance.is_alive(): instance = self.registry.discover(service_name) if not instance: raise ServiceUnavailableException(f"Service {service_name} not found") self.cache[service_name] = instance # 构建请求URL url = f"{instance.url}{endpoint}" try: response = requests.post(url, json=kwargs, timeout=5) response.raise_for_status() return response.json() except requests.RequestException as e: # 调用失败,清除缓存 self.cache.pop(service_name, None) raise e # ========== 使用示例 ========== # 服务启动时注册 registry = ServiceRegistry() async def start_service(): service_instance = ServiceInstance( service_id=f"order-service-{os.getenv('INSTANCE_ID')}", address=os.getenv('SERVICE_ADDRESS'), port=int(os.getenv('SERVICE_PORT')) ) registry.register('order-service', service_instance) # 定期发送心跳 while True: await asyncio.sleep(5) registry.heartbeat('order-service', service_instance.service_id) 2.4 分布式配置管理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 # ========== 配置中心 ========== import asyncio import json from typing import Any, Callable from watchfiles import awatch class ConfigCenter: """分布式配置中心""" def __init__(self, config_dir: str = './config'): self.config_dir = config_dir self.configs = {} self.watchers = {} # config_key -> [callbacks] def load_config(self, service_name: str) -> dict: """加载服务配置""" config_file = f"{self.config_dir}/{service_name}.json" try: with open(config_file) as f: config = json.load(f) self.configs[service_name] = config return config except FileNotFoundError: return {} def get_config(self, service_name: str, key: str = None) -> Any: """获取配置""" config = self.configs.get(service_name, {}) if key: return config.get(key) return config def watch_config(self, service_name: str, callback: Callable): """监听配置变化""" if service_name not in self.watchers: self.watchers[service_name] = [] self.watchers[service_name].append(callback) async def watch_changes(self): """监听配置文件变化""" async for changes in awatch(self.config_dir): for change_type, config_path in changes: service_name = config_path.stem if change_type == Change.modified: # 重新加载配置 old_config = self.configs.get(service_name, {}) new_config = self.load_config(service_name) # 触发回调 if service_name in self.watchers: for callback in self.watchers[service_name]: await callback(old_config, new_config) # ========== 使用示例 ========== config_center = ConfigCenter() # 加载配置 app_config = config_center.load_config('order-service') # 监听配置变化 async def on_config_changed(old_config, new_config): """配置变化处理""" if old_config.get('log_level') != new_config.get('log_level'): # 重新配置日志级别 logging.getLogger().setLevel(new_config['log_level']) if old_config.get('database') != new_config.get('database'): # 重新建立数据库连接 await reconnect_database(new_config['database']) config_center.watch_config('order-service', on_config_changed) 三、数据一致性设计 3.1 分布式事务 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 # ========== 两阶段提交 (2PC) ========== class TwoPhaseCommit: """两阶段提交协调者""" def __init__(self): self.participants = [] def register_participant(self, participant): """注册参与者""" self.participants.append(participant) async def execute(self, transaction_data): """执行分布式事务""" transaction_id = generate_transaction_id() # 阶段1: 准备阶段 prepared = [] for participant in self.participants: try: result = await participant.prepare(transaction_id, transaction_data) if result == 'PREPARED': prepared.append(participant) else: # 任何参与者拒绝,回滚所有 await self._rollback_all(transaction_id, prepared) return False except Exception as e: await self._rollback_all(transaction_id, prepared) raise e # 阶段2: 提交阶段 committed = [] for participant in prepared: try: await participant.commit(transaction_id) committed.append(participant) except Exception as e: # 提交失败,需要人工介入 await self._rollback_all(transaction_id, committed) raise Exception(f"Commit failed: {e}") return True async def _rollback_all(self, transaction_id, participants): """回滚所有参与者""" for participant in participants: try: await participant.rollback(transaction_id) except Exception as e: logging.error(f"Rollback failed: {e}") # ========== Saga模式 ========== # 长事务的替代方案 class SagaOrchestrator: """Saga编排器""" def __init__(self): self.steps = [] self.compensations = [] def add_step(self, action, compensation): """添加步骤""" self.steps.append(action) self.compensations.append(compensation) async def execute(self, initial_data): """执行Saga""" context = initial_data executed_steps = [] # 执行每个步骤 for i, step in enumerate(self.steps): try: context = await step(context) executed_steps.append(i) except Exception as e: # 失败,执行补偿 await self._compensate(executed_steps, context) raise e return context async def _compensate(self, executed_steps, context): """执行补偿事务""" # 逆序执行补偿 for i in reversed(executed_steps): try: await self.compensations[i](context) except Exception as e: logging.error(f"Compensation failed: {e}") # 订单Saga示例 class OrderSaga: """订单处理Saga""" def __init__(self): self.saga = SagaOrchestrator() self._setup_steps() def _setup_steps(self): """设置Saga步骤""" # 步骤1: 创建订单 async def create_order(context): order = await order_repository.create(context['order_data']) context['order'] = order return context async def cancel_order(context): await order_repository.update_status( context['order'].id, 'CANCELLED' ) # 步骤2: 扣减库存 async def deduct_inventory(context): for item in context['order'].items: await inventory_service.deduct_stock( item.product_id, item.quantity ) return context async def restore_inventory(context): for item in context['order'].items: await inventory_service.restore_stock( item.product_id, item.quantity ) # 步骤3: 处理支付 async def process_payment(context): payment = await payment_service.charge( context['order'].user_id, context['order'].total_amount ) context['payment'] = payment return context async def refund_payment(context): await payment_service.refund( context['payment'].transaction_id ) # 步骤4: 发送通知 async def send_notification(context): await notification_service.send( context['order'].user_email, 'Order Created', f'Your order {context["order"].id} has been created' ) return context async def cancel_notification(context): # 通知可能不需要补偿 pass # 添加步骤和补偿 self.saga.add_step(create_order, cancel_order) self.saga.add_step(deduct_inventory, restore_inventory) self.saga.add_step(process_payment, refund_payment) self.saga.add_step(send_notification, cancel_notification) async def execute(self, order_data): """执行订单Saga""" return await self.saga.execute({'order_data': order_data}) 3.2 最终一致性 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 # ========== 事件溯源 ========== # 通过事件流重建状态 class EventStore: """事件存储""" def __init__(self): self.events = [] async def append_event(self, aggregate_id: str, event: dict): """追加事件""" event['aggregate_id'] = aggregate_id event['timestamp'] = datetime.now().isoformat() event['version'] = len(self.events) + 1 self.events.append(event) async def get_events(self, aggregate_id: str) -> List[dict]: """获取聚合的所有事件""" return [ e for e in self.events if e['aggregate_id'] == aggregate_id ] class OrderAggregate: """订单聚合 - 通过事件重建状态""" def __init__(self, event_store: EventStore): self.event_store = event_store self.state = None async def rebuild(self, order_id: str): """从事件流重建状态""" events = await self.event_store.get_events(order_id) state = None for event in events: state = self._apply_event(state, event) self.state = state return state def _apply_event(self, state, event): """应用事件到状态""" event_type = event['type'] if event_type == 'OrderCreated': return { 'id': event['order_id'], 'user_id': event['user_id'], 'items': event['items'], 'status': 'CREATED' } elif event_type == 'PaymentCompleted': state['status'] = 'PAID' state['payment_id'] = event['payment_id'] return state elif event_type == 'OrderShipped': state['status'] = 'SHIPPED' state['shipping_id'] = event['shipping_id'] return state elif event_type == 'OrderCancelled': state['status'] = 'CANCELLED' return state return state async def create_order(self, user_id, items): """创建订单""" event = { 'type': 'OrderCreated', 'order_id': generate_id(), 'user_id': user_id, 'items': items } await self.event_store.append_event(event['order_id'], event) return await self.rebuild(event['order_id']) # ========== CQRS ========== # 命令查询职责分离 class CommandBus: """命令总线""" def __init__(self): self.handlers = {} def register(self, command_type: str, handler): """注册命令处理器""" self.handlers[command_type] = handler async def execute(self, command: dict): """执行命令""" command_type = command['type'] if command_type not in self.handlers: raise ValueError(f"Unknown command: {command_type}") return await self.handlers[command_type](command) class QueryBus: """查询总线""" def __init__(self): self.handlers = {} def register(self, query_type: str, handler): """注册查询处理器""" self.handlers[query_type] = handler async def execute(self, query: dict): """执行查询""" query_type = query['type'] if query_type not in self.handlers: raise ValueError(f"Unknown query: {query_type}") return await self.handlers[query_type](query) # CQRS示例 class OrderService: """订单服务 - CQRS""" def __init__(self): self.command_bus = CommandBus() self.query_bus = QueryBus() self.event_store = EventStore() self.read_db = {} # 读模型 self._register_handlers() def _register_handlers(self): """注册处理器""" # 命令处理器 self.command_bus.register('CreateOrder', self._handle_create_order) self.command_bus.register('CancelOrder', self._handle_cancel_order) # 查询处理器 self.query_bus.register('GetOrder', self._handle_get_order) self.query_bus.register('ListOrders', self._handle_list_orders) async def _handle_create_order(self, command): """处理创建订单命令""" event = { 'type': 'OrderCreated', 'order_id': command['order_id'], 'user_id': command['user_id'], 'items': command['items'] } await self.event_store.append_event(command['order_id'], event) # 更新读模型 self._update_read_model(event) return event['order_id'] async def _handle_cancel_order(self, command): """处理取消订单命令""" event = { 'type': 'OrderCancelled', 'order_id': command['order_id'] } await self.event_store.append_event(command['order_id'], event) # 更新读模型 self._update_read_model(event) async def _handle_get_order(self, query): """处理获取订单查询""" return self.read_db.get(query['order_id']) async def _handle_list_orders(self, query): """处理订单列表查询""" user_id = query.get('user_id') orders = [ order for order in self.read_db.values() if not user_id or order['user_id'] == user_id ] return orders def _update_read_model(self, event): """更新读模型""" order_id = event['order_id'] if event['type'] == 'OrderCreated': self.read_db[order_id] = { 'id': order_id, 'user_id': event['user_id'], 'items': event['items'], 'status': 'CREATED' } elif event['type'] == 'OrderCancelled': if order_id in self.read_db: self.read_db[order_id]['status'] = 'CANCELLED' 四、容错与高可用设计 4.1 熔断器模式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 import asyncio from enum import Enum from datetime import datetime, timedelta class CircuitState(Enum): CLOSED = 'CLOSED' # 正常状态 OPEN = 'OPEN' # 熔断状态 HALF_OPEN = 'HALF_OPEN' # 半开状态 class CircuitBreaker: """熔断器""" def __init__( self, failure_threshold: int = 5, timeout: int = 60, half_open_attempts: int = 3 ): self.failure_threshold = failure_threshold self.timeout = timeout self.half_open_attempts = half_open_attempts self.state = CircuitState.CLOSED self.failure_count = 0 self.success_count = 0 self.last_failure_time = None async def call(self, func, *args, **kwargs): """通过熔断器调用函数""" if self.state == CircuitState.OPEN: # 熔断状态,检查是否可以进入半开 if self._should_attempt_reset(): self.state = CircuitState.HALF_OPEN self.success_count = 0 else: raise CircuitBreakerOpenException( f"Circuit breaker is OPEN. Try again later." ) try: result = await func(*args, **kwargs) # 成功,重置计数 self._on_success() return result except Exception as e: # 失败,增加计数 self._on_failure() raise e def _should_attempt_reset(self) -> bool: """检查是否应该尝试重置""" if self.last_failure_time is None: return False elapsed = (datetime.now() - self.last_failure_time).seconds return elapsed >= self.timeout def _on_success(self): """处理成功""" if self.state == CircuitState.HALF_OPEN: self.success_count += 1 # 半开状态下连续成功,恢复关闭状态 if self.success_count >= self.half_open_attempts: self.state = CircuitState.CLOSED self.failure_count = 0 elif self.state == CircuitState.CLOSED: self.failure_count = 0 def _on_failure(self): """处理失败""" self.failure_count += 1 self.last_failure_time = datetime.now() # 达到阈值,打开熔断器 if self.failure_count >= self.failure_threshold: self.state = CircuitState.OPEN # 使用示例 async def call_external_service(url): """调用外部服务""" response = await aiohttp.get(url) return await response.json() # 创建熔断器 circuit_breaker = CircuitBreaker( failure_threshold=5, timeout=60, half_open_attempts=3 ) # 通过熔断器调用 try: result = await circuit_breaker.call( call_external_service, 'http://external-service/api/data' ) except CircuitBreakerOpenException: # 熔断器打开,使用降级逻辑 result = get_cached_data() except Exception as e: # 其他错误处理 logger.error(f"Service call failed: {e}") 4.2 重试与超时 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 import asyncio from functools import wraps from typing import Callable, Type class RetryConfig: """重试配置""" def __init__( self, max_attempts: int = 3, base_delay: float = 1.0, max_delay: float = 10.0, exponential_base: float = 2, jitter: bool = True, retry_exceptions: list = None ): self.max_attempts = max_attempts self.base_delay = base_delay self.max_delay = max_delay self.exponential_base = exponential_base self.jitter = jitter self.retry_exceptions = retry_exceptions or [Exception] def retry(config: RetryConfig = None): """重试装饰器""" if config is None: config = RetryConfig() def decorator(func: Callable): @wraps(func) async def wrapper(*args, **kwargs): last_exception = None for attempt in range(1, config.max_attempts + 1): try: return await func(*args, **kwargs) except tuple(config.retry_exceptions) as e: last_exception = e if attempt < config.max_attempts: # 计算延迟时间 delay = min( config.base_delay * (config.exponential_base ** (attempt - 1)), config.max_delay ) # 添加抖动 if config.jitter: delay = delay * (0.5 + random.random() * 0.5) logger.warning( f"Attempt {attempt} failed: {e}. " f"Retrying in {delay:.2f}s..." ) await asyncio.sleep(delay) # 所有尝试都失败 raise last_exception return wrapper return decorator # 超时装饰器 def timeout(seconds: float): """超时装饰器""" def decorator(func: Callable): @wraps(func) async def wrapper(*args, **kwargs): try: return await asyncio.wait_for( func(*args, **kwargs), timeout=seconds ) except asyncio.TimeoutError: raise TimeoutException( f"Function {func.__name__} timed out after {seconds}s" ) return wrapper return decorator # 使用示例 @retry(RetryConfig( max_attempts=3, base_delay=1.0, exponential_base=2, retry_exceptions=[ConnectionError, TimeoutError] )) @timeout(seconds=5) async def call_external_api(url): """调用外部API,带重试和超时""" async with aiohttp.ClientSession() as session: async with session.get(url) as response: response.raise_for_status() return await response.json() 4.3 限流与降级 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 import time from collections import deque from typing import Callable, Any class RateLimiter: """速率限制器""" def __init__(self, rate: int, per: float): """ rate: 允许的请求数 per: 时间窗口(秒) """ self.rate = rate self.per = per self.allowance = rate self.last_check = time.time() def acquire(self, tokens: int = 1) -> bool: """获取令牌""" current = time.time() elapsed = current - self.last_check # 补充令牌 self.allowance += elapsed * (self.rate / self.per) if self.allowance > self.rate: self.allowance = self.rate self.last_check = current # 检查是否有足够的令牌 if self.allowance < tokens: return False self.allowance -= tokens return True class TokenBucket: """令牌桶算法""" def __init__(self, capacity: int, refill_rate: float): """ capacity: 桶容量 refill_rate: 填充速率(每秒) """ self.capacity = capacity self.refill_rate = refill_rate self.tokens = capacity self.last_refill = time.time() def consume(self, tokens: int = 1) -> bool: """消费令牌""" self._refill() if self.tokens >= tokens: self.tokens -= tokens return True return False def _refill(self): """补充令牌""" now = time.time() elapsed = now - self.last_refill refill_amount = elapsed * self.refill_rate self.tokens = min(self.capacity, self.tokens + refill_amount) self.last_refill = now class SlidingWindow: """滑动窗口限流""" def __init__(self, limit: int, window: float): """ limit: 窗口内最大请求数 window: 时间窗口(秒) """ self.limit = limit self.window = window self.requests = deque() def is_allowed(self) -> bool: """检查是否允许请求""" now = time.time() # 移除窗口外的请求 while self.requests and self.requests[0] < now - self.window: self.requests.popleft() # 检查是否超过限制 if len(self.requests) >= self.limit: return False self.requests.append(now) return True # 降级装饰器 class FallbackExecutor: """降级执行器""" def __init__(self): self.fallbacks = {} def register_fallback(self, func_name: str, fallback: Callable): """注册降级函数""" self.fallbacks[func_name] = fallback async def execute_with_fallback( self, func: Callable, *args, fallback_result: Any = None, **kwargs ): """执行函数,失败时降级""" try: return await func(*args, **kwargs) except Exception as e: func_name = func.__name__ # 查找注册的降级函数 if func_name in self.fallbacks: logger.warning(f"Function {func_name} failed, using fallback") return await self.fallbacks[func_name](*args, **kwargs) # 使用默认降级结果 if fallback_result is not None: logger.warning(f"Function {func_name} failed, using fallback result") return fallback_result # 没有降级方案,抛出异常 raise e # 使用示例 # 创建限流器 rate_limiter = RateLimiter(rate=100, per=1) # 100请求/秒 token_bucket = TokenBucket(capacity=10, refill_rate=1) # 10令牌容量,每秒补充1个 sliding_window = SlidingWindow(limit=100, window=60) # 60秒内最多100请求 # 创建降级执行器 fallback_executor = FallbackExecutor() async def get_user_data(user_id): """获取用户数据""" # 检查限流 if not rate_limiter.acquire(): raise RateLimitException("Too many requests") # 调用服务 return await user_service.get_user(user_id) # 注册降级函数 async def get_user_data_fallback(user_id): """降级:返回缓存的用户数据""" return await cache.get(f"user:{user_id}") fallback_executor.register_fallback('get_user_data', get_user_data_fallback) # 使用 try: result = await fallback_executor.execute_with_fallback( get_user_data, user_id='123' ) except Exception as e: logger.error(f"All attempts failed: {e}") 五、可观测性设计 5.1 日志系统 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 import structlog from typing import Any class LogContext: """日志上下文""" def __init__(self): self.context = {} def set(self, key: str, value: Any): """设置上下文""" self.context[key] = value def get(self, key: str, default=None): """获取上下文""" return self.context.get(key, default) def clear(self): """清空上下文""" self.context.clear() # 全局日志上下文 log_context = LogContext() # 配置structlog structlog.configure( processors=[ structlog.stdlib.filter_by_level, structlog.stdlib.add_logger_name, structlog.stdlib.add_log_level, structlog.stdlib.PositionalArgumentsFormatter(), structlog.processors.TimeStamper(fmt="iso"), structlog.processors.StackInfoRenderer(), structlog.processors.format_exc_info, structlog.processors.UnicodeDecoder(), # 添加上下文 lambda logger, method_name, event_dict: { **event_dict, **log_context.context }, # 格式化输出 structlog.processors.JSONRenderer() ], context_class=dict, logger_factory=structlog.stdlib.LoggerFactory(), cache_logger_on_first_use=True, ) class ServiceLogger: """服务日志记录器""" def __init__(self, service_name: str): self.service_name = service_name self.logger = structlog.get_logger() def log_request(self, request_id: str, method: str, path: str, **kwargs): """记录请求""" self.logger.info( "incoming_request", request_id=request_id, service=self.service_name, method=method, path=path, **kwargs ) def log_response( self, request_id: str, status_code: int, duration_ms: float, **kwargs ): """记录响应""" self.logger.info( "outgoing_response", request_id=request_id, service=self.service_name, status_code=status_code, duration_ms=duration_ms, **kwargs ) def log_error(self, error: Exception, **kwargs): """记录错误""" self.logger.error( "error_occurred", service=self.service_name, error_type=type(error).__name__, error_message=str(error), **kwargs ) def log_service_call( self, service_name: str, method: str, duration_ms: float, success: bool, **kwargs ): """记录服务调用""" self.logger.info( "service_call", caller=self.service_name, service=service_name, method=method, duration_ms=duration_ms, success=success, **kwargs ) # 中间件示例 class LoggingMiddleware: """日志中间件""" def __init__(self, logger: ServiceLogger): self.logger = logger async def process_request(self, request, call_next): """处理请求""" request_id = generate_request_id() start_time = time.time() # 设置日志上下文 log_context.set('request_id', request_id) log_context.set('user_id', request.user_id) # 记录请求 self.logger.log_request( request_id=request_id, method=request.method, path=request.path ) try: # 处理请求 response = await call_next(request) # 记录响应 duration_ms = (time.time() - start_time) * 1000 self.logger.log_response( request_id=request_id, status_code=response.status_code, duration_ms=duration_ms ) return response except Exception as e: duration_ms = (time.time() - start_time) * 1000 self.logger.log_error( error=e, request_id=request_id, duration_ms=duration_ms ) raise finally: log_context.clear() 5.2 链路追踪 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor from opentelemetry.exporter.jaeger.thrift import JaegerExporter # 配置Tracer trace.set_tracer_provider(TracerProvider()) tracer_provider = trace.get_tracer_provider() # 配置Jaeger导出器 jaeger_exporter = JaegerExporter( agent_host_name="localhost", agent_port=6831, ) tracer_provider.add_span_processor( BatchSpanProcessor(jaeger_exporter) ) class TracingClient: """带追踪的客户端""" def __init__(self, service_name: str): self.service_name = service_name self.tracer = trace.get_tracer(__name__) async def call_service( self, service_name: str, method: str, **kwargs ): """调用服务并追踪""" with self.tracer.start_as_current_span( f"{service_name}.{method}", kind=trace.SpanKind.CLIENT ) as span: # 添加属性 span.set_attribute("service", self.service_name) span.set_attribute("target_service", service_name) span.set_attribute("method", method) try: # 注入追踪上下文 headers = {} trace.inject(headers) # 调用服务 result = await self._make_request( service_name, method, headers=headers, **kwargs ) span.set_attribute("success", True) return result except Exception as e: span.record_exception(e) span.set_attribute("success", False) raise async def _make_request(self, service_name, method, headers, **kwargs): """实际请求逻辑""" # 实现服务调用 pass # 使用示例 client = TracingClient("order-service") async def create_order(user_id, items): """创建订单 - 带追踪""" with client.tracer.start_as_current_span("create_order") as span: span.set_attribute("user_id", user_id) span.set_attribute("item_count", len(items)) # 调用库存服务 inventory_result = await client.call_service( "inventory-service", "check_stock", items=items ) # 调用支付服务 payment_result = await client.call_service( "payment-service", "process_payment", user_id=user_id, amount=calculate_amount(items) ) return { "inventory": inventory_result, "payment": payment_result } 5.3 指标监控 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 from prometheus_client import Counter, Histogram, Gauge, start_http_server # 定义指标 request_count = Counter( 'http_requests_total', 'Total HTTP requests', ['method', 'endpoint', 'status'] ) request_duration = Histogram( 'http_request_duration_seconds', 'HTTP request duration', ['method', 'endpoint'] ) active_connections = Gauge( 'active_connections', 'Number of active connections' ) business_metric = Counter( 'business_operations_total', 'Total business operations', ['operation', 'status'] ) class MetricsMiddleware: """指标收集中间件""" def __init__(self): self.active_connections = active_connections async def process_request(self, request, call_next): """处理请求并收集指标""" # 增加活跃连接数 self.active_connections.inc() start_time = time.time() try: response = await call_next(request) # 记录请求计数 request_count.labels( method=request.method, endpoint=request.path, status=response.status_code ).inc() # 记录请求耗时 duration = time.time() - start_time request_duration.labels( method=request.method, endpoint=request.path ).observe(duration) return response finally: # 减少活跃连接数 self.active_connections.dec() class BusinessMetrics: """业务指标收集""" @staticmethod def record_operation(operation: str, success: bool): """记录业务操作""" status = "success" if success else "failure" business_metric.labels( operation=operation, status=status ).inc() @staticmethod def record_order_created(order_value: float): """记录订单创建""" business_metric.labels( operation="order_created", status="success" ).inc() @staticmethod def record_payment_failed(amount: float, reason: str): """记录支付失败""" business_metric.labels( operation=f"payment_failed_{reason}", status="failure" ).inc() # 使用示例 async def create_order_logic(user_id, items): """创建订单逻辑""" try: order = await order_service.create(user_id, items) BusinessMetrics.record_operation("order_created", True) return order except InventoryError as e: BusinessMetrics.record_operation("order_created", False) BusinessMetrics.record_operation("inventory_check_failed", False) raise except PaymentError as e: BusinessMetrics.record_operation("order_created", False) BusinessMetrics.record_payment_failed( order.total, e.reason ) raise # 启动指标服务器 start_http_server(8000) 总结 后端系统架构设计是一个复杂的系统工程,需要综合考虑多个维度: ...

现代前端架构深度解析:构建可扩展的大型应用

引言 随着前端应用的复杂度不断增加,传统的单体前端架构已难以满足大型项目的需求。现代前端架构需要解决代码分割、团队协作、性能优化、可维护性等多方面的挑战。本文将从架构设计的角度,深入探讨如何构建可扩展的大型前端应用。 一、前端架构演进史 1.1 从页面到应用的发展历程 jQuery时代 → AMD/RequireJS → CommonJS/Node.js → ES6 Modules → 现代框架时代 发展阶段 阶段 特点 代表技术 局限性 静态页面 HTML + CSS + 少量JS jQuery、Prototype 代码复用差 模块化初期 RequireJS、SeaJS AMD、CMD 加载复杂 组件化 React、Vue诞生 Virtual DOM 状态管理混乱 工程化 Webpack、Rollup ES6 Modules 构建复杂度高 现代化 Next.js、Nuxt.js SSR、SSR Streaming 学习曲线陡峭 1.2 当前架构挑战 大型前端应用面临的核心问题 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 // 问题1: 代码组织混乱 // src/ // components/ // 1000+ 组件 // pages/ // 200+ 页面 // utils/ // 工具函数散落各处 // api/ // API调用不规范 // 问题2: 状态管理复杂 // - 全局状态与局部状态边界模糊 // - 状态流转难以追踪 // - 多个状态管理方案混用 // 问题3: 性能瓶颈 // - 首屏加载时间长 // - 路由切换卡顿 // - 内存泄漏风险 // 问题4: 团队协作困难 // - 代码冲突频繁 // - 发布周期长 // - 技术栈不统一 二、架构设计原则 2.1 SOLID原则在前端的应用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 // S - 单一职责原则 // ❌ 违反单一职责 class UserComponent { render() { } fetchUser() { } validateInput() { } formatData() { } logAnalytics() { } } // ✅ 遵循单一职责 class UserComponent { constructor( private renderer: UserRenderer, private userService: UserService, private validator: InputValidator ) { } render() { this.renderer.render() } fetchUser() { this.userService.fetch() } } // O - 开闭原则 // 使用插件系统扩展功能 interface ComponentPlugin { install(component: any): void uninstall(component: any): void } class Component { private plugins: ComponentPlugin[] = [] use(plugin: ComponentPlugin) { this.plugins.push(plugin) plugin.install(this) return this } } // L - 里氏替换原则 // 基类可被子类无缝替换 abstract class BaseStore<T> { abstract get(id: string): Promise<T> abstract set(id: string, data: T): Promise<void> } class UserStore extends BaseStore<User> { async get(id: string): Promise<User> { } async set(id: string, data: User): Promise<void> { } } // I - 接口隔离原则 // 拆分大接口为小接口 interface ReadOnlyRepository<T> { findById(id: string): Promise<T> findAll(): Promise<T[]> } interface WriteOnlyRepository<T> { create(data: T): Promise<T> update(id: string, data: Partial<T>): Promise<T> delete(id: string): Promise<void> } // D - 依赖倒置原则 // 依赖抽象而非具体实现 interface CacheService { get(key: string): Promise<any> set(key: string, value: any): Promise<void> } class UserService { constructor(private cache: CacheService) { } } 2.2 分层架构 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 // 标准前端分层架构 ┌─────────────────────────────────────────────┐ │ Presentation Layer │ │ (Components, Pages, UI Logic) │ ├─────────────────────────────────────────────┤ │ Business Logic Layer │ │ (Hooks, Composables, Use Cases) │ ├─────────────────────────────────────────────┤ │ Data Access Layer │ │ (API Client, Cache, State Management) │ ├─────────────────────────────────────────────┤ │ Infrastructure Layer │ │ (HTTP, WebSocket, LocalStorage) │ └─────────────────────────────────────────────┘ // 实现示例 // ========== Presentation Layer ========== // views/UserList.vue <template> <UserDataTable :users="users" :loading="loading" @refresh="handleRefresh" /> </template> // ========== Business Logic Layer ========== // composables/useUserList.ts export function useUserList() { const { users, loading, error, fetch } = userRepository() const refresh = async () => { await fetch() analytics.track('user_list_refreshed') } const filteredUsers = computed(() => { return users.value.filter(user => user.active) }) return { users: filteredUsers, loading, error, refresh } } // ========== Data Access Layer ========== // repositories/userRepository.ts export function userRepository() { const api = useApiClient() const cache = useCache() const fetch = async () => { const cached = await cache.get('users') if (cached) return cached const data = await api.get('/users') await cache.set('users', data, 300) // 5分钟 return data } return { users: ref([]), loading: ref(false), error: ref(null), fetch } } // ========== Infrastructure Layer =========== // utils/apiClient.ts class ApiClient { private baseURL: string private interceptors: RequestInterceptor[] async get<T>(url: string): Promise<T> { const request = new Request(this.baseURL + url) return this.execute<T>(request) } } 2.3 领域驱动设计(DDD)在前端 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 // 1. 领域模型定义 // domains/user/User.ts export class User { constructor( private readonly id: UserId, private readonly email: Email, private name: UserName, private status: UserStatus ) {} // 领域逻辑 activate(): void { if (this.status === UserStatus.ACTIVE) { throw new Error('User already active') } this.status = UserStatus.ACTIVE } deactivate(): void { this.status = UserStatus.INACTIVE } isActive(): boolean { return this.status === UserStatus.ACTIVE } } // 值对象 export class Email { constructor(private readonly value: string) { if (!this.validate(value)) { throw new Error('Invalid email') } } private validate(email: string): boolean { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) } getValue(): string { return this.value } } // 2. 领域服务 // domains/user/UserService.ts export class UserService { constructor( private userRepo: UserRepository, private emailService: EmailService ) {} async registerUser(data: RegisterUserData): Promise<User> { // 业务规则验证 if (await this.userRepo.existsByEmail(data.email)) { throw new Error('Email already registered') } // 创建领域对象 const user = new User( UserId.generate(), new Email(data.email), new UserName(data.name), UserStatus.PENDING ) // 持久化 await this.userRepo.save(user) // 发送欢迎邮件 await this.emailService.sendWelcome(user.email.getValue()) return user } } // 3. 应用服务(用例) // application/useCases/RegisterUserUseCase.ts export class RegisterUserUseCase { constructor(private userService: UserService) { } async execute(request: RegisterUserRequest): Promise<RegisterUserResponse> { try { const user = await this.userService.registerUser(request.data) return { success: true, userId: user.id.getValue(), message: 'Registration successful' } } catch (error) { return { success: false, error: error.message } } } } // 4. 在组件中使用 // components/RegisterForm.vue export default { setup() { const registerUser = useRegisterUserUseCase() const handleSubmit = async (formData) => { const result = await registerUser.execute({ data: { email: formData.email, name: formData.name, password: formData.password } }) if (result.success) { router.push(`/welcome/${result.userId}`) } else { showError(result.error) } } return { handleSubmit } } } 三、微前端架构 3.1 微前端架构模式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 // 模式1: 路由分发 // 主应用根据路由加载不同子应用 const microApps = [ { name: 'user-center', entry: '//localhost:3001', container: '#subapp', activeRule: '/users' }, { name: 'order-system', entry: '//localhost:3002', container: '#subapp', activeRule: '/orders' } ] // 模式2: 组合式集成 // 主应用提供容器,子应用作为组件渲染 <template> <div> <AppHeader /> <MicroApp name="user-center" :props="userProps" /> <AppFooter /> </div> </template> // 模式3: EMP (EMP Module Federation) // 去中心化的模块共享 // 子应用A new ModuleFederationPlugin({ name: 'appA', exposes: { './UserList': './src/components/UserList' }, shared: ['vue', 'vue-router'] }) // 子应用B使用A的组件 import UserList from 'appA/UserList' 3.2 模块联邦实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 // webpack.config.js - 主应用 const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin') module.exports = { plugins: [ new ModuleFederationPlugin({ name: 'host_app', remotes: { userApp: 'user_app@http://localhost:3001/remoteEntry.js', orderApp: 'order_app@http://localhost:3002/remoteEntry.js' }, shared: { vue: { singleton: true, requiredVersion: '^3.0.0' }, 'vue-router': { singleton: true } } }) ] } // 在主应用中使用远程模块 // src/App.vue <script> import { defineAsyncComponent } from 'vue' // 动态加载远程组件 const UserDashboard = defineAsyncComponent(() => import('userApp/Dashboard') ) const OrderList = defineAsyncComponent(() => import('orderApp/OrderList') ) export default { components: { UserDashboard, OrderList } } </script> // 子应用配置 - userApp // webpack.config.js module.exports = { plugins: [ new ModuleFederationPlugin({ name: 'user_app', filename: 'remoteEntry.js', exposes: { './Dashboard': './src/components/Dashboard.vue', './UserProfile': './src/components/UserProfile.vue', './UserStore': './src/stores/user' }, shared: { vue: { singleton: true, requiredVersion: '^3.0.0' } } }) ] } 3.3 微前端通信方案 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 // ========== 方案1: 自定义事件总线 ========== // utils/eventBus.ts class MicroEventBus { private events: Map<string, Set<Function>> constructor() { this.events = new Map() } on(event: string, callback: Function) { if (!this.events.has(event)) { this.events.set(event, new Set()) } this.events.get(event)!.add(callback) } off(event: string, callback: Function) { this.events.get(event)?.delete(callback) } emit(event: string, data?: any) { this.events.get(event)?.forEach(callback => callback(data)) } } // 全局单例 export const microEventBus = new MicroEventBus() // 子应用A - 发送事件 import { microEventBus } from './eventBus' microEventBus.emit('user:login', { userId: '123', userName: 'Alice' }) // 子应用B - 监听事件 microEventBus.on('user:login', (user) => { console.log('User logged in:', user) updateUI(user) }) // ========== 方案2: 状态共享 ========== // stores/sharedStore.ts import { reactive, readonly } from 'vue' const state = reactive({ user: null, theme: 'light', locale: 'zh-CN' }) export const sharedStore = { state: readonly(state), setUser(user: any) { state.user = user }, setTheme(theme: string) { state.theme = theme }, setLocale(locale: string) { state.locale = locale } } // ========== 方案3: 全局状态管理 ========== // 使用Pinia创建跨应用store // stores/global.ts import { defineStore } from 'pinia' export const useGlobalStore = defineStore('global', { state: () => ({ currentUser: null, notifications: [] }), actions: { async login(credentials) { const user = await api.login(credentials) this.currentUser = user }, logout() { this.currentUser = null }, addNotification(notification) { this.notifications.push(notification) } } }) 3.4 样式隔离 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 // ========== 方案1: CSS Modules ========== // components/UserCard.module.css .card { padding: 20px; border-radius: 8px; background: white; } .title { font-size: 18px; color: #333; } // components/UserCard.vue <template> <div :class="$style.card"> <h3 :class="$style.title">{{ title }}</h3> </div> </template> <script> import styles from './UserCard.module.css' export default { $style: styles } </script> // ========== 方案2: Shadow DOM ========== // components/ShadowWidget.ts class ShadowWidget extends HTMLElement { constructor() { super() // 创建Shadow DOM const shadow = this.attachShadow({ mode: 'open' }) // 隔离的样式 const style = document.createElement('style') style.textContent = ` .widget { padding: 20px; background: #f5f5f5; } .widget h3 { color: #333; margin: 0 0 10px 0; } ` // 隔离的内容 const wrapper = document.createElement('div') wrapper.className = 'widget' wrapper.innerHTML = ` <h3>Shadow DOM Widget</h3> <p>This is isolated from host page styles</p> ` shadow.appendChild(style) shadow.appendChild(wrapper) } } customElements.define('shadow-widget', ShadowWidget) // ========== 方案3: CSS-in-JS ========== // 使用styled-components或emotion import styled from 'styled-components' const Card = styled.div` padding: 20px; border-radius: 8px; background: white; h3 { font-size: 18px; color: #333; } ` // 组件自动生成唯一类名 <Card> <h3>Title</h3> </Card> // ========== 方案4: 命名空间 ========== // 推荐的BEM + 命名空间组合 // [子应用名]-[块]__[元素]--[修饰器] .user-center-card__header--active { background: #007bff; } .order-system-list__item--highlighted { background: #ffc107; } 四、状态管理架构 4.1 状态管理选型 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 // ========== 方案对比 ========== // 1. Redux Toolkit - 复杂应用 import { createSlice, configureStore } from '@reduxjs/toolkit' const userSlice = createSlice({ name: 'user', initialState: { user: null, status: 'idle' }, reducers: { setUser(state, action) { state.user = action.payload }, clearUser(state) { state.user = null } }, extraReducers: (builder) => { builder .addCase(fetchUser.pending, (state) => { state.status = 'loading' }) .addCase(fetchUser.fulfilled, (state, action) => { state.status = 'succeeded' state.user = action.payload }) } }) export const { setUser, clearUser } = userSlice.actions export default configureStore({ reducer: { user: userSlice.reducer } }) // 2. Zustand - 轻量级 import create from 'zustand' const useUserStore = create((set, get) => ({ user: null, status: 'idle', setUser: (user) => set({ user }), fetchUser: async (id) => { set({ status: 'loading' }) const user = await api.getUser(id) set({ user, status: 'succeeded' }) }, getUserAge: () => { const { user } = get() return user ? calculateAge(user.birthday) : 0 } })) // 3. Pinia - Vue推荐 import { defineStore } from 'pinia' export const useUserStore = defineStore('user', { state: () => ({ user: null, status: 'idle' }), getters: { isLoggedIn: (state) => !!state.user, userName: (state) => state.user?.name || 'Guest' }, actions: { async fetchUser(id) { this.status = 'loading' this.user = await api.getUser(id) this.status = 'succeeded' } } }) // 4. Jotai - 原子化状态 import { atom, useAtom } from 'jotai' // 原子状态 const userAtom = atom(null) const statusAtom = atom('idle') // 派生原子 const isLoggedInAtom = atom( (get) => !!get(userAtom) ) // 组件中使用 function UserProfile() { const [user, setUser] = useAtom(userAtom) const [status] = useAtom(statusAtom) const [isLoggedIn] = useAtom(isLoggedInAtom) // ... } 4.2 分层状态架构 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 // ========== 状态分层设计 ========== // 1. 服务端状态 - React Query / SWR import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' // 获取数据 function useUser(id: string) { return useQuery({ queryKey: ['user', id], queryFn: () => api.getUser(id), staleTime: 5 * 60 * 1000, // 5分钟 cacheTime: 10 * 60 * 1000 // 10分钟 }) } // 修改数据 function useUpdateUser() { const queryClient = useQueryClient() return useMutation({ mutationFn: ({ id, data }) => api.updateUser(id, data), onSuccess: (data, variables) => { // 自动更新缓存 queryClient.setQueryData(['user', variables.id], data) // 或使缓存失效 queryClient.invalidateQueries(['user', variables.id]) } }) } // 2. 全局UI状态 - Zustand import create from 'zustand/vanilla' const uiStore = create((set) => ({ theme: 'light', sidebarOpen: true, modalOpen: false, toggleTheme: () => set((state) => ({ theme: state.theme === 'light' ? 'dark' : 'light' })), toggleSidebar: () => set((state) => ({ sidebarOpen: !state.sidebarOpen })), openModal: () => set({ modalOpen: true }), closeModal: () => set({ modalOpen: false }) })) // 3. 表单状态 - 原子状态 import { atom, useAtom } from 'jotai' const formDataAtom = atom({ username: '', email: '', password: '' }) const formErrorsAtom = atom({}) const useForm = () => { const [data, setData] = useAtom(formDataAtom) const [errors, setErrors] = useAtom(formErrorsAtom) const updateField = (field, value) => { setData((prev) => ({ ...prev, [field]: value })) } const validate = () => { const newErrors = {} if (!data.username) newErrors.username = 'Required' if (!data.email) newErrors.email = 'Required' setErrors(newErrors) return Object.keys(newErrors).length === 0 } return { data, errors, updateField, validate } } // ========== 状态组合使用 ========== function UserProfile({ userId }) { // 服务端状态 const { data: user, isLoading } = useUser(userId) const updateUser = useUpdateUser() // UI状态 const { theme, toggleTheme } = useUiStore() // 本地状态 const [isEditing, setIsEditing] = useState(false) if (isLoading) return <Spinner /> return ( <div className={theme}> {isEditing ? ( <EditForm user={user} onSave={(data) => updateUser.mutate({ id: userId, data })} onCancel={() => setIsEditing(false)} /> ) : ( <UserDetail user={user} onEdit={() => setIsEditing(true)} /> )} <button onClick={toggleTheme}>Toggle Theme</button> </div> ) } 4.3 状态持久化 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 // ========== 本地持久化方案 ========== // 1. Zustand + localStorage import { persist } from 'zustand/middleware' export const useUserStore = create( persist( (set) => ({ user: null, token: null, setUser: (user) => set({ user }), setToken: (token) => set({ token }), logout: () => set({ user: null, token: null }) }), { name: 'user-storage', // 部分持久化 partialize: (state) => ({ user: state.user, token: state.token }) } ) ) // 2. Pinia + localStorage import { createPinia } from 'pinia' import piniaPluginPersistedstate from 'pinia-plugin-persistedstate' const pinia = createPinia() pinia.use(piniaPluginPersistedstate) export const useAuthStore = defineStore('auth', { state: () => ({ token: null, refreshToken: null }), actions: { setTokens(token, refreshToken) { this.token = token this.refreshToken = refreshToken } }, persist: { key: 'auth', storage: localStorage, pick: ['token', 'refreshToken'] } }) // 3. IndexedDB - 大量数据 import { openDB } from 'idb' const dbPromise = openDB('app-db', 1, { upgrade(db) { db.createObjectStore('cache') } }) export const idbStorage = { async getItem(key) { const db = await dbPromise return await db.get('cache', key) }, async setItem(key, value) { const db = await dbPromise return await db.put('cache', value, key) }, async removeItem(key) { const db = await dbPromise return await db.delete('cache', key) } } // 4. 服务端状态同步 import { useQuery, useMutation } from '@tanstack/react-query' // 自动同步到服务端 function useSyncedState(key, initialValue) { const queryClient = useQueryClient() const { data } = useQuery({ queryKey: ['state', key], queryFn: () => api.getState(key), initialData: initialValue }) const mutation = useMutation({ mutationFn: (value) => api.setState(key, value), onSuccess: () => { queryClient.invalidateQueries(['state', key]) } }) const setState = (value) => { mutation.mutate(value) } return [data, setState] } 五、性能优化架构 5.1 代码分割策略 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 // ========== 路由级别分割 ========== // Vue Router const routes = [ { path: '/dashboard', component: () => import( /* webpackChunkName: "dashboard" */ './views/Dashboard.vue' ) }, { path: '/users', component: () => import( /* webpackChunkName: "users" */ './views/Users.vue' ) } ] // React Router const Dashboard = lazy(() => import('./views/Dashboard')) const Users = lazy(() => import('./views/Users')) function App() { return ( <Suspense fallback={<Spinner />}> <Routes> <Route path="/dashboard" element={<Dashboard />} /> <Route path="/users" element={<Users />} /> </Routes> </Suspense> ) } // ========== 组件级别分割 ========== // Vue 3 - defineAsyncComponent const HeavyComponent = defineAsyncComponent({ loader: () => import('./HeavyComponent.vue'), loadingComponent: LoadingSpinner, errorComponent: ErrorDisplay, delay: 200, timeout: 5000 }) // React - lazy + Suspense const HeavyChart = lazy(() => import('./HeavyChart')) function Dashboard() { const [showChart, setShowChart] = useState(false) return ( <div> <button onClick={() => setShowChart(true)}> Show Chart </button> {showChart && ( <Suspense fallback={<Spinner />}> <HeavyChart /> </Suspense> )} </div> ) } // ========== 条件加载 ========== // 只在需要时加载库 const loadMonaco = async () => { const monaco = await import('monaco-editor') return monaco } const loadChartLibrary = async () => { if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) { return null // 用户不喜欢动画 } const chart = await import('echarts') return chart } // ========== 预加载策略 ========== // 预加载下一个可能访问的页面 function ProductList({ products }) { const prefetch = usePrefetch() const handleMouseEnter = (productId) => { // 鼠标悬停时预加载 prefetch(`/products/${productId}`) } return ( <ul> {products.map(product => ( <li key={product.id} onMouseEnter={() => handleMouseEnter(product.id)} > <Link to={`/products/${product.id}`}> {product.name} </Link> </li> ))} </ul> ) } // Webpack魔法注释 const ProductDetail = lazy(() => import( /* webpackPrefetch: true */ /* webpackChunkName: "product-detail" */ './ProductDetail' )) 5.2 渲染优化 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 // ========== 虚拟列表 ========== import { useVirtualizer } from '@tanstack/react-virtual' function VirtualList({ items }) { const parentRef = useRef() const virtualizer = useVirtualizer({ count: items.length, getScrollElement: () => parentRef.current, estimateSize: () => 50, // 每项高度 overscan: 5 // 额外渲染项数 }) return ( <div ref={parentRef} style={{ height: '400px', overflow: 'auto' }}> <div style={{ height: `${virtualizer.getTotalSize()}px`, position: 'relative' }} > {virtualizer.getVirtualItems().map(virtualItem => ( <div key={virtualItem.key} style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: `${virtualItem.size}px`, transform: `translateY(${virtualItem.start}px)` }} > {items[virtualItem.index].content} </div> ))} </div> </div> ) } // ========== 防抖/节流 ========== import { useDebouncedCallback, useThrottledCallback } from '@hooks' function SearchInput() { // 防抖搜索 const debouncedSearch = useDebouncedCallback( (query) => { performSearch(query) }, 500 // 延迟 ) return ( <input type="text" onChange={(e) => debouncedSearch(e.target.value)} /> ) } function ScrollHandler() { // 节流滚动事件 const throttledScroll = useThrottledCallback( () => { updatePosition() }, 100 // 间隔 ) useEffect(() => { window.addEventListener('scroll', throttledScroll) return () => window.removeEventListener('scroll', throttledScroll) }, [throttledScroll]) } // ========== React优化 ========== import { memo, useMemo, useCallback, useRef } from 'react' // 1. 组件记忆化 const ExpensiveComponent = memo(function ExpensiveComponent({ data }) { return <div>{/* 复杂渲染 */}</div> }) // 2. 计算缓存 function DataProcessor({ items }) { const sorted = useMemo(() => { return items.sort((a, b) => a.value - b.value) }, [items]) // 只在items变化时重新计算 const filtered = useMemo(() => { return sorted.filter(item => item.active) }, [sorted]) return <List items={filtered} /> } // 3. 函数稳定化 function ParentComponent() { const [count, setCount] = useState(0) // 不稳定的函数引用 const handleClickBad = () => { setCount(count + 1) } // 稳定的函数引用 const handleClickGood = useCallback(() => { setCount(c => c + 1) }, []) // 依赖为空,函数引用不变 return <ChildComponent onClick={handleClickGood} /> } // 4. 列表渲染优化 function TodoList({ todos, onToggle }) { const todoRefs = useRef(new Map()) const handleToggle = useCallback((id) => { // 批量更新 startTransition(() => { onToggle(id) }) }, [onToggle]) return ( <ul> {todos.map(todo => ( <TodoItem key={todo.id} ref={(node) => { if (node) { todoRefs.current.set(todo.id, node) } else { todoRefs.current.delete(todo.id) } }} todo={todo} onToggle={handleToggle} /> ))} </ul> ) } const TodoItem = memo(function TodoItem({ todo, onToggle }) { return ( <li onClick={() => onToggle(todo.id)}> {todo.text} </li> ) }) // ========== Vue优化 ========== // 1. computed缓存 export default { setup() { const items = ref([]) // 计算属性自动缓存 const filtered = computed(() => { return items.value.filter(item => item.active) }) const sorted = computed(() => { return filtered.value.sort((a, b) => a.value - b.value) }) return { sorted } } } // 2. v-once/v-memo <template> <!-- 只渲染一次 --> <Logo v-once /> <!-- 按条件记忆 --> <div v-for="item in list" :key="item.id" v-memo="[item.id, item.selected]"> {{ item.text }} </div> </template> // 3. watchEffect优化 watchEffect((onCleanup) => { const timer = setInterval(() => { updateData() }, 1000) onCleanup(() => { clearInterval(timer) // 清理副作用 }) }) // 4. shallowRef/shallowReactive // 大对象优化 const state = shallowReactive({ // 只顶层是响应式的 items: largeItemsArray }) // 只需要重新赋值时使用 const data = shallowRef(null) 5.3 资源优化 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 // ========== 图片优化 ========== // 1. 响应式图片 <picture> <source media="(min-width: 1024px)" srcSet="image-large.webp" type="image/webp" /> <source media="(min-width: 768px)" srcSet="image-medium.webp" type="image/webp" /> <source srcSet="image-small.webp" type="image/webp" /> <img src="image-fallback.jpg" alt="Description" loading="lazy" /> </picture> // 2. 懒加载图片 import { lazyload } from '@utils/lazyload' function ImageWithLazy({ src, alt }) { const imgRef = useRef() const [isLoaded, setIsLoaded] = useState(false) useEffect(() => { const observer = new IntersectionObserver( (entries) => { entries.forEach(entry => { if (entry.isIntersecting) { const img = entry.target img.src = img.dataset.src observer.unobserve(img) } }) }, { rootMargin: '50px' } ) if (imgRef.current) { observer.observe(imgRef.current) } return () => observer.disconnect() }, []) return ( <img ref={imgRef} data-src={src} alt={alt} onLoad={() => setIsLoaded(true)} style={{ opacity: isLoaded ? 1 : 0 }} /> ) } // 3. 图片组件封装 function OptimizedImage({ src, alt, width, height, priority = false }) { const [imageSrc, setImageSrc] = useState(null) useEffect(() => { const load = async () => { // 使用WebP转换服务 const webpSrc = await convertToWebP(src, width) setImageSrc(webpSrc) } if (priority) { load() } else { const observer = new IntersectionObserver((entries) => { if (entries[0].isIntersecting) { load() observer.disconnect() } }) // ... observe logic } }, [src, width, priority]) return <img src={imageSrc} alt={alt} loading={!priority ? 'lazy' : 'eager'} /> } // ========== 字体优化 ========== // 1. 字体预加载 <link rel="preload" href="/fonts/main.woff2" as="font" type="font/woff2" crossOrigin="anonymous" /> // 2. 字体显示策略 @font-face { font-family: 'CustomFont'; src: url('/fonts/custom.woff2') format('woff2'); font-display: swap; /* 立即显示后备字体 */ /* font-display: optional; 短暂等待后使用后备字体 */ /* font-display: fallback; 短暂等待,隐藏短时间 */ } // 3. 字体子集化 // 只包含使用的字符 // 使用fonttools或在线工具生成subset // ========== 第三方资源优化 ========== // 动态加载重型库 const loadGoogleMaps = () => { return new Promise((resolve) => { if (window.google) { resolve(window.google) return } const script = document.createElement('script') script.src = `https://maps.googleapis.com/maps/api/js?key=${API_KEY}` script.async = true script.onload = () => resolve(window.google) document.head.appendChild(script) }) } // 使用场景 function MapComponent() { const [map, setMap] = useState(null) useEffect(() => { let mounted = true loadGoogleMaps().then(google => { if (mounted) { setMap(new google.maps.Map(/* ... */)) } }) return () => { mounted = false } }, []) return <div ref={mapRef} /> } // ========== 缓存策略 ========== // Service Worker缓存 // sw.js const CACHE_NAME = 'app-v1' const STATIC_CACHE = [ '/', '/styles/main.css', '/scripts/main.js' ] self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE_NAME).then((cache) => { return cache.addAll(STATIC_CACHE) }) ) }) self.addEventListener('fetch', (event) => { event.respondWith( caches.match(event.request).then((response) => { return response || fetch(event.request) }) ) }) // 网络优先策略 async function networkFirst(request) { try { const response = await fetch(request) const cache = await caches.open(CACHE_NAME) cache.put(request, response.clone()) return response } catch { return caches.match(request) } } // 缓存优先策略 async function cacheFirst(request) { const cached = await caches.match(request) if (cached) return cached const response = await fetch(request) const cache = await caches.open(CACHE_NAME) cache.put(request, response.clone()) return response } // 过期策略 async function staleWhileRevalidate(request) { const cache = await caches.open(CACHE_NAME) const cached = await cache.match(request) const fetchPromise = fetch(request).then((response) => { cache.put(request, response.clone()) return response }) return cached || fetchPromise } 六、构建优化 6.1 Webpack优化配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 // webpack.config.js const path = require('path') const TerserPlugin = require('terser-webpack-plugin') const CssMinimizerPlugin = require('css-minimizer-webpack-plugin') module.exports = { // ========== 1. 构建模式 ========== mode: 'production', // ========== 2. 代码分割 ========== optimization: { splitChunks: { chunks: 'all', cacheGroups: { // 框架代码单独打包 framework: { test: /[\\/]node_modules[\\/](react|react-dom|vue)[\\/]/, name: 'framework', priority: 40 }, // UI库单独打包 ui: { test: /[\\/]node_modules[\\/](@mui|@ant-design|element-plus)[\\/]/, name: 'ui', priority: 30 }, // 工具库 lib: { test: /[\\/]node_modules[\\/](lodash|axios|dayjs)[\\/]/, name: 'lib', priority: 20 }, // 公共代码 commons: { minChunks: 2, priority: 10, reuseExistingChunk: true } } }, // 运行时代码单独提取 runtimeChunk: 'single', // 压缩配置 minimize: true, minimizer: [ new TerserPlugin({ terserOptions: { parse: { ecma: 8 }, compress: { ecma: 5, warnings: false, comparisons: false, inline: 2, drop_console: true }, mangle: { safari10: true }, output: { ecma: 5, comments: false, ascii_only: true } } }), new CssMinimizerPlugin() ] }, // ========== 3. 模块解析 ========== resolve: { // 路径别名 alias: { '@': path.resolve(__dirname, 'src'), '@components': path.resolve(__dirname, 'src/components'), '@utils': path.resolve(__dirname, 'src/utils') }, // 扩展名 extensions: ['.js', '.jsx', '.ts', '.tsx', '.vue', '.json'], // 模块查找路径 modules: ['node_modules', path.resolve(__dirname, 'src')] }, // ========== 4. 缓存配置 ========== cache: { type: 'filesystem', buildDependencies: { config: [__filename] } }, // ========== 5. 输出配置 ========== output: { path: path.resolve(__dirname, 'dist'), filename: 'js/[name].[contenthash:8].js', chunkFilename: 'js/[name].[contenthash:8].chunk.js', // 资源文件名 assetModuleFilename: 'assets/[name].[hash:8][ext]' }, // ========== 6. 性能优化 ========== performance: { hints: 'warning', maxAssetSize: 244 * 1024, // 244KB maxEntrypointSize: 244 * 1024 } } 6.2 Vite优化配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 // vite.config.ts import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import { visualizer } from 'rollup-plugin-visualizer' import viteCompression from 'vite-plugin-compression' export default defineConfig({ plugins: [ vue(), // 构建分析 visualizer({ open: true, gzipSize: true, brotliSize: true }), // Gzip压缩 viteCompression({ algorithm: 'gzip', ext: '.gz' }), // Brotli压缩 viteCompression({ algorithm: 'brotliCompress', ext: '.br' }) ], build: { // 产物目录 outDir: 'dist', // 静态资源目录 assetsDir: 'assets', // 生成source map sourcemap: false, // 构建后是否生成 manifest.json manifest: true, // chunk大小警告阈值 chunkSizeWarningLimit: 1000, // 代码分割 rollupOptions: { output: { // 手动分包 manualChunks: { 'vue-vendor': ['vue', 'vue-router', 'pinia'], 'ui-lib': ['element-plus'], 'utils': ['axios', 'lodash-es', 'dayjs'] }, // 文件命名 chunkFileNames: 'js/[name]-[hash].js', entryFileNames: 'js/[name]-[hash].js', assetFileNames: '[ext]/[name]-[hash].[ext]' } }, // 压缩 minify: 'terser', terserOptions: { compress: { drop_console: true, drop_debugger: true } } }, // 依赖优化 optimizeDeps: { include: ['vue', 'vue-router', 'pinia'], exclude: ['some-large-dep'] }, // CSS配置 css: { modules: { localsConvention: 'camelCase' }, preprocessorOptions: { scss: { additionalData: `@import "@/styles/variables.scss";` } } }, // 开发服务器 server: { port: 3000, open: true, proxy: { '/api': { target: 'http://localhost:8080', changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, '') } } } }) 七、监控与调试 7.1 性能监控 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 // ========== Core Web Vitals监控 ========== // utils/performanceMonitor.ts interface PerformanceMetrics { FCP: number // First Contentful Paint LCP: number // Largest Contentful Paint FID: number // First Input Delay CLS: number // Cumulative Layout Shift TTFB: number // Time to First Byte } export class PerformanceMonitor { private metrics: Partial<PerformanceMetrics> = {} async collectMetrics(): Promise<PerformanceMetrics> { // 等待页面加载完成 await new Promise(resolve => window.addEventListener('load', resolve)) // FCP const fcpEntry = performance.getEntriesByName('first-contentful-paint')[0] as any this.metrics.FCP = fcpEntry?.startTime || 0 // LCP this.metrics.LCP = await this.getLCP() // FID this.metrics.FID = await this.getFID() // CLS this.metrics.CLS = await this.getCLS() // TTFB const navigation = performance.getEntriesByType('navigation')[0] as any this.metrics.TTFB = navigation?.responseStart || 0 return this.metrics as PerformanceMetrics } private getLCP(): Promise<number> { return new Promise(resolve => { new PerformanceObserver((list) => { const entries = list.getEntries() const lastEntry = entries[entries.length - 1] as any resolve(lastEntry?.startTime || 0) }).observe({ entryTypes: ['largest-contentful-paint'] }) }) } private getFID(): Promise<number> { return new Promise(resolve => { new PerformanceObserver((list) => { const firstInput = list.getEntries()[0] as any resolve(firstInput?.processingStart - firstInput?.startTime || 0) }).observe({ entryTypes: ['first-input'] }) }) } private getCLS(): Promise<number> { return new Promise(resolve => { let clsValue = 0 new PerformanceObserver((list) => { for (const entry of list.getEntries() as any[]) { if (!entry.hadRecentInput) { clsValue += entry.value } } resolve(clsValue) }).observe({ entryTypes: ['layout-shift'] }) }) } reportToAnalytics(metrics: PerformanceMetrics) { // 发送到分析平台 analytics.track('page_performance', { fcp: metrics.FCP, lcp: metrics.LCP, fid: metrics.FID, cls: metrics.CLS, ttfb: metrics.TTFB, url: window.location.href, userAgent: navigator.userAgent }) } } // ========== 错误监控 ========== // utils/errorTracker.ts export class ErrorTracker { private errors: Error[] = [] init() { // 全局错误捕获 window.addEventListener('error', (event) => { this.captureError(event.error || new Error(event.message)) }) // Promise拒绝捕获 window.addEventListener('unhandledrejection', (event) => { this.captureError(event.reason) }) // Vue错误处理 if (typeof app !== 'undefined' && app.config) { app.config.errorHandler = (err, instance, info) => { this.captureError(err, { componentName: instance?.$options?.name, lifecycle: info }) } } } captureError(error: Error, context?: any) { const errorInfo = { message: error.message, stack: error.stack, timestamp: Date.now(), url: window.location.href, userAgent: navigator.userAgent, context } this.errors.push(error as any) // 发送到错误追踪服务 this.sendToService(errorInfo) } private sendToService(errorInfo: any) { // 发送到Sentry、自建服务等 fetch('/api/errors', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(errorInfo) }).catch(console.error) } } // ========== 用户行为追踪 ========== // utils/analytics.ts export class UserBehaviorTracker { private events: any[] = [] trackPageView() { this.trackEvent('page_view', { url: window.location.href, referrer: document.referrer, title: document.title }) } trackClick(element: HTMLElement) { this.trackEvent('click', { tagName: element.tagName, id: element.id, className: element.className, text: element.textContent?.substring(0, 50) }) } trackScroll(depth: number) { this.trackEvent('scroll', { scrollDepth: depth, pageHeight: document.body.scrollHeight }) } trackEngagement(duration: number) { this.trackEvent('engagement', { duration, interactions: this.events.length }) } private trackEvent(type: string, data: any) { const event = { type, data, timestamp: Date.now() } this.events.push(event) this.sendEvent(event) } private sendEvent(event: any) { // 批量发送或实时发送 if (this.events.length >= 10) { this.flush() } } flush() { if (this.events.length === 0) return fetch('/api/analytics/events', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ events: this.events }) }).then(() => { this.events = [] }).catch(console.error) } } 7.2 调试工具 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 // ========== Vue DevTools集成 ========== // 开发环境启用调试功能 if (import.meta.env.DEV) { app.config.devtools = true // 添加组件名称便于调试 app.component('UserProfile', UserProfile) } // ========== React DevTools ========== // 使用React Developer Tools Profiler import { Profiler } from 'react' function onRenderCallback( id, phase, actualDuration, baseDuration, startTime, commitTime ) { console.log({ id, phase, actualDuration, baseDuration, startTime, commitTime }) } <Profiler id="UserProfile" onRender={onRenderCallback}> <UserProfile /> </Profiler> // ========== 自定义调试工具 ========== // utils/debug.ts export const debug = { log: (...args: any[]) => { if (import.meta.env.DEV) { console.log('[DEBUG]', ...args) } }, group: (label: string, fn: () => void) => { if (import.meta.env.DEV) { console.group(label) fn() console.groupEnd() } }, time: (label: string) => { if (import.meta.env.DEV) { console.time(label) } }, timeEnd: (label: string) => { if (import.meta.env.DEV) { console.timeEnd(label) } }, track: (name: string, value: any) => { if (import.meta.env.DEV) { console.log(`[TRACK] ${name}:`, value) } } } // 使用示例 debug.time('dataFetch') fetchData().then(data => { debug.track('fetchedData', data) debug.timeEnd('dataFetch') }) 总结 构建现代前端架构需要综合考虑多个维度: ...

微前端架构设计最佳实践:从理论到落地的完整指南

引言 随着前端应用规模的增长,单体应用面临着维护困难、部署低效、技术栈固化等问题。微前端架构通过将应用拆分为多个独立的子应用,实现了应用级别的模块化。本文将全面介绍微前端架构的设计与实现。 一、微前端基础概念 1.1 什么是微前端 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // 单体应用 vs 微前端 // 单体应用 const MonolithicApp = () => { return ( <div> <Header /> {/* 用户团队维护 */} <Dashboard /> {/* 数据团队维护 */} <Settings /> {/* 配置团队维护 */} <Billing /> {/* 财务团队维护 */} </div> ) } // 微前端架构 const MicroFrontendApp = () => { return ( <div> <MicroApp name="header" /> {/* 独立部署 */} <MicroApp name="dashboard" /> {/* 独立部署 */} <MicroApp name="settings" /> {/* 独立部署 */} <MicroApp name="billing" /> {/* 独立部署 */} </div> ) } 1.2 微前端核心价值 优势 说明 收益 技术栈无关 各子应用可选择不同技术 团队自治、技术灵活性 独立开发部署 子应用独立版本控制 提高发布频率、降低风险 增量升级 逐步迁移旧系统 降低迁移成本 团队自治 独立开发测试部署 提高团队效率 1.3 微前端技术选型对比 方案 实现复杂度 样式隔离 JS隔离 适用场景 qiankun 中 支持 支持 Vue/React/Angular混用 single-spa 高 手动处理 手动处理 高度定制需求 Module Federation 低 需配置 需配置 Webpack 5项目 iframe 低 天然隔离 天然隔离 快速隔离、跨域限制 二、qiankun微前端实战 2.1 主应用配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 // 主应用入口 main.ts import { registerMicroApps, start, initGlobalState } from 'qiankun' // 1. 注册子应用 const apps = [ { name: 'dashboard', entry: '//localhost:7101', container: '#subapp-container', activeRule: '/dashboard', props: { routerBase: '/dashboard', getGlobalState: () => store.getState() } }, { name: 'settings', entry: '//localhost:7102', container: '#subapp-container', activeRule: '/settings', props: { routerBase: '/settings' } }, { name: 'billing', entry: '//localhost:7103', container: '#subapp-container', activeRule: '/billing' } ] // 2. 配置全局状态 const initialState = { user: null, token: null, theme: 'light' } const actions = initGlobalState(initialState) // 3. 监听状态变化 actions.onGlobalStateChange((state, prev) => { console.log('Global state changed:', state, prev) }) // 4. 启动qiankun registerMicroApps(apps, { beforeLoad: [ app => { console.log('Loading app:', app.name) return Promise.resolve() } ], beforeMount: [ app => { console.log('Mounting app:', app.name) return Promise.resolve() } ], afterMount: [ app => { console.log('Mounted app:', app.name) return Promise.resolve() } ], beforeUnmount: [ app => { console.log('Unmounting app:', app.name) return Promise.resolve() } ], afterUnmount: [ app => { console.log('Unmounted app:', app.name) return Promise.resolve() } ] }) start({ sandbox: { strictStyleIsolation: true, // 严格样式隔离 experimentalStyleIsolation: true // 实验性样式隔离 }, prefetch: true, // 预加载子应用资源 singular: false, // 是否单实例 fetch: window.fetch // 自定义fetch方法 }) 2.2 子应用配置(Vue 3) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 // 子应用入口 main.ts import { createApp } from 'vue' import { createRouter, createWebHistory } from 'vue-router' import App from './App.vue' let app: any let router: any let history: any // 渲染函数 function render(props: any = {}) { const { container } = props history = createWebHistory(props.routerBase || '/') router = createRouter({ history, routes: [ { path: '/', component: () => import('./views/Home.vue') }, { path: '/about', component: () => import('./views/About.vue') } ] }) app = createApp(App) app.use(router) app.mount(container ? container.querySelector('#app') : '#app') } // 独立运行 if (!(window as any).__POWERED_BY_QIANKUN__) { render() } // qiankun生命周期 export async function bootstrap() { console.log('Dashboard app bootstrapped') } export async function mount(props: any) { console.log('Dashboard app mounted with props:', props) render(props) // 接收主应用传递的状态 props.onGlobalStateChange && props.onGlobalStateChange((state: any) => { console.log('Global state:', state) }, true) } export async function unmount() { app?.unmount() history?.destroy() app = null router = null history = null } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 // vue.config.js const { name } = require('./package.json') module.exports = { devServer: { port: 7101, headers: { 'Access-Control-Allow-Origin': '*' // 允许跨域 } }, configureWebpack: { output: { library: `${name}-[name]`, libraryTarget: 'umd', globalObject: 'window' } } } 2.3 应用间通信 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 // 1. 基于props通信(推荐) // 主应用 registerMicroApps([ { name: 'dashboard', entry: '//localhost:7101', container: '#subapp-container', activeRule: '/dashboard', props: { // 传递方法 onNavigate: (to: string) => { console.log('Navigate to:', to) }, // 传递数据 sharedData: { apiEndpoint: 'https://api.example.com' }, // 传递状态管理 getGlobalState: () => store.getState() } } ]) // 子应用接收 export async function mount(props: any) { const { onNavigate, sharedData, getGlobalState } = props // 使用传递的方法 onNavigate('/settings') // 访问共享数据 console.log('API endpoint:', sharedData.apiEndpoint) // 访问全局状态 const globalState = getGlobalState() } // 2. 全局状态管理 // 主应用 import { initGlobalState } from 'qiankun' const initialState = { user: null, theme: 'light', locale: 'zh-CN' } const actions = initGlobalState(initialState) // 主应用更新状态 actions.setGlobalState({ user: { id: 1, name: 'Alice' } }) // 子应用监听状态 export async function mount(props: any) { props.onGlobalStateChange((state: any, prev: any) => { console.log('State changed from', prev, 'to', state) // 响应状态变化 if (state.theme !== prev.theme) { updateTheme(state.theme) } }, true) } // 3. 自定义事件总线 // 创建事件总线 class EventBus { private events: Map<string, Function[]> = new Map() on(event: string, callback: Function) { if (!this.events.has(event)) { this.events.set(event, []) } this.events.get(event)!.push(callback) } emit(event: string, ...args: any[]) { const callbacks = this.events.get(event) || [] callbacks.forEach(callback => callback(...args)) } off(event: string, callback: Function) { const callbacks = this.events.get(event) || [] const index = callbacks.indexOf(callback) if (index > -1) { callbacks.splice(index, 1) } } } // 挂载到window window.__EVENT_BUS__ = new EventBus() // 使用 window.__EVENT_BUS__.on('user-login', (user) => { console.log('User logged in:', user) }) window.__EVENT_BUS__.emit('user-login', { id: 1, name: 'Alice' }) 三、Module Federation实战 3.1 Webpack配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 // 主应用 webpack.config.js const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin') module.exports = { plugins: [ new ModuleFederationPlugin({ name: 'host', remotes: { dashboard: 'dashboard@http://localhost:7101/remoteEntry.js', settings: 'settings@http://localhost:7102/remoteEntry.js' }, shared: { react: { singleton: true, requiredVersion: '^18.0.0' }, 'react-dom': { singleton: true, requiredVersion: '^18.0.0' }, vue: { singleton: true, requiredVersion: '^3.0.0' } } }) ] } // 子应用 webpack.config.js module.exports = { plugins: [ new ModuleFederationPlugin({ name: 'dashboard', filename: 'remoteEntry.js', exposes: { './Dashboard': './src/Dashboard.vue', './router': './src/router' }, shared: { vue: { singleton: true, requiredVersion: '^3.0.0' }, 'vue-router': { singleton: true } } }) ] } 3.2 动态加载远程模块 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 // 主应用中动态加载 import { defineAsyncComponent } from 'vue' // 方式1:使用defineAsyncComponent const Dashboard = defineAsyncComponent(() => import('dashboard/Dashboard') ) // 方式2:手动加载 async function loadRemoteModule() { const module = await import('dashboard/Dashboard') return module.default } // 方式3:错误边界 const SafeDashboard = defineAsyncComponent({ loader: () => import('dashboard/Dashboard'), loadingComponent: LoadingSpinner, errorComponent: ErrorDisplay, delay: 200, timeout: 5000 }) // 使用 <template> <Dashboard v-if="loaded" /> <Loading v-else /> </template> 四、样式隔离方案 4.1 CSS Modules 1 2 3 4 5 6 7 8 9 10 /* Dashboard.module.css */ .container { padding: 20px; background: #f0f0f0; } .title { font-size: 24px; color: #333; } 1 2 3 4 5 6 7 8 9 10 <!-- Dashboard.vue --> <template> <div :class="$style.container"> <h1 :class="$style.title">Dashboard</h1> </div> </template> <script setup> import styles from './Dashboard.module.css' </script> 4.2 Shadow DOM 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 // 使用Shadow DOM实现完全隔离 class ShadowComponent extends HTMLElement { constructor() { super() // 创建Shadow DOM const shadow = this.attachShadow({ mode: 'open' }) // 添加样式 const style = document.createElement('style') style.textContent = ` .container { padding: 20px; background: #f0f0f0; } ` shadow.appendChild(style) // 添加内容 const container = document.createElement('div') container.className = 'container' container.innerHTML = '<h1>Shadow DOM Content</h1>' shadow.appendChild(container) } } customElements.define('shadow-component', ShadowComponent) 4.3 动态CSS隔离 1 2 3 4 5 6 7 8 9 10 11 12 13 // qiankun的样式隔离 start({ sandbox: { strictStyleIsolation: true // 为每个子应用创建Shadow DOM } }) // 或使用实验性CSS作用域 start({ sandbox: { experimentalStyleIsolation: true // 添加作用域选择器 } }) 五、共享依赖管理 5.1 依赖共享配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 // webpack.config.js new ModuleFederationPlugin({ shared: { // 单例模式共享 react: { singleton: true, // 只加载一个版本 requiredVersion: '^18.0.0', eager: true // 初始时加载 }, // 版本控制 'lodash': { singleton: false, // 允许多版本 version: '^4.17.0' }, // 自定义共享 'shared-utils': { import: './src/utils', shareScope: 'default' } } }) 5.2 公共组件库 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 // 创建共享组件库 // shared-components/src/index.ts export { Button } from './Button' export { Input } from './Input' export { Modal } from './Modal' // 主应用暴露共享组件 // webpack.config.js new ModuleFederationPlugin({ name: 'host', exposes: { './shared': './shared-components/src' } }) // 子应用使用共享组件 // webpack.config.js new ModuleFederationPlugin({ name: 'dashboard', remotes: { host: 'host@http://localhost:3000/remoteEntry.js' }, shared: { vue: { singleton: true } } }) // 子应用中使用 import { Button, Input } from 'host/shared' 六、部署策略 6.1 独立部署 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 # 主应用部署配置 # .github/workflows/deploy-host.yml name: Deploy Host App on: push: branches: [main] paths: - 'packages/host/**' jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Build run: | cd packages/host npm install npm run build - name: Deploy to CDN run: | aws s3 sync packages/host/dist s3://cdn.example.com/host 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 # 子应用部署配置 # .github/workflows/deploy-dashboard.yml name: Deploy Dashboard App on: push: branches: [main] paths: - 'packages/dashboard/**' jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Build run: | cd packages/dashboard npm install npm run build - name: Deploy to CDN run: | aws s3 sync packages/dashboard/dist s3://cdn.example.com/dashboard 6.2 版本管理策略 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // 应用版本管理 const appVersions = { host: '1.2.0', dashboard: '2.1.0', settings: '1.5.0', billing: '1.0.0' } // A/B测试部署 const abTestConfig = { '/dashboard': { control: '//cdn.example.com/dashboard/2.1.0/remoteEntry.js', experiment: '//cdn.example.com/dashboard/2.2.0/remoteEntry.js', traffic: 0.1 // 10%流量到新版本 } } function getAppEntry(appName: string): string { const config = abTestConfig[`/${appName}`] if (!config) return `//cdn.example.com/${appName}/latest/remoteEntry.js` const traffic = Math.random() return traffic < config.traffic ? config.experiment : config.control } 七、监控与调试 7.1 性能监控 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 // 微前端性能监控 class MicroFrontendMonitor { trackAppLoad(appName: string) { const startTime = performance.now() return { end: () => { const duration = performance.now() - startTime this.sendMetrics({ app: appName, type: 'load', duration }) } } } trackAppError(appName: string, error: Error) { this.sendMetrics({ app: appName, type: 'error', message: error.message, stack: error.stack }) } private sendMetrics(data: any) { fetch('/api/metrics', { method: 'POST', body: JSON.stringify(data) }) } } // 使用qiankun生命周期 const monitor = new MicroFrontendMonitor() registerMicroApps(apps, { beforeMount: [app => monitor.trackAppLoad(app.name)], error: [app => monitor.trackAppError(app.name, app.error)] }) 7.2 错误边界 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 <!-- ErrorBoundary.vue --> <template> <div v-if="error" class="error-boundary"> <h2>Something went wrong</h2> <p>{{ error.message }}</p> <button @click="retry">Retry</button> </div> <slot v-else /> </template> <script setup lang="ts"> import { ref, onErrorCaptured } from 'vue' const error = ref<Error | null>(null) onErrorCaptured((err: Error) => { error.value = err // 上报错误 console.error('Micro frontend error:', err) return false // 阻止错误继续传播 }) function retry() { error.value = null } </script> 总结 微前端架构实施要点: ...

RESTful API设计原则:构建优雅的Web服务接口

深入探讨RESTful API的设计原则和最佳实践,帮助你构建清晰、一致、易用的API接口。

微服务通信模式深度解析

掌握微服务通信的核心模式,构建高效可靠的分布式系统。