@k2works/claude-code-booster 3.2.1 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/lib/assets/docs/article/index.md +4 -1
  2. package/lib/assets/docs/article/practical-database-design/index.md +121 -0
  3. package/lib/assets/docs/article/practical-database-design/part1/chapter01.md +288 -0
  4. package/lib/assets/docs/article/practical-database-design/part1/chapter02.md +518 -0
  5. package/lib/assets/docs/article/practical-database-design/part1/chapter03.md +557 -0
  6. package/lib/assets/docs/article/practical-database-design/part2/chapter04.md +924 -0
  7. package/lib/assets/docs/article/practical-database-design/part2/chapter05.md +1627 -0
  8. package/lib/assets/docs/article/practical-database-design/part2/chapter06.md +2716 -0
  9. package/lib/assets/docs/article/practical-database-design/part2/chapter07.md +2082 -0
  10. package/lib/assets/docs/article/practical-database-design/part2/chapter08.md +2105 -0
  11. package/lib/assets/docs/article/practical-database-design/part2/chapter09.md +2031 -0
  12. package/lib/assets/docs/article/practical-database-design/part2/chapter10.md +1387 -0
  13. package/lib/assets/docs/article/practical-database-design/part2/chapter11.md +1677 -0
  14. package/lib/assets/docs/article/practical-database-design/part2/chapter12.md +1417 -0
  15. package/lib/assets/docs/article/practical-database-design/part2/chapter13.md +1434 -0
  16. package/lib/assets/docs/article/practical-database-design/part3/chapter14.md +667 -0
  17. package/lib/assets/docs/article/practical-database-design/part3/chapter15.md +1625 -0
  18. package/lib/assets/docs/article/practical-database-design/part3/chapter16.md +1915 -0
  19. package/lib/assets/docs/article/practical-database-design/part3/chapter17.md +1708 -0
  20. package/lib/assets/docs/article/practical-database-design/part3/chapter18.md +2095 -0
  21. package/lib/assets/docs/article/practical-database-design/part3/chapter19.md +1123 -0
  22. package/lib/assets/docs/article/practical-database-design/part3/chapter20.md +1031 -0
  23. package/lib/assets/docs/article/practical-database-design/part3/chapter21.md +1382 -0
  24. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter14-orm.md +991 -0
  25. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter15-orm.md +1300 -0
  26. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter16-orm.md +1166 -0
  27. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter17-orm.md +1584 -0
  28. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter18-orm.md +1183 -0
  29. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter19-orm.md +1016 -0
  30. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter20-orm.md +1753 -0
  31. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter21-orm.md +1447 -0
  32. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter22-orm.md +1878 -0
  33. package/lib/assets/docs/article/practical-database-design/part4/chapter22.md +965 -0
  34. package/lib/assets/docs/article/practical-database-design/part4/chapter23.md +2069 -0
  35. package/lib/assets/docs/article/practical-database-design/part4/chapter24.md +2439 -0
  36. package/lib/assets/docs/article/practical-database-design/part4/chapter25.md +3661 -0
  37. package/lib/assets/docs/article/practical-database-design/part4/chapter26.md +2916 -0
  38. package/lib/assets/docs/article/practical-database-design/part4/chapter27.md +3105 -0
  39. package/lib/assets/docs/article/practical-database-design/part4/chapter28.md +2697 -0
  40. package/lib/assets/docs/article/practical-database-design/part4/chapter29.md +2544 -0
  41. package/lib/assets/docs/article/practical-database-design/part4/chapter30.md +2180 -0
  42. package/lib/assets/docs/article/practical-database-design/part4/chapter31.md +1192 -0
  43. package/lib/assets/docs/article/practical-database-design/part4/chapter32.md +2101 -0
  44. package/lib/assets/docs/article/practical-database-design/part5/chapter33.md +1032 -0
  45. package/lib/assets/docs/article/practical-database-design/part5/chapter34.md +1609 -0
  46. package/lib/assets/docs/article/practical-database-design/part5/chapter35.md +1453 -0
  47. package/lib/assets/docs/article/practical-database-design/part5/chapter36.md +1292 -0
  48. package/lib/assets/docs/article/practical-database-design/part5/chapter37.md +1470 -0
  49. package/lib/assets/docs/article/practical-database-design/part5/chapter38.md +1698 -0
  50. package/lib/assets/docs/article/practical-database-design/part5/chapter39.md +2334 -0
  51. package/lib/assets/docs/article/practical-database-design/study/study2-1.md +1693 -0
  52. package/lib/assets/docs/article/practical-database-design/study/study2-2.md +1347 -0
  53. package/lib/assets/docs/article/practical-database-design/study/study2-3.md +2044 -0
  54. package/lib/assets/docs/article/practical-database-design/study/study2-4.md +2229 -0
  55. package/lib/assets/docs/article/practical-database-design/study/study2-5.md +2418 -0
  56. package/lib/assets/docs/article/practical-database-design/study/study3-1.md +2205 -0
  57. package/lib/assets/docs/article/practical-database-design/study/study3-2.md +2221 -0
  58. package/lib/assets/docs/article/practical-database-design/study/study3-3.md +2253 -0
  59. package/lib/assets/docs/article/practical-database-design/study/study3-4.md +2106 -0
  60. package/lib/assets/docs/article/practical-database-design/study/study3-5.md +2507 -0
  61. package/lib/assets/docs/article/practical-database-design/study/study4-1.md +2587 -0
  62. package/lib/assets/docs/article/practical-database-design/study/study4-2.md +2075 -0
  63. package/lib/assets/docs/article/practical-database-design/study/study4-3.md +1805 -0
  64. package/lib/assets/docs/article/practical-database-design/study/study4-4.md +1895 -0
  65. package/lib/assets/docs/article/practical-database-design/study/study4-5.md +2878 -0
  66. package/package.json +1 -1
