[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"public:announcements":3,"footer:categories:zh":4,"public:navigations:zh":132,"post:detail:post-20-CQRSEve:zh":177},[],[5,23,39,55,71,88,103,117],{"id":6,"name":7,"slug":12,"description":13,"icon":18,"color":19,"cover_image":20,"created_at":21,"post_count":22},1,{"en":8,"ja":9,"zh":10,"zh_Hant":11},"Technology","テクノロジー","技术","技術","technology",{"en":14,"ja":15,"zh":16,"zh_Hant":17},"Cutting-edge technology exploration and in-depth analysis covering programming languages, frameworks, and architecture design","プログラミング言語、フレームワーク、アーキテクチャ設計を含む先端技術の探究","前沿技术探索与深度分析，涵盖编程语言、框架、架构设计等核心领域","前沿技術探索與深度分析，涵蓋編程語言、框架、架構設計等核心領域","heroicons:cog-6-tooth","#6366f1",null,"2026-09-30T18:09:53.633610Z",8,{"id":24,"name":25,"slug":29,"description":30,"icon":35,"color":36,"cover_image":20,"created_at":37,"post_count":38},2,{"en":26,"ja":27,"zh":28,"zh_Hant":28},"Tutorial","チュートリアル","教程","tutorial",{"en":31,"ja":32,"zh":33,"zh_Hant":34},"Hands-on tutorials from scratch with clear steps and complete code for developers at all levels","ゼロから始める実践的なチュートリアル。明確な手順と完全なコードで、全てのレベルの開発者に最適","从零开始的实战教程，步骤清晰，代码完整，适合各阶段开发者学习","從零開始的實戰教程，步驟清晰，代碼完整，適合各階段開發者學習","heroicons:academic-cap","#10b981","2026-09-30T18:09:53.641581Z",6,{"id":40,"name":41,"slug":45,"description":46,"icon":51,"color":52,"cover_image":20,"created_at":53,"post_count":54},3,{"en":42,"ja":43,"zh":44,"zh_Hant":44},"Frontend","フロントエンド","前端","frontend",{"en":47,"ja":48,"zh":49,"zh_Hant":50},"Full coverage of web frontend development including Vue, React, new CSS features, and performance optimization","Vue、React、CSSの新機能やパフォーマンス最適化を含むWebフロントエンド開発の全領域","Web前端开发全栈覆盖，包括Vue、React、CSS新特性及性能优化等话题","Web前端開發全棧覆蓋，包括Vue、React、CSS新特性及性能優化等話題","heroicons:computer-desktop","#ec4899","2026-09-30T18:09:53.644838Z",7,{"id":56,"name":57,"slug":62,"description":63,"icon":68,"color":69,"cover_image":20,"created_at":70,"post_count":40},4,{"en":58,"ja":59,"zh":60,"zh_Hant":61},"Backend","バックエンド","后端","後端","backend",{"en":64,"ja":65,"zh":66,"zh_Hant":67},"Server-side development best practices including API design, database optimization, and microservices architecture","API設計、データベース最適化、マイクロサービスアーキテクチャを含むサーバーサイド開発の実践","服务端开发实战经验，API设计、数据库优化、微服务架构等深度内容","服務端開發實戰經驗，API設計、數據庫優化、微服務架構等深度內容","heroicons:server-stack","#f59e0b","2026-09-30T18:09:53.647836Z",{"id":72,"name":73,"slug":78,"description":79,"icon":84,"color":85,"cover_image":20,"created_at":86,"post_count":87},5,{"en":74,"ja":75,"zh":76,"zh_Hant":77},"Fullstack","フルスタック","全栈","全棧","fullstack",{"en":80,"ja":81,"zh":82,"zh_Hant":83},"End-to-end development guides covering the full project lifecycle and technology stack selection","フロントエンドからバックエンドまでの開発プロセス全体をカバーするガイド","从前端到后端的全流程开发指南，覆盖完整项目生命周期与技术选型","從前端到後端的全流程開發指南，覆蓋完整項目生命週期與技術選型","heroicons:swatch","#8b5cf6","2026-09-30T18:09:53.650513Z",0,{"id":38,"name":89,"slug":94,"description":95,"icon":100,"color":101,"cover_image":20,"created_at":102,"post_count":56},{"en":90,"ja":91,"zh":92,"zh_Hant":93},"Essays","エッセイ","随笔","隨筆","essays",{"en":96,"ja":97,"zh":98,"zh_Hant":99},"Technical reflections and development insights recording the programmer's growth journey","プログラマーの成長の軌跡を記録する技術的考察と開発の洞察","技术思考与开发心得分享，记录程序员成长路上的点滴感悟","技術思考與開發心得分享，記錄程序員成長路上的點滴感悟","heroicons:pencil-square","#f43f5e","2026-09-30T18:09:53.653105Z",{"id":54,"name":104,"slug":108,"description":109,"icon":114,"color":115,"cover_image":20,"created_at":116,"post_count":56},{"en":105,"ja":106,"zh":107,"zh_Hant":107},"Tools","ツール","工具","tools",{"en":110,"ja":111,"zh":112,"zh_Hant":113},"Development toolchain and productivity tool recommendations to supercharge your development experience","開発効率を飛躍的に向上させるツールチェーンと生産性ツールの推奨","开发工具链与效率提升利器推荐，让你的开发体验如虎添翼","開發工具鏈與效率提升利器推薦，讓你的開發體驗如虎添翼","heroicons:wrench-screwdriver","#06b6d4","2026-09-30T18:09:53.655605Z",{"id":22,"name":118,"slug":123,"description":124,"icon":129,"color":130,"cover_image":20,"created_at":131,"post_count":87},{"en":119,"ja":120,"zh":121,"zh_Hant":122},"Translation","翻訳","翻译","翻譯","translation",{"en":125,"ja":126,"zh":127,"zh_Hant":128},"Curated translations of high-quality foreign technical articles to keep up with international trends","国際的な技術トレンドを追うための厳選された海外技術記事の翻訳","优质外文技术文章精选翻译，紧跟国际技术前沿动态","優質外文技術文章精選翻譯，緊跟國際技術前沿動態","heroicons:language","#84cc16","2026-09-30T18:09:53.658041Z",[133,144,150,157,164,171],{"id":6,"title":134,"url":139,"icon":20,"parent_id":20,"location":140,"order":6,"is_active":141,"target_blank":142,"created_at":143,"updated_at":20},{"zh":135,"en":136,"ja":137,"zh_TW":138},"首页","Home","ホーム","首頁","\u002F","header",true,false,"2026-09-30T18:09:54.251095Z",{"id":24,"title":145,"url":149,"icon":20,"parent_id":20,"location":140,"order":24,"is_active":141,"target_blank":142,"created_at":143,"updated_at":20},{"zh":146,"en":147,"ja":148,"zh_TW":146},"文章","Posts","記事","\u002Fposts",{"id":40,"title":151,"url":156,"icon":20,"parent_id":20,"location":140,"order":40,"is_active":141,"target_blank":142,"created_at":143,"updated_at":20},{"zh":152,"en":153,"ja":154,"zh_TW":155},"分类","Categories","カテゴリー","分類","\u002Fcategories",{"id":56,"title":158,"url":163,"icon":20,"parent_id":20,"location":140,"order":56,"is_active":141,"target_blank":142,"created_at":143,"updated_at":20},{"zh":159,"en":160,"ja":161,"zh_TW":162},"标签","Tags","タグ","標籤","\u002Ftags",{"id":72,"title":165,"url":170,"icon":20,"parent_id":20,"location":140,"order":72,"is_active":141,"target_blank":142,"created_at":143,"updated_at":20},{"zh":166,"en":167,"ja":168,"zh_TW":169},"关于","About","概要","關於","\u002Fpage\u002Fabout",{"id":38,"title":172,"url":176,"icon":20,"parent_id":20,"location":140,"order":38,"is_active":141,"target_blank":142,"created_at":143,"updated_at":20},{"zh":173,"en":174,"ja":175,"zh_TW":173},"留言板","Guestbook","ゲストブック","\u002Fpage\u002Fguestbook",{"id":178,"title":179,"subtitle":20,"slug":180,"source":181,"source_url":20,"audio":20,"video":20,"video_url":20,"content":182,"excerpt":183,"cover_image":20,"author":184,"category":187,"tags":188,"status":212,"visibility":213,"password":20,"views":214,"likes_count":87,"is_pinned":142,"allow_comments":141,"comments_count":195,"is_password_protected":142,"meta_title":179,"meta_description":183,"meta_keywords":215,"created_at":216,"published_at":216,"updated_at":217,"reading_time":6},20,"CQRS + Event Sourcing 架构模式解析","post-20-CQRSEve","原创","# CQRS + Event Sourcing 架构模式解析\n\n当业务发展到一定规模，传统 CRUD 读写同库模型在复杂查询\u002F审计\u002F并发控制遇到瓶颈。CQRS + ES 是打破瓶颈的高级模式，但复杂度成倍上升，必须慎重选型。\n\n## Event Sourcing：事件为真相源\n\n不存当前状态，只存导致状态变化的事件流（OrderCreated → ItemAdded → OrderPlaced）。重放所有事件可重建任意时间点状态，天然拥有完整审计轨迹。配合快照避免每次从 0 重放。\n\n```python\n```python\nfrom __future__ import annotations\nimport json, time\nfrom dataclasses import dataclass, field\nfrom typing import Callable, Iterable, Any\nfrom collections import defaultdict\n\n@dataclass\nclass DomainEvent:\n    event_id: str\n    aggregate_type: str\n    aggregate_id: str\n    event_type: str\n    payload: dict\n    occurred_at: float = field(default_factory=time.time)\n    version: int = 1\n\nclass EventStore:\n    def __init__(self) -> None:\n        self._events: list[DomainEvent] = []\n        self._snapshots: dict[tuple[str, str], tuple[int, Any]] = {}\n        self._subs: dict[str, list[Callable[[DomainEvent], None]]] = defaultdict(list)\n\n    def append(self, events: Iterable[DomainEvent], expected_version: int | None = None) -> None:\n        events = list(events)\n        if expected_version is not None and events:\n            at, aid = events[0].aggregate_type, events[0].aggregate_id\n            cur = sum(1 for e in self._events if e.aggregate_type == at and e.aggregate_id == aid)\n            if cur != expected_version:\n                raise ValueError(f\"Concurrency conflict: expected v{expected_version}, got v{cur}\")\n        for e in events:\n            self._events.append(e)\n            for s in self._subs.get(e.event_type, []) + self._subs.get(\"*\", []): s(e)\n\n    def load(self, agg_type: str, agg_id: str, snapshot_every: int = 50) -> tuple[Any, int]:\n        key = (agg_type, agg_id)\n        start_ver, state = self._snapshots.get(key, (0, None))\n        version = start_ver\n        events = [e for e in self._events if e.aggregate_type == agg_type and e.aggregate_id == agg_id][start_ver:]\n        for e in events:\n            version += 1\n            fn = globals().get(f\"apply_{e.event_type}\")\n            state = fn(state, e) if fn else state\n            if version % snapshot_every == 0: self._snapshots[key] = (version, state)\n        return state, version\n\n    def subscribe(self, event_type: str, fn: Callable[[DomainEvent], None]) -> None:\n        self._subs[event_type].append(fn)\n\ndef apply_OrderCreated(state, e): return {\"order_id\": e.aggregate_id, \"items\": {}, \"status\": \"CREATED\", **e.payload}\ndef apply_ItemAdded(state, e):\n    s = dict(state); pid = e.payload[\"product_id\"]\n    s[\"items\"] = {**s[\"items\"], pid: s[\"items\"].get(pid, 0) + e.payload[\"qty\"]}\n    return s\ndef apply_OrderPlaced(state, e): return {**state, \"status\": \"PLACED\", \"placed_at\": e.occurred_at}\n\nstore = EventStore()\nprojection: dict[str, dict] = {}\nstore.subscribe(\"OrderPlaced\", lambda e: projection.__setitem__(e.aggregate_id, {\"status\": \"PLACED\", **e.payload}))\n```\n```\n\n## CQRS：写读模型分离\n\n写入侧走领域模型 + 事件，通过事件订阅异步构建读侧投影表（Projection）。写侧保证一致性，读侧针对查询做反范式和索引，各自最优，但引入最终一致性窗口。\n\n| 维度 | 传统 CRUD | 纯 CQRS | CQRS + Event Sourcing |\n|------|----------|--------|---------------------|\n| 存储 | 单表既读又写 | 写库+读库 | 事件流+N个投影表 |\n| 查询能力 | 中等 | 极高 | 极高+时间旅行 |\n| 审计追溯 | 额外加字段 | 难 | 天生免费 |\n| 调试难度 | 低 | 中高 | 非常高 |\n| 适合场景 | 大部分业务 | 读多写少查询复杂 | 金融\u002F账本\u002F溯源 |\n\n## 最佳实践\n\n先问三问再决定：业务是否需要不可变审计？查询是否真的复杂到读写冲突？团队是否有 DDD 经验？三个 Yes 才考虑。否则传统 CRUD + 审计表往往 ROI 更高。","透彻解析两种高复杂度分布式架构模式：CQRS 读写模型分离实现查询极致性能、Event Sourcing 以事件作为唯一真相源实现全量审计与时间回溯，讨论一致性\u002F快照\u002F幂等难点与反模式。",{"id":6,"username":185,"nickname":185,"avatar":20,"cover_image":20,"bio":20,"website":20,"github":20,"avatar_source":20,"resolved_avatar_url":20,"title":20,"created_at":186},"Choyeon","2026-09-30T18:09:53.330367Z",{"id":38,"name":92,"slug":94,"description":98,"icon":100,"color":101,"cover_image":20,"created_at":102,"post_count":87},[189,194,200,206],{"id":24,"name":190,"slug":191,"color":192,"icon":20,"is_active":141,"created_at":193,"post_count":87},"FastAPI","fastapi","#009688","2026-09-30T18:09:53.669567Z",{"id":195,"name":196,"slug":197,"color":198,"icon":20,"is_active":141,"created_at":199,"post_count":87},10,"PostgreSQL","postgresql","#336791","2026-09-30T18:09:53.691803Z",{"id":201,"name":202,"slug":203,"color":204,"icon":20,"is_active":141,"created_at":205,"post_count":87},11,"Redis","redis","#dc382d","2026-09-30T18:09:53.695422Z",{"id":207,"name":208,"slug":209,"color":210,"icon":20,"is_active":141,"created_at":211,"post_count":87},13,"算法","algorithms","#ef4444","2026-09-30T18:09:53.700921Z","published","public",246,"算法,PostgreSQL,Redis,FastAPI","2026-09-14T09:09:53.733462Z","2026-10-01T04:54:47.237263Z"]