@@ -0,0 +1,1609 @@
1
+ # 第34章:メッセージングパターン
2
+
3
+ 本章では、エンタープライズインテグレーションの基盤となるメッセージングパターンについて解説します。Gregor Hohpe と Bobby Woolf による「Enterprise Integration Patterns」で体系化されたパターンを、基幹業務システムの文脈で理解していきます。
4
+
5
+ ---
6
+
7
+ ## 34.1 メッセージングの基礎
8
+
9
+ ### メッセージングシステムの全体像
10
+
11
+ メッセージングシステムは、分散システム間の非同期通信を実現するための基盤です。送信側と受信側が直接接続する必要がなく、疎結合なシステム統合を可能にします。
12
+
13
+ ```plantuml
14
+ @startuml
15
+ title メッセージングシステムの基本構造
16
+
17
+ rectangle "送信側アプリケーション" as sender {
18
+ rectangle "ビジネスロジック" as sender_logic
19
+ rectangle "メッセージ\nエンドポイント" as sender_endpoint
20
+ }
21
+
22
+ rectangle "メッセージングシステム" as messaging {
23
+ queue "メッセージ\nチャネル" as channel
24
+ rectangle "メッセージ\nルーター" as router
25
+ rectangle "メッセージ\n変換" as transformer
26
+ }
27
+
28
+ rectangle "受信側アプリケーション" as receiver {
29
+ rectangle "メッセージ\nエンドポイント" as receiver_endpoint
30
+ rectangle "ビジネスロジック" as receiver_logic
31
+ }
32
+
33
+ sender_logic --> sender_endpoint
34
+ sender_endpoint --> channel
35
+ channel --> router
36
+ router --> transformer
37
+ transformer --> receiver_endpoint
38
+ receiver_endpoint --> receiver_logic
39
+
40
+ note bottom of messaging
41
+ ・非同期通信
42
+ ・疎結合
43
+ ・信頼性のある配信
44
+ ・スケーラビリティ
45
+ end note
46
+
47
+ @enduml
48
+ ```
49
+
50
+ ### メッセージチャネル(Message Channel)
51
+
52
+ メッセージチャネルは、送信側と受信側をつなぐ論理的なパイプです。チャネルの種類によって、メッセージの配信方法が異なります。
53
+
54
+ ```plantuml
55
+ @startuml
56
+ title メッセージチャネルの種類
57
+
58
+ rectangle "Point-to-Point Channel" as p2p {
59
+ rectangle "送信者A" as senderA
60
+ queue "キュー" as queue1
61
+ rectangle "受信者A" as receiverA
62
+
63
+ senderA --> queue1
64
+ queue1 --> receiverA
65
+ }
66
+
67
+ note right of p2p
68
+ ・1対1の通信
69
+ ・メッセージは1つの受信者のみが受信
70
+ ・負荷分散に適用可能
71
+
72
+ 例:受注処理キュー
73
+ end note
74
+
75
+ rectangle "Publish-Subscribe Channel" as pubsub {
76
+ rectangle "発行者" as publisher
77
+ collections "トピック" as topic
78
+ rectangle "購読者A" as subA
79
+ rectangle "購読者B" as subB
80
+ rectangle "購読者C" as subC
81
+
82
+ publisher --> topic
83
+ topic --> subA
84
+ topic --> subB
85
+ topic --> subC
86
+ }
87
+
88
+ note right of pubsub
89
+ ・1対多の通信
90
+ ・すべての購読者がメッセージを受信
91
+ ・イベント通知に最適
92
+
93
+ 例:売上イベントの通知
94
+ end note
95
+
96
+ @enduml
97
+ ```
98
+
99
+ #### 基幹業務システムにおけるチャネル設計
100
+
101
+ ```plantuml
102
+ @startuml
103
+ title 基幹業務システムのメッセージチャネル設計
104
+
105
+ package "販売管理" as sales {
106
+ rectangle "受注サービス" as order_svc
107
+ rectangle "出荷サービス" as ship_svc
108
+ rectangle "売上サービス" as sales_svc
109
+ }
110
+
111
+ package "メッセージチャネル" as channels {
112
+ queue "受注確定キュー" as order_queue
113
+ collections "売上イベント\nトピック" as sales_topic
114
+ queue "仕訳生成キュー" as journal_queue
115
+ }
116
+
117
+ package "会計" as accounting {
118
+ rectangle "自動仕訳\nサービス" as auto_journal
119
+ }
120
+
121
+ package "生産管理" as production {
122
+ rectangle "生産計画\nサービス" as prod_plan
123
+ }
124
+
125
+ package "分析" as analytics {
126
+ rectangle "売上分析\nサービス" as sales_analytics
127
+ }
128
+
129
+ order_svc --> order_queue : 受注確定
130
+ order_queue --> ship_svc : 出荷指示作成
131
+ sales_svc --> sales_topic : 売上計上イベント
132
+ sales_topic --> auto_journal : 仕訳生成
133
+ sales_topic --> prod_plan : 需要情報更新
134
+ sales_topic --> sales_analytics : 分析データ収集
135
+
136
+ @enduml
137
+ ```
138
+
139
+ ### メッセージ(Message)の構造
140
+
141
+ メッセージは、ヘッダーとボディで構成されます。ヘッダーにはルーティングや処理に必要なメタデータを、ボディにはビジネスデータを含めます。
142
+
143
+ ```plantuml
144
+ @startuml
145
+ title メッセージの構造
146
+
147
+ class "Message" as msg {
148
+ +Header header
149
+ +Body body
150
+ }
151
+
152
+ class "Header" as header {
153
+ +String messageId
154
+ +String correlationId
155
+ +String replyTo
156
+ +Date timestamp
157
+ +String messageType
158
+ +Map<String, Object> properties
159
+ }
160
+
161
+ class "Body" as body {
162
+ +Object payload
163
+ +String contentType
164
+ +String encoding
165
+ }
166
+
167
+ msg --> header
168
+ msg --> body
169
+
170
+ note right of header
171
+ 【メタデータ】
172
+ ・messageId: 一意識別子
173
+ ・correlationId: 関連メッセージの追跡
174
+ ・replyTo: 返信先チャネル
175
+ ・timestamp: 送信日時
176
+ ・messageType: メッセージ種別
177
+ end note
178
+
179
+ note right of body
180
+ 【ビジネスデータ】
181
+ ・payload: 実際のデータ
182
+ ・contentType: JSON/XML等
183
+ ・encoding: UTF-8等
184
+ end note
185
+
186
+ @enduml
187
+ ```
188
+
189
+ #### 売上イベントメッセージの例
190
+
191
+ ```plantuml
192
+ @startuml
193
+ title 売上イベントメッセージの例
194
+
195
+ object "売上イベントメッセージ" as sales_event {
196
+ <b>Header</b>
197
+ messageId = "MSG-20240115-001"
198
+ correlationId = "ORD-2024-00123"
199
+ messageType = "SalesCompleted"
200
+ timestamp = "2024-01-15T10:30:00Z"
201
+ source = "sales-service"
202
+ --
203
+ <b>Body</b>
204
+ eventType = "売上計上"
205
+ salesId = "SLS-2024-00456"
206
+ orderNumber = "ORD-2024-00123"
207
+ customerId = "CUS-001"
208
+ salesDate = "2024-01-15"
209
+ totalAmount = 108000
210
+ taxAmount = 8000
211
+ lines = [...]
212
+ }
213
+
214
+ @enduml
215
+ ```
216
+
217
+ <details>
218
+ <summary>Java 実装例</summary>
219
+
220
+ ```java
221
+ // メッセージヘッダー
222
+ public record MessageHeader(
223
+ String messageId,
224
+ String correlationId,
225
+ String replyTo,
226
+ Instant timestamp,
227
+ String messageType,
228
+ String source,
229
+ Map<String, Object> properties
230
+ ) {
231
+ public static MessageHeader create(String messageType, String source) {
232
+ return new MessageHeader(
233
+ UUID.randomUUID().toString(),
234
+ null,
235
+ null,
236
+ Instant.now(),
237
+ messageType,
238
+ source,
239
+ new HashMap<>()
240
+ );
241
+ }
242
+
243
+ public MessageHeader withCorrelationId(String correlationId) {
244
+ return new MessageHeader(
245
+ messageId, correlationId, replyTo, timestamp,
246
+ messageType, source, properties
247
+ );
248
+ }
249
+ }
250
+
251
+ // メッセージ本体
252
+ public record Message<T>(
253
+ MessageHeader header,
254
+ T payload
255
+ ) {
256
+ public static <T> Message<T> of(String messageType, String source, T payload) {
257
+ return new Message<>(
258
+ MessageHeader.create(messageType, source),
259
+ payload
260
+ );
261
+ }
262
+ }
263
+
264
+ // 売上イベント
265
+ public record SalesCompletedEvent(
266
+ String salesId,
267
+ String orderNumber,
268
+ String customerId,
269
+ LocalDate salesDate,
270
+ BigDecimal totalAmount,
271
+ BigDecimal taxAmount,
272
+ List<SalesLineEvent> lines
273
+ ) {}
274
+
275
+ // 使用例
276
+ Message<SalesCompletedEvent> message = Message.of(
277
+ "SalesCompleted",
278
+ "sales-service",
279
+ new SalesCompletedEvent(
280
+ "SLS-2024-00456",
281
+ "ORD-2024-00123",
282
+ "CUS-001",
283
+ LocalDate.of(2024, 1, 15),
284
+ new BigDecimal("108000"),
285
+ new BigDecimal("8000"),
286
+ lines
287
+ )
288
+ ).header().withCorrelationId("ORD-2024-00123");
289
+ ```
290
+
291
+ </details>
292
+
293
+ ### パイプとフィルター(Pipes and Filters)
294
+
295
+ パイプとフィルターパターンは、複雑な処理を小さな独立したステップ(フィルター)に分解し、パイプでつなげて処理する方式です。
296
+
297
+ ```plantuml
298
+ @startuml
299
+ title パイプとフィルターパターン
300
+
301
+ rectangle "入力" as input
302
+ rectangle "フィルターA\n(検証)" as filterA
303
+ rectangle "フィルターB\n(変換)" as filterB
304
+ rectangle "フィルターC\n(エンリッチ)" as filterC
305
+ rectangle "フィルターD\n(ルーティング)" as filterD
306
+ rectangle "出力" as output
307
+
308
+ input --> filterA : パイプ
309
+ filterA --> filterB : パイプ
310
+ filterB --> filterC : パイプ
311
+ filterC --> filterD : パイプ
312
+ filterD --> output : パイプ
313
+
314
+ note bottom of filterA
315
+ 各フィルターは
316
+ ・独立して動作
317
+ ・単一責任
318
+ ・再利用可能
319
+ ・テスト容易
320
+ end note
321
+
322
+ @enduml
323
+ ```
324
+
325
+ #### 売上仕訳生成パイプライン
326
+
327
+ ```plantuml
328
+ @startuml
329
+ title 売上から仕訳生成へのパイプライン
330
+
331
+ rectangle "売上\nイベント" as input
332
+
333
+ rectangle "バリデーション\nフィルター" as validate {
334
+ note right
335
+ ・必須項目チェック
336
+ ・金額整合性確認
337
+ end note
338
+ }
339
+
340
+ rectangle "仕訳パターン\n判定フィルター" as pattern {
341
+ note right
342
+ ・商品グループ判定
343
+ ・顧客グループ判定
344
+ ・科目決定
345
+ end note
346
+ }
347
+
348
+ rectangle "仕訳明細\n生成フィルター" as generate {
349
+ note right
350
+ ・借方明細生成
351
+ ・貸方明細生成
352
+ ・消費税計算
353
+ end note
354
+ }
355
+
356
+ rectangle "貸借一致\n検証フィルター" as balance {
357
+ note right
358
+ ・借方合計 = 貸方合計
359
+ ・検証エラー処理
360
+ end note
361
+ }
362
+
363
+ rectangle "仕訳\nイベント" as output
364
+
365
+ input --> validate
366
+ validate --> pattern
367
+ pattern --> generate
368
+ generate --> balance
369
+ balance --> output
370
+
371
+ @enduml
372
+ ```
373
+
374
+ <details>
375
+ <summary>Java 実装例</summary>
376
+
377
+ ```java
378
+ // フィルターインターフェース
379
+ @FunctionalInterface
380
+ public interface Filter<T> {
381
+ T process(T input) throws FilterException;
382
+
383
+ default Filter<T> andThen(Filter<T> next) {
384
+ return input -> next.process(this.process(input));
385
+ }
386
+ }
387
+
388
+ // パイプラインビルダー
389
+ public class Pipeline<T> {
390
+ private final List<Filter<T>> filters = new ArrayList<>();
391
+
392
+ public Pipeline<T> addFilter(Filter<T> filter) {
393
+ filters.add(filter);
394
+ return this;
395
+ }
396
+
397
+ public T execute(T input) throws FilterException {
398
+ T result = input;
399
+ for (Filter<T> filter : filters) {
400
+ result = filter.process(result);
401
+ }
402
+ return result;
403
+ }
404
+ }
405
+
406
+ // 売上仕訳変換コンテキスト
407
+ public class SalesJournalContext {
408
+ private SalesCompletedEvent salesEvent;
409
+ private JournalPattern pattern;
410
+ private List<JournalLine> journalLines;
411
+ private JournalEntry journalEntry;
412
+ private List<String> errors = new ArrayList<>();
413
+
414
+ // getter/setter
415
+ }
416
+
417
+ // バリデーションフィルター
418
+ public class ValidationFilter implements Filter<SalesJournalContext> {
419
+ @Override
420
+ public SalesJournalContext process(SalesJournalContext ctx) {
421
+ SalesCompletedEvent event = ctx.getSalesEvent();
422
+
423
+ if (event.salesId() == null || event.salesId().isBlank()) {
424
+ ctx.getErrors().add("売上IDは必須です");
425
+ }
426
+ if (event.totalAmount().compareTo(BigDecimal.ZERO) <= 0) {
427
+ ctx.getErrors().add("売上金額は正の値である必要があります");
428
+ }
429
+
430
+ if (!ctx.getErrors().isEmpty()) {
431
+ throw new ValidationException(ctx.getErrors());
432
+ }
433
+ return ctx;
434
+ }
435
+ }
436
+
437
+ // 仕訳パターン判定フィルター
438
+ public class PatternDeterminationFilter implements Filter<SalesJournalContext> {
439
+ private final JournalPatternRepository patternRepository;
440
+
441
+ @Override
442
+ public SalesJournalContext process(SalesJournalContext ctx) {
443
+ JournalPattern pattern = patternRepository.findByProductAndCustomerGroup(
444
+ ctx.getSalesEvent().productGroup(),
445
+ ctx.getSalesEvent().customerGroup()
446
+ ).orElseThrow(() -> new PatternNotFoundException("仕訳パターンが見つかりません"));
447
+
448
+ ctx.setPattern(pattern);
449
+ return ctx;
450
+ }
451
+ }
452
+
453
+ // パイプラインの構築と実行
454
+ public class SalesJournalPipeline {
455
+ private final Pipeline<SalesJournalContext> pipeline;
456
+
457
+ public SalesJournalPipeline(
458
+ ValidationFilter validationFilter,
459
+ PatternDeterminationFilter patternFilter,
460
+ JournalLineGenerationFilter generationFilter,
461
+ BalanceValidationFilter balanceFilter) {
462
+
463
+ this.pipeline = new Pipeline<SalesJournalContext>()
464
+ .addFilter(validationFilter)
465
+ .addFilter(patternFilter)
466
+ .addFilter(generationFilter)
467
+ .addFilter(balanceFilter);
468
+ }
469
+
470
+ public JournalEntry process(SalesCompletedEvent event) {
471
+ SalesJournalContext ctx = new SalesJournalContext();
472
+ ctx.setSalesEvent(event);
473
+
474
+ SalesJournalContext result = pipeline.execute(ctx);
475
+ return result.getJournalEntry();
476
+ }
477
+ }
478
+ ```
479
+
480
+ </details>
481
+
482
+ ---
483
+
484
+ ## 34.2 メッセージルーティング
485
+
486
+ メッセージルーティングは、メッセージの内容や属性に基づいて、適切な宛先にメッセージを振り分ける機能です。
487
+
488
+ ### Content-Based Router(内容ベースルーター)
489
+
490
+ メッセージの内容を検査し、条件に基づいて異なるチャネルにルーティングします。
491
+
492
+ ```plantuml
493
+ @startuml
494
+ title Content-Based Router パターン
495
+
496
+ rectangle "入力\nチャネル" as input
497
+
498
+ rectangle "Content-Based\nRouter" as router
499
+
500
+ queue "売上仕訳\nチャネル" as sales_channel
501
+ queue "仕入仕訳\nチャネル" as purchase_channel
502
+ queue "経費仕訳\nチャネル" as expense_channel
503
+
504
+ input --> router
505
+
506
+ router --> sales_channel : 伝票区分 = "売上"
507
+ router --> purchase_channel : 伝票区分 = "仕入"
508
+ router --> expense_channel : 伝票区分 = "経費"
509
+
510
+ note right of router
511
+ メッセージ内容を検査し
512
+ 条件に基づいて
513
+ 適切なチャネルへ振り分け
514
+ end note
515
+
516
+ @enduml
517
+ ```
518
+
519
+ #### 基幹業務システムでの適用例
520
+
521
+ ```plantuml
522
+ @startuml
523
+ title 取引イベントのルーティング
524
+
525
+ rectangle "取引イベント" as input
526
+
527
+ rectangle "取引種別\nルーター" as router
528
+
529
+ package "販売系処理" as sales_pkg {
530
+ queue "受注処理" as order_q
531
+ queue "出荷処理" as ship_q
532
+ queue "売上処理" as sales_q
533
+ }
534
+
535
+ package "調達系処理" as purchase_pkg {
536
+ queue "発注処理" as po_q
537
+ queue "入荷処理" as receipt_q
538
+ queue "仕入処理" as purchase_q
539
+ }
540
+
541
+ package "在庫系処理" as inv_pkg {
542
+ queue "入庫処理" as stock_in_q
543
+ queue "出庫処理" as stock_out_q
544
+ queue "棚卸処理" as inventory_q
545
+ }
546
+
547
+ input --> router
548
+
549
+ router --> order_q : type = ORDER
550
+ router --> ship_q : type = SHIPMENT
551
+ router --> sales_q : type = SALES
552
+ router --> po_q : type = PURCHASE_ORDER
553
+ router --> receipt_q : type = RECEIPT
554
+ router --> purchase_q : type = PURCHASE
555
+ router --> stock_in_q : type = STOCK_IN
556
+ router --> stock_out_q : type = STOCK_OUT
557
+ router --> inventory_q : type = INVENTORY
558
+
559
+ @enduml
560
+ ```
561
+
562
+ <details>
563
+ <summary>Java 実装例</summary>
564
+
565
+ ```java
566
+ // ルーティング条件
567
+ public interface RoutingCondition<T> {
568
+ boolean matches(T message);
569
+ String getDestination();
570
+ }
571
+
572
+ // Content-Based Router
573
+ public class ContentBasedRouter<T> {
574
+ private final List<RoutingCondition<T>> conditions = new ArrayList<>();
575
+ private String defaultDestination;
576
+
577
+ public ContentBasedRouter<T> when(Predicate<T> predicate, String destination) {
578
+ conditions.add(new RoutingCondition<>() {
579
+ @Override
580
+ public boolean matches(T message) {
581
+ return predicate.test(message);
582
+ }
583
+ @Override
584
+ public String getDestination() {
585
+ return destination;
586
+ }
587
+ });
588
+ return this;
589
+ }
590
+
591
+ public ContentBasedRouter<T> otherwise(String destination) {
592
+ this.defaultDestination = destination;
593
+ return this;
594
+ }
595
+
596
+ public String route(T message) {
597
+ return conditions.stream()
598
+ .filter(c -> c.matches(message))
599
+ .findFirst()
600
+ .map(RoutingCondition::getDestination)
601
+ .orElse(defaultDestination);
602
+ }
603
+ }
604
+
605
+ // 取引イベントルーター
606
+ public class TransactionEventRouter {
607
+ private final ContentBasedRouter<TransactionEvent> router;
608
+ private final MessageSender messageSender;
609
+
610
+ public TransactionEventRouter(MessageSender messageSender) {
611
+ this.messageSender = messageSender;
612
+ this.router = new ContentBasedRouter<TransactionEvent>()
613
+ .when(e -> e.type() == TransactionType.ORDER, "order-queue")
614
+ .when(e -> e.type() == TransactionType.SHIPMENT, "shipment-queue")
615
+ .when(e -> e.type() == TransactionType.SALES, "sales-queue")
616
+ .when(e -> e.type() == TransactionType.PURCHASE_ORDER, "po-queue")
617
+ .when(e -> e.type() == TransactionType.RECEIPT, "receipt-queue")
618
+ .when(e -> e.type() == TransactionType.PURCHASE, "purchase-queue")
619
+ .otherwise("dead-letter-queue");
620
+ }
621
+
622
+ public void route(TransactionEvent event) {
623
+ String destination = router.route(event);
624
+ messageSender.send(destination, event);
625
+ }
626
+ }
627
+ ```
628
+
629
+ </details>
630
+
631
+ ### Message Filter(メッセージフィルター)
632
+
633
+ 条件に合致するメッセージのみを通過させ、それ以外は破棄または別のチャネルに送ります。
634
+
635
+ ```plantuml
636
+ @startuml
637
+ title Message Filter パターン
638
+
639
+ rectangle "入力\nチャネル" as input
640
+
641
+ rectangle "Message\nFilter" as filter
642
+
643
+ rectangle "出力\nチャネル" as output
644
+
645
+ rectangle "破棄/DLQ" as discard
646
+
647
+ input --> filter
648
+ filter --> output : 条件に合致
649
+ filter --> discard : 条件に不合致
650
+
651
+ note right of filter
652
+ 【フィルター条件の例】
653
+ ・金額が閾値以上
654
+ ・特定の顧客のみ
655
+ ・特定期間のデータのみ
656
+ ・重複メッセージの排除
657
+ end note
658
+
659
+ @enduml
660
+ ```
661
+
662
+ #### 高額取引フィルターの例
663
+
664
+ ```plantuml
665
+ @startuml
666
+ title 高額取引アラートフィルター
667
+
668
+ rectangle "売上イベント" as input
669
+
670
+ rectangle "高額取引\nフィルター" as filter {
671
+ note right
672
+ 条件:金額 >= 100万円
673
+ end note
674
+ }
675
+
676
+ rectangle "通常処理\nチャネル" as normal
677
+ rectangle "高額取引\nアラートチャネル" as alert
678
+
679
+ input --> filter
680
+ filter --> normal : 金額 < 100万円
681
+ filter --> alert : 金額 >= 100万円
682
+
683
+ @enduml
684
+ ```
685
+
686
+ ### Splitter / Aggregator(分割 / 集約)
687
+
688
+ 大きなメッセージを複数の小さなメッセージに分割し、処理後に再び集約するパターンです。
689
+
690
+ ```plantuml
691
+ @startuml
692
+ title Splitter / Aggregator パターン
693
+
694
+ rectangle "受注\nメッセージ" as input
695
+ note right of input
696
+ 受注ヘッダー
697
+ + 明細10件
698
+ end note
699
+
700
+ rectangle "Splitter\n(分割)" as splitter
701
+
702
+ rectangle "明細1" as line1
703
+ rectangle "明細2" as line2
704
+ rectangle "..." as dots
705
+ rectangle "明細10" as line10
706
+
707
+ rectangle "在庫引当\n処理" as process
708
+
709
+ rectangle "Aggregator\n(集約)" as aggregator
710
+
711
+ rectangle "引当結果\nメッセージ" as output
712
+ note right of output
713
+ 受注ヘッダー
714
+ + 引当結果10件
715
+ end note
716
+
717
+ input --> splitter
718
+ splitter --> line1
719
+ splitter --> line2
720
+ splitter --> dots
721
+ splitter --> line10
722
+
723
+ line1 --> process
724
+ line2 --> process
725
+ dots --> process
726
+ line10 --> process
727
+
728
+ process --> aggregator
729
+ aggregator --> output
730
+
731
+ note bottom of splitter
732
+ 【Splitter】
733
+ 複合メッセージを
734
+ 個別メッセージに分割
735
+ end note
736
+
737
+ note bottom of aggregator
738
+ 【Aggregator】
739
+ 関連メッセージを
740
+ 1つに集約
741
+ ・correlationIdで関連付け
742
+ ・完了条件の判定
743
+ end note
744
+
745
+ @enduml
746
+ ```
747
+
748
+ #### 基幹業務システムでの適用例
749
+
750
+ ```plantuml
751
+ @startuml
752
+ title 一括仕訳処理のSplitter/Aggregator
753
+
754
+ rectangle "月次締め\nリクエスト" as input
755
+
756
+ rectangle "売上データ\n取得" as fetch
757
+
758
+ rectangle "Splitter" as splitter
759
+
760
+ rectangle "仕訳変換\n処理" as transform
761
+
762
+ rectangle "Aggregator" as aggregator
763
+
764
+ rectangle "仕訳バッチ\n登録" as register
765
+
766
+ rectangle "月次締め\n完了" as output
767
+
768
+ input --> fetch : 期間指定
769
+ fetch --> splitter : 売上リスト
770
+
771
+ splitter --> transform : 売上1
772
+ splitter --> transform : 売上2
773
+ splitter --> transform : 売上N
774
+
775
+ transform --> aggregator : 仕訳1
776
+ transform --> aggregator : 仕訳2
777
+ transform --> aggregator : 仕訳N
778
+
779
+ aggregator --> register : 仕訳リスト
780
+ register --> output
781
+
782
+ note right of aggregator
783
+ 【集約条件】
784
+ ・すべての売上が処理完了
785
+ ・タイムアウト時は部分集約
786
+ ・エラー時は補償処理
787
+ end note
788
+
789
+ @enduml
790
+ ```
791
+
792
+ <details>
793
+ <summary>Java 実装例</summary>
794
+
795
+ ```java
796
+ // Splitter
797
+ public class OrderLineSplitter {
798
+ public List<Message<OrderLineEvent>> split(Message<OrderEvent> orderMessage) {
799
+ OrderEvent order = orderMessage.payload();
800
+ return order.lines().stream()
801
+ .map(line -> {
802
+ OrderLineEvent lineEvent = new OrderLineEvent(
803
+ order.orderId(),
804
+ line.lineNumber(),
805
+ line.productId(),
806
+ line.quantity(),
807
+ line.unitPrice()
808
+ );
809
+ return Message.of("OrderLine", "splitter", lineEvent)
810
+ .withCorrelationId(order.orderId());
811
+ })
812
+ .toList();
813
+ }
814
+ }
815
+
816
+ // Aggregator
817
+ public class AllocationResultAggregator {
818
+ private final Map<String, AggregationState> states = new ConcurrentHashMap<>();
819
+
820
+ public record AggregationState(
821
+ String correlationId,
822
+ int expectedCount,
823
+ List<AllocationResult> results,
824
+ Instant startTime
825
+ ) {}
826
+
827
+ public void aggregate(Message<AllocationResult> message) {
828
+ String correlationId = message.header().correlationId();
829
+ AllocationResult result = message.payload();
830
+
831
+ states.compute(correlationId, (id, state) -> {
832
+ if (state == null) {
833
+ // 初期状態
834
+ state = new AggregationState(
835
+ id,
836
+ getExpectedCount(id),
837
+ new ArrayList<>(),
838
+ Instant.now()
839
+ );
840
+ }
841
+ state.results().add(result);
842
+ return state;
843
+ });
844
+
845
+ checkCompletion(correlationId);
846
+ }
847
+
848
+ private void checkCompletion(String correlationId) {
849
+ AggregationState state = states.get(correlationId);
850
+ if (state == null) return;
851
+
852
+ // 完了条件:すべての結果が揃った
853
+ if (state.results().size() >= state.expectedCount()) {
854
+ AggregatedAllocationResult aggregated = new AggregatedAllocationResult(
855
+ correlationId,
856
+ state.results()
857
+ );
858
+ publishAggregatedResult(aggregated);
859
+ states.remove(correlationId);
860
+ }
861
+ // タイムアウトチェック
862
+ else if (Duration.between(state.startTime(), Instant.now()).toMinutes() > 5) {
863
+ handleTimeout(state);
864
+ }
865
+ }
866
+ }
867
+ ```
868
+
869
+ </details>
870
+
871
+ ### Resequencer(再順序付け)
872
+
873
+ 順序が乱れて到着したメッセージを、正しい順序に並べ替えてから処理します。
874
+
875
+ ```plantuml
876
+ @startuml
877
+ title Resequencer パターン
878
+
879
+ rectangle "入力チャネル" as input
880
+
881
+ rectangle "Resequencer" as reseq {
882
+ rectangle "バッファ" as buffer
883
+ rectangle "順序判定" as order
884
+ }
885
+
886
+ rectangle "出力チャネル" as output
887
+
888
+ input --> reseq : メッセージ(3)
889
+ input --> reseq : メッセージ(1)
890
+ input --> reseq : メッセージ(5)
891
+ input --> reseq : メッセージ(2)
892
+ input --> reseq : メッセージ(4)
893
+
894
+ reseq --> output : メッセージ(1)
895
+ reseq --> output : メッセージ(2)
896
+ reseq --> output : メッセージ(3)
897
+ reseq --> output : メッセージ(4)
898
+ reseq --> output : メッセージ(5)
899
+
900
+ note right of reseq
901
+ 【Resequencer の動作】
902
+ ・シーケンス番号でバッファリング
903
+ ・欠番の待機
904
+ ・タイムアウト処理
905
+
906
+ 【適用例】
907
+ ・在庫移動の順序保証
908
+ ・仕訳の時系列順序
909
+ end note
910
+
911
+ @enduml
912
+ ```
913
+
914
+ ---
915
+
916
+ ## 34.3 メッセージ変換
917
+
918
+ 異なるシステム間でデータをやり取りする際、データ形式やスキーマの変換が必要になります。
919
+
920
+ ### Message Translator(メッセージ変換)
921
+
922
+ あるシステムのメッセージ形式を、別のシステムが理解できる形式に変換します。
923
+
924
+ ```plantuml
925
+ @startuml
926
+ title Message Translator パターン
927
+
928
+ rectangle "送信側\nシステム" as sender
929
+
930
+ rectangle "Message\nTranslator" as translator
931
+
932
+ rectangle "受信側\nシステム" as receiver
933
+
934
+ sender --> translator : フォーマットA
935
+ translator --> receiver : フォーマットB
936
+
937
+ note bottom of translator
938
+ 【変換内容】
939
+ ・データ形式(JSON ↔ XML)
940
+ ・スキーマ変換
941
+ ・フィールド名マッピング
942
+ ・値の変換(コード変換等)
943
+ ・データ型変換
944
+ end note
945
+
946
+ @enduml
947
+ ```
948
+
949
+ #### 売上から仕訳への変換例
950
+
951
+ ```plantuml
952
+ @startuml
953
+ title 売上イベントから仕訳への変換
954
+
955
+ class "売上イベント" as sales {
956
+ +salesId: String
957
+ +salesDate: Date
958
+ +customerId: String
959
+ +totalAmount: Decimal
960
+ +taxAmount: Decimal
961
+ +lines: List<SalesLine>
962
+ }
963
+
964
+ class "SalesLine" as sales_line {
965
+ +productId: String
966
+ +quantity: int
967
+ +unitPrice: Decimal
968
+ +amount: Decimal
969
+ }
970
+
971
+ class "仕訳伝票" as journal {
972
+ +journalId: String
973
+ +journalDate: Date
974
+ +journalType: String
975
+ +entries: List<JournalEntry>
976
+ }
977
+
978
+ class "仕訳明細" as journal_entry {
979
+ +debitCredit: String
980
+ +accountCode: String
981
+ +amount: Decimal
982
+ +description: String
983
+ }
984
+
985
+ class "SalesJournalTranslator" as translator {
986
+ +translate(SalesEvent): JournalEntry
987
+ -determineAccounts()
988
+ -calculateTax()
989
+ -createDebitEntries()
990
+ -createCreditEntries()
991
+ }
992
+
993
+ sales "1" -- "*" sales_line
994
+ journal "1" -- "*" journal_entry
995
+ translator ..> sales : 入力
996
+ translator ..> journal : 出力
997
+
998
+ @enduml
999
+ ```
1000
+
1001
+ <details>
1002
+ <summary>Java 実装例</summary>
1003
+
1004
+ ```java
1005
+ // メッセージ変換インターフェース
1006
+ public interface MessageTranslator<S, T> {
1007
+ T translate(S source);
1008
+ }
1009
+
1010
+ // 売上から仕訳への変換
1011
+ @Component
1012
+ public class SalesJournalTranslator
1013
+ implements MessageTranslator<SalesCompletedEvent, JournalEntryCommand> {
1014
+
1015
+ private final JournalPatternRepository patternRepository;
1016
+ private final AccountRepository accountRepository;
1017
+
1018
+ @Override
1019
+ public JournalEntryCommand translate(SalesCompletedEvent sales) {
1020
+ // 仕訳パターン取得
1021
+ JournalPattern pattern = patternRepository.findBySalesType(
1022
+ sales.salesType()
1023
+ ).orElseThrow();
1024
+
1025
+ // 借方明細(売掛金)
1026
+ List<JournalLineCommand> debitLines = List.of(
1027
+ new JournalLineCommand(
1028
+ DebitCredit.DEBIT,
1029
+ pattern.debitAccountCode(),
1030
+ sales.totalAmount(),
1031
+ "売掛金計上 " + sales.customerName()
1032
+ )
1033
+ );
1034
+
1035
+ // 貸方明細(売上 + 仮受消費税)
1036
+ List<JournalLineCommand> creditLines = new ArrayList<>();
1037
+ creditLines.add(new JournalLineCommand(
1038
+ DebitCredit.CREDIT,
1039
+ pattern.creditAccountCode(),
1040
+ sales.totalAmount().subtract(sales.taxAmount()),
1041
+ "売上計上 " + sales.salesId()
1042
+ ));
1043
+ creditLines.add(new JournalLineCommand(
1044
+ DebitCredit.CREDIT,
1045
+ pattern.taxAccountCode(),
1046
+ sales.taxAmount(),
1047
+ "仮受消費税"
1048
+ ));
1049
+
1050
+ // 仕訳伝票作成
1051
+ return new JournalEntryCommand(
1052
+ generateJournalId(),
1053
+ sales.salesDate(),
1054
+ JournalType.SALES,
1055
+ sales.salesId(),
1056
+ Stream.concat(debitLines.stream(), creditLines.stream()).toList()
1057
+ );
1058
+ }
1059
+ }
1060
+ ```
1061
+
1062
+ </details>
1063
+
1064
+ ### Envelope Wrapper(エンベロープラッパー)
1065
+
1066
+ メッセージに追加のメタデータを付与するためのラッパーです。
1067
+
1068
+ ```plantuml
1069
+ @startuml
1070
+ title Envelope Wrapper パターン
1071
+
1072
+ rectangle "アプリケーション\nデータ" as app_data
1073
+
1074
+ rectangle "Envelope\nWrapper" as wrapper
1075
+
1076
+ rectangle "エンベロープ付き\nメッセージ" as envelope {
1077
+ rectangle "ルーティング情報" as routing
1078
+ rectangle "セキュリティ情報" as security
1079
+ rectangle "トレース情報" as trace
1080
+ rectangle "アプリケーション\nデータ" as data
1081
+ }
1082
+
1083
+ app_data --> wrapper
1084
+ wrapper --> envelope
1085
+
1086
+ note right of envelope
1087
+ 【エンベロープの内容】
1088
+ ・送信元/宛先情報
1089
+ ・認証トークン
1090
+ ・トレースID(分散トレーシング)
1091
+ ・タイムスタンプ
1092
+ ・バージョン情報
1093
+ end note
1094
+
1095
+ @enduml
1096
+ ```
1097
+
1098
+ <details>
1099
+ <summary>Java 実装例</summary>
1100
+
1101
+ ```java
1102
+ // エンベロープ
1103
+ public record MessageEnvelope<T>(
1104
+ RoutingInfo routing,
1105
+ SecurityInfo security,
1106
+ TraceInfo trace,
1107
+ T payload
1108
+ ) {
1109
+ public record RoutingInfo(
1110
+ String source,
1111
+ String destination,
1112
+ String replyTo,
1113
+ int priority
1114
+ ) {}
1115
+
1116
+ public record SecurityInfo(
1117
+ String authToken,
1118
+ String userId,
1119
+ List<String> roles
1120
+ ) {}
1121
+
1122
+ public record TraceInfo(
1123
+ String traceId,
1124
+ String spanId,
1125
+ String parentSpanId,
1126
+ Instant timestamp
1127
+ ) {}
1128
+
1129
+ public static <T> MessageEnvelope<T> wrap(
1130
+ T payload,
1131
+ String source,
1132
+ String destination) {
1133
+ return new MessageEnvelope<>(
1134
+ new RoutingInfo(source, destination, null, 0),
1135
+ null,
1136
+ new TraceInfo(
1137
+ UUID.randomUUID().toString(),
1138
+ UUID.randomUUID().toString(),
1139
+ null,
1140
+ Instant.now()
1141
+ ),
1142
+ payload
1143
+ );
1144
+ }
1145
+ }
1146
+
1147
+ // Envelope Wrapper
1148
+ @Component
1149
+ public class EnvelopeWrapper {
1150
+ private final SecurityContext securityContext;
1151
+ private final TraceContext traceContext;
1152
+
1153
+ public <T> MessageEnvelope<T> wrap(T payload, String destination) {
1154
+ return new MessageEnvelope<>(
1155
+ new RoutingInfo(
1156
+ "current-service",
1157
+ destination,
1158
+ null,
1159
+ 0
1160
+ ),
1161
+ new SecurityInfo(
1162
+ securityContext.getToken(),
1163
+ securityContext.getUserId(),
1164
+ securityContext.getRoles()
1165
+ ),
1166
+ new TraceInfo(
1167
+ traceContext.getTraceId(),
1168
+ traceContext.newSpanId(),
1169
+ traceContext.getCurrentSpanId(),
1170
+ Instant.now()
1171
+ ),
1172
+ payload
1173
+ );
1174
+ }
1175
+
1176
+ public <T> T unwrap(MessageEnvelope<T> envelope) {
1177
+ // セキュリティ検証
1178
+ validateSecurity(envelope.security());
1179
+ // トレース情報の伝播
1180
+ propagateTrace(envelope.trace());
1181
+ return envelope.payload();
1182
+ }
1183
+ }
1184
+ ```
1185
+
1186
+ </details>
1187
+
1188
+ ### Content Enricher(コンテンツエンリッチャー)
1189
+
1190
+ メッセージに不足している情報を外部ソースから取得して追加します。
1191
+
1192
+ ```plantuml
1193
+ @startuml
1194
+ title Content Enricher パターン
1195
+
1196
+ rectangle "入力メッセージ" as input
1197
+ note right of input
1198
+ customerId: "CUS-001"
1199
+ productId: "PRD-001"
1200
+ quantity: 10
1201
+ end note
1202
+
1203
+ rectangle "Content\nEnricher" as enricher
1204
+
1205
+ database "顧客マスタ" as customer_db
1206
+ database "商品マスタ" as product_db
1207
+
1208
+ rectangle "出力メッセージ" as output
1209
+ note right of output
1210
+ customerId: "CUS-001"
1211
+ <b>customerName: "株式会社A"</b>
1212
+ <b>creditLimit: 1000000</b>
1213
+ productId: "PRD-001"
1214
+ <b>productName: "商品A"</b>
1215
+ <b>unitPrice: 1000</b>
1216
+ quantity: 10
1217
+ <b>amount: 10000</b>
1218
+ end note
1219
+
1220
+ input --> enricher
1221
+ enricher --> customer_db : 顧客情報取得
1222
+ enricher --> product_db : 商品情報取得
1223
+ enricher --> output
1224
+
1225
+ @enduml
1226
+ ```
1227
+
1228
+ #### 受注エンリッチメントの例
1229
+
1230
+ ```plantuml
1231
+ @startuml
1232
+ title 受注データのエンリッチメント
1233
+
1234
+ rectangle "受注イベント\n(基本情報のみ)" as input
1235
+
1236
+ rectangle "Customer\nEnricher" as cust_enricher
1237
+ rectangle "Product\nEnricher" as prod_enricher
1238
+ rectangle "Price\nEnricher" as price_enricher
1239
+ rectangle "Inventory\nEnricher" as inv_enricher
1240
+
1241
+ database "顧客マスタ" as cust_db
1242
+ database "商品マスタ" as prod_db
1243
+ database "単価マスタ" as price_db
1244
+ database "在庫情報" as inv_db
1245
+
1246
+ rectangle "受注イベント\n(完全情報)" as output
1247
+
1248
+ input --> cust_enricher
1249
+ cust_enricher --> cust_db
1250
+ cust_enricher --> prod_enricher
1251
+ prod_enricher --> prod_db
1252
+ prod_enricher --> price_enricher
1253
+ price_enricher --> price_db
1254
+ price_enricher --> inv_enricher
1255
+ inv_enricher --> inv_db
1256
+ inv_enricher --> output
1257
+
1258
+ note bottom of output
1259
+ 追加された情報:
1260
+ ・顧客名、与信情報
1261
+ ・商品名、商品区分
1262
+ ・適用単価
1263
+ ・在庫数、引当可能数
1264
+ end note
1265
+
1266
+ @enduml
1267
+ ```
1268
+
1269
+ <details>
1270
+ <summary>Java 実装例</summary>
1271
+
1272
+ ```java
1273
+ // Enricherインターフェース
1274
+ public interface ContentEnricher<T> {
1275
+ T enrich(T message);
1276
+ }
1277
+
1278
+ // 受注エンリッチャーチェーン
1279
+ @Component
1280
+ public class OrderEnricherChain {
1281
+ private final List<ContentEnricher<OrderEvent>> enrichers;
1282
+
1283
+ public OrderEnricherChain(
1284
+ CustomerEnricher customerEnricher,
1285
+ ProductEnricher productEnricher,
1286
+ PriceEnricher priceEnricher,
1287
+ InventoryEnricher inventoryEnricher) {
1288
+ this.enrichers = List.of(
1289
+ customerEnricher,
1290
+ productEnricher,
1291
+ priceEnricher,
1292
+ inventoryEnricher
1293
+ );
1294
+ }
1295
+
1296
+ public OrderEvent enrich(OrderEvent order) {
1297
+ OrderEvent enriched = order;
1298
+ for (ContentEnricher<OrderEvent> enricher : enrichers) {
1299
+ enriched = enricher.enrich(enriched);
1300
+ }
1301
+ return enriched;
1302
+ }
1303
+ }
1304
+
1305
+ // 顧客情報エンリッチャー
1306
+ @Component
1307
+ public class CustomerEnricher implements ContentEnricher<OrderEvent> {
1308
+ private final CustomerRepository customerRepository;
1309
+
1310
+ @Override
1311
+ public OrderEvent enrich(OrderEvent order) {
1312
+ Customer customer = customerRepository.findById(order.customerId())
1313
+ .orElseThrow(() -> new CustomerNotFoundException(order.customerId()));
1314
+
1315
+ return order.toBuilder()
1316
+ .customerName(customer.name())
1317
+ .customerAddress(customer.address())
1318
+ .creditLimit(customer.creditLimit())
1319
+ .build();
1320
+ }
1321
+ }
1322
+
1323
+ // 商品情報エンリッチャー
1324
+ @Component
1325
+ public class ProductEnricher implements ContentEnricher<OrderEvent> {
1326
+ private final ProductRepository productRepository;
1327
+
1328
+ @Override
1329
+ public OrderEvent enrich(OrderEvent order) {
1330
+ List<OrderLineEvent> enrichedLines = order.lines().stream()
1331
+ .map(line -> {
1332
+ Product product = productRepository.findById(line.productId())
1333
+ .orElseThrow();
1334
+ return line.toBuilder()
1335
+ .productName(product.name())
1336
+ .productCategory(product.category())
1337
+ .taxRate(product.taxRate())
1338
+ .build();
1339
+ })
1340
+ .toList();
1341
+
1342
+ return order.toBuilder()
1343
+ .lines(enrichedLines)
1344
+ .build();
1345
+ }
1346
+ }
1347
+ ```
1348
+
1349
+ </details>
1350
+
1351
+ ### Canonical Data Model(標準データモデル)
1352
+
1353
+ 複数のシステム間で共通に使用するデータモデルを定義し、変換の複雑さを軽減します。
1354
+
1355
+ ```plantuml
1356
+ @startuml
1357
+ title Canonical Data Model パターン
1358
+
1359
+ rectangle "販売管理\nシステム" as sales {
1360
+ rectangle "販売固有\nモデル" as sales_model
1361
+ }
1362
+
1363
+ rectangle "生産管理\nシステム" as production {
1364
+ rectangle "生産固有\nモデル" as prod_model
1365
+ }
1366
+
1367
+ rectangle "会計\nシステム" as accounting {
1368
+ rectangle "会計固有\nモデル" as acc_model
1369
+ }
1370
+
1371
+ rectangle "標準データモデル\n(Canonical Model)" as canonical {
1372
+ rectangle "標準取引先" as std_partner
1373
+ rectangle "標準商品/品目" as std_product
1374
+ rectangle "標準取引" as std_transaction
1375
+ }
1376
+
1377
+ sales_model <--> canonical : 変換
1378
+ prod_model <--> canonical : 変換
1379
+ acc_model <--> canonical : 変換
1380
+
1381
+ note bottom of canonical
1382
+ 【標準データモデルの利点】
1383
+ ・変換数の削減(N×N → 2×N)
1384
+ ・一貫したデータ定義
1385
+ ・システム追加時の影響最小化
1386
+
1387
+ 【定義すべき項目】
1388
+ ・共通エンティティ(取引先、商品等)
1389
+ ・共通イベント(取引、在庫移動等)
1390
+ ・共通コード体系
1391
+ end note
1392
+
1393
+ @enduml
1394
+ ```
1395
+
1396
+ #### 基幹業務システムの標準データモデル
1397
+
1398
+ ```plantuml
1399
+ @startuml
1400
+ title 基幹業務システムの標準データモデル
1401
+
1402
+ package "標準マスタモデル" as master {
1403
+ class "StandardPartner" as partner {
1404
+ +partnerId: String
1405
+ +partnerType: PartnerType
1406
+ +name: String
1407
+ +address: Address
1408
+ +contacts: List<Contact>
1409
+ }
1410
+
1411
+ class "StandardProduct" as product {
1412
+ +productId: String
1413
+ +productType: ProductType
1414
+ +name: String
1415
+ +unit: Unit
1416
+ +prices: List<Price>
1417
+ }
1418
+
1419
+ class "StandardDepartment" as dept {
1420
+ +departmentId: String
1421
+ +name: String
1422
+ +parentId: String
1423
+ +level: int
1424
+ }
1425
+ }
1426
+
1427
+ package "標準トランザクションモデル" as transaction {
1428
+ class "StandardTransaction" as trans {
1429
+ +transactionId: String
1430
+ +transactionType: TransactionType
1431
+ +transactionDate: Date
1432
+ +partnerId: String
1433
+ +totalAmount: Money
1434
+ +lines: List<TransactionLine>
1435
+ }
1436
+
1437
+ class "TransactionLine" as line {
1438
+ +lineNumber: int
1439
+ +productId: String
1440
+ +quantity: Quantity
1441
+ +unitPrice: Money
1442
+ +amount: Money
1443
+ }
1444
+ }
1445
+
1446
+ package "標準イベントモデル" as event {
1447
+ class "StandardEvent" as evt {
1448
+ +eventId: String
1449
+ +eventType: EventType
1450
+ +timestamp: Instant
1451
+ +source: String
1452
+ +payload: Object
1453
+ }
1454
+ }
1455
+
1456
+ trans "1" -- "*" line
1457
+
1458
+ note bottom of master
1459
+ 【コード体系の標準化】
1460
+ ・取引先コード:PTN-XXXXXXXX
1461
+ ・商品コード:PRD-XXXXXXXX
1462
+ ・部門コード:DPT-XXXX
1463
+ end note
1464
+
1465
+ @enduml
1466
+ ```
1467
+
1468
+ <details>
1469
+ <summary>Java 実装例</summary>
1470
+
1471
+ ```java
1472
+ // 標準取引先モデル
1473
+ public record StandardPartner(
1474
+ String partnerId,
1475
+ PartnerType partnerType,
1476
+ String name,
1477
+ Address address,
1478
+ List<Contact> contacts,
1479
+ Map<String, String> attributes
1480
+ ) {
1481
+ public enum PartnerType {
1482
+ CUSTOMER, // 顧客
1483
+ SUPPLIER, // 仕入先
1484
+ SUBCONTRACTOR // 外注先
1485
+ }
1486
+ }
1487
+
1488
+ // 標準トランザクションモデル
1489
+ public record StandardTransaction(
1490
+ String transactionId,
1491
+ TransactionType transactionType,
1492
+ LocalDate transactionDate,
1493
+ String partnerId,
1494
+ Money totalAmount,
1495
+ List<TransactionLine> lines,
1496
+ Map<String, String> attributes
1497
+ ) {
1498
+ public enum TransactionType {
1499
+ ORDER, // 受注
1500
+ SHIPMENT, // 出荷
1501
+ SALES, // 売上
1502
+ PURCHASE_ORDER, // 発注
1503
+ RECEIPT, // 入荷
1504
+ PURCHASE, // 仕入
1505
+ WORK_ORDER, // 製造指示
1506
+ COMPLETION // 完成
1507
+ }
1508
+ }
1509
+
1510
+ // 販売固有モデルから標準モデルへの変換
1511
+ @Component
1512
+ public class SalesOrderToCanonicalTranslator
1513
+ implements MessageTranslator<SalesOrder, StandardTransaction> {
1514
+
1515
+ @Override
1516
+ public StandardTransaction translate(SalesOrder order) {
1517
+ return new StandardTransaction(
1518
+ "TXN-" + order.orderId(),
1519
+ TransactionType.ORDER,
1520
+ order.orderDate(),
1521
+ "PTN-" + order.customerId(),
1522
+ Money.of(order.totalAmount(), "JPY"),
1523
+ order.lines().stream()
1524
+ .map(this::translateLine)
1525
+ .toList(),
1526
+ Map.of(
1527
+ "originalOrderId", order.orderId(),
1528
+ "salesRepId", order.salesRepId()
1529
+ )
1530
+ );
1531
+ }
1532
+
1533
+ private TransactionLine translateLine(SalesOrderLine line) {
1534
+ return new TransactionLine(
1535
+ line.lineNumber(),
1536
+ "PRD-" + line.productCode(),
1537
+ Quantity.of(line.quantity(), line.unit()),
1538
+ Money.of(line.unitPrice(), "JPY"),
1539
+ Money.of(line.amount(), "JPY")
1540
+ );
1541
+ }
1542
+ }
1543
+
1544
+ // 標準モデルから会計固有モデルへの変換
1545
+ @Component
1546
+ public class CanonicalToJournalTranslator
1547
+ implements MessageTranslator<StandardTransaction, JournalEntry> {
1548
+
1549
+ @Override
1550
+ public JournalEntry translate(StandardTransaction transaction) {
1551
+ // 取引種別に応じた仕訳パターンを適用
1552
+ JournalPattern pattern = determinePattern(transaction.transactionType());
1553
+
1554
+ return new JournalEntry(
1555
+ generateJournalId(),
1556
+ transaction.transactionDate(),
1557
+ pattern.journalType(),
1558
+ createJournalLines(transaction, pattern)
1559
+ );
1560
+ }
1561
+ }
1562
+ ```
1563
+
1564
+ </details>
1565
+
1566
+ ---
1567
+
1568
+ ## 34.4 まとめ
1569
+
1570
+ 本章では、エンタープライズインテグレーションの基盤となるメッセージングパターンについて解説しました。
1571
+
1572
+ ### 学んだパターン一覧
1573
+
1574
+ | カテゴリ | パターン | 用途 |
1575
+ |---------|---------|------|
1576
+ | **基礎** | Message Channel | メッセージの伝送経路 |
1577
+ | | Message | データとメタデータの構造 |
1578
+ | | Pipes and Filters | 処理の分解と連結 |
1579
+ | **ルーティング** | Content-Based Router | 内容に基づく振り分け |
1580
+ | | Message Filter | 条件による通過/破棄 |
1581
+ | | Splitter/Aggregator | 分割と集約 |
1582
+ | | Resequencer | 順序の再整列 |
1583
+ | **変換** | Message Translator | 形式変換 |
1584
+ | | Envelope Wrapper | メタデータ付与 |
1585
+ | | Content Enricher | 情報の追加 |
1586
+ | | Canonical Data Model | 標準データ形式 |
1587
+
1588
+ ### 基幹業務システムへの適用ポイント
1589
+
1590
+ 1. **チャネル設計**
1591
+
1592
+ - Point-to-Point:受注処理、仕訳生成など1対1の処理
1593
+ - Pub/Sub:イベント通知、複数システムへの連携
1594
+
1595
+ 2. **ルーティング設計**
1596
+
1597
+ - 取引種別による振り分け
1598
+ - 金額閾値によるフィルタリング
1599
+ - 月次締めでの分割/集約
1600
+
1601
+ 3. **変換設計**
1602
+
1603
+ - 売上→仕訳の自動変換
1604
+ - マスタ情報のエンリッチメント
1605
+ - 標準データモデルによる統合
1606
+
1607
+ ### 次章の予告
1608
+
1609
+ 第35章では、システム間連携パターンについて詳しく解説します。販売管理と財務会計、販売管理と生産管理、生産管理と財務会計の具体的な連携方法を学びます。