@k2works/claude-code-booster 3.2.1 → 3.3.1

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 (70) hide show
  1. package/lib/assets/.claude/skills/analyzing-business/SKILL.md +2 -2
  2. package/lib/assets/.claude/skills/analyzing-inception-deck/SKILL.md +5 -5
  3. package/lib/assets/.claude/skills/analyzing-requirements/SKILL.md +2 -2
  4. package/lib/assets/.claude/skills/generating-slides/SKILL.md +7 -7
  5. package/lib/assets/docs/article/index.md +4 -1
  6. package/lib/assets/docs/article/practical-database-design/index.md +121 -0
  7. package/lib/assets/docs/article/practical-database-design/part1/chapter01.md +288 -0
  8. package/lib/assets/docs/article/practical-database-design/part1/chapter02.md +518 -0
  9. package/lib/assets/docs/article/practical-database-design/part1/chapter03.md +557 -0
  10. package/lib/assets/docs/article/practical-database-design/part2/chapter04.md +924 -0
  11. package/lib/assets/docs/article/practical-database-design/part2/chapter05.md +1627 -0
  12. package/lib/assets/docs/article/practical-database-design/part2/chapter06.md +2716 -0
  13. package/lib/assets/docs/article/practical-database-design/part2/chapter07.md +2082 -0
  14. package/lib/assets/docs/article/practical-database-design/part2/chapter08.md +2105 -0
  15. package/lib/assets/docs/article/practical-database-design/part2/chapter09.md +2031 -0
  16. package/lib/assets/docs/article/practical-database-design/part2/chapter10.md +1387 -0
  17. package/lib/assets/docs/article/practical-database-design/part2/chapter11.md +1677 -0
  18. package/lib/assets/docs/article/practical-database-design/part2/chapter12.md +1417 -0
  19. package/lib/assets/docs/article/practical-database-design/part2/chapter13.md +1434 -0
  20. package/lib/assets/docs/article/practical-database-design/part3/chapter14.md +667 -0
  21. package/lib/assets/docs/article/practical-database-design/part3/chapter15.md +1625 -0
  22. package/lib/assets/docs/article/practical-database-design/part3/chapter16.md +1915 -0
  23. package/lib/assets/docs/article/practical-database-design/part3/chapter17.md +1708 -0
  24. package/lib/assets/docs/article/practical-database-design/part3/chapter18.md +2095 -0
  25. package/lib/assets/docs/article/practical-database-design/part3/chapter19.md +1123 -0
  26. package/lib/assets/docs/article/practical-database-design/part3/chapter20.md +1031 -0
  27. package/lib/assets/docs/article/practical-database-design/part3/chapter21.md +1382 -0
  28. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter14-orm.md +991 -0
  29. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter15-orm.md +1300 -0
  30. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter16-orm.md +1166 -0
  31. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter17-orm.md +1584 -0
  32. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter18-orm.md +1183 -0
  33. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter19-orm.md +1016 -0
  34. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter20-orm.md +1753 -0
  35. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter21-orm.md +1447 -0
  36. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter22-orm.md +1878 -0
  37. package/lib/assets/docs/article/practical-database-design/part4/chapter22.md +965 -0
  38. package/lib/assets/docs/article/practical-database-design/part4/chapter23.md +2069 -0
  39. package/lib/assets/docs/article/practical-database-design/part4/chapter24.md +2439 -0
  40. package/lib/assets/docs/article/practical-database-design/part4/chapter25.md +3661 -0
  41. package/lib/assets/docs/article/practical-database-design/part4/chapter26.md +2916 -0
  42. package/lib/assets/docs/article/practical-database-design/part4/chapter27.md +3105 -0
  43. package/lib/assets/docs/article/practical-database-design/part4/chapter28.md +2697 -0
  44. package/lib/assets/docs/article/practical-database-design/part4/chapter29.md +2544 -0
  45. package/lib/assets/docs/article/practical-database-design/part4/chapter30.md +2180 -0
  46. package/lib/assets/docs/article/practical-database-design/part4/chapter31.md +1192 -0
  47. package/lib/assets/docs/article/practical-database-design/part4/chapter32.md +2101 -0
  48. package/lib/assets/docs/article/practical-database-design/part5/chapter33.md +1032 -0
  49. package/lib/assets/docs/article/practical-database-design/part5/chapter34.md +1609 -0
  50. package/lib/assets/docs/article/practical-database-design/part5/chapter35.md +1453 -0
  51. package/lib/assets/docs/article/practical-database-design/part5/chapter36.md +1292 -0
  52. package/lib/assets/docs/article/practical-database-design/part5/chapter37.md +1470 -0
  53. package/lib/assets/docs/article/practical-database-design/part5/chapter38.md +1698 -0
  54. package/lib/assets/docs/article/practical-database-design/part5/chapter39.md +2334 -0
  55. package/lib/assets/docs/article/practical-database-design/study/study2-1.md +1693 -0
  56. package/lib/assets/docs/article/practical-database-design/study/study2-2.md +1347 -0
  57. package/lib/assets/docs/article/practical-database-design/study/study2-3.md +2044 -0
  58. package/lib/assets/docs/article/practical-database-design/study/study2-4.md +2229 -0
  59. package/lib/assets/docs/article/practical-database-design/study/study2-5.md +2418 -0
  60. package/lib/assets/docs/article/practical-database-design/study/study3-1.md +2205 -0
  61. package/lib/assets/docs/article/practical-database-design/study/study3-2.md +2221 -0
  62. package/lib/assets/docs/article/practical-database-design/study/study3-3.md +2253 -0
  63. package/lib/assets/docs/article/practical-database-design/study/study3-4.md +2106 -0
  64. package/lib/assets/docs/article/practical-database-design/study/study3-5.md +2507 -0
  65. package/lib/assets/docs/article/practical-database-design/study/study4-1.md +2587 -0
  66. package/lib/assets/docs/article/practical-database-design/study/study4-2.md +2075 -0
  67. package/lib/assets/docs/article/practical-database-design/study/study4-3.md +1805 -0
  68. package/lib/assets/docs/article/practical-database-design/study/study4-4.md +1895 -0
  69. package/lib/assets/docs/article/practical-database-design/study/study4-5.md +2878 -0
  70. package/package.json +1 -1
@@ -0,0 +1,1805 @@
1
+ # 実践データベース設計:生産管理システム 研究 3 - gRPC サービスの実装
2
+
3
+ ## はじめに
4
+
5
+ 本研究では、API サーバー構成(第32章)とは異なるアプローチとして、**gRPC** による生産管理システムを実装します。Protocol Buffers によるスキーマ駆動開発と HTTP/2 の双方向ストリーミングを活用した、高性能な API を構築します。
6
+
7
+ 第32章で構築したヘキサゴナルアーキテクチャ(ドメイン層・アプリケーション層)はそのまま共有し、**Input Adapter として gRPC サービス層のみを追加**します。
8
+
9
+ ---
10
+
11
+ ## 第42章:gRPC サーバーの基礎
12
+
13
+ ### 42.1 gRPC とは
14
+
15
+ gRPC は Google が開発した高性能な RPC(Remote Procedure Call)フレームワークです。Protocol Buffers をインターフェース定義言語(IDL)として使用し、HTTP/2 上で動作します。
16
+
17
+ ```plantuml
18
+ @startuml grpc_architecture
19
+ !define RECTANGLE class
20
+
21
+ skinparam backgroundColor #FEFEFE
22
+
23
+ package "gRPC Architecture (生産管理システム)" {
24
+
25
+ package "Client Side" {
26
+ RECTANGLE "gRPC Client\n(Java/Kotlin/Go)" as client {
27
+ - ItemServiceStub
28
+ - PurchaseOrderServiceStub
29
+ - MrpServiceStub
30
+ }
31
+ }
32
+
33
+ package "Server Side" {
34
+ RECTANGLE "gRPC Server\n(Spring Boot + grpc-spring-boot-starter)" as server {
35
+ - ItemGrpcService
36
+ - PurchaseOrderGrpcService
37
+ - MrpGrpcService
38
+ }
39
+ }
40
+
41
+ package "Shared" {
42
+ RECTANGLE "Protocol Buffers\n(.proto files)" as proto {
43
+ - item.proto
44
+ - purchase_order.proto
45
+ - mrp.proto
46
+ }
47
+ }
48
+ }
49
+
50
+ client --> proto : "生成されたStub\nを使用"
51
+ server --> proto : "生成されたService\nを実装"
52
+ client <--> server : "HTTP/2\n(双方向ストリーミング)"
53
+
54
+ note bottom of proto
55
+ スキーマ駆動開発
56
+ 型安全な通信
57
+ 言語間相互運用性
58
+ end note
59
+
60
+ @enduml
61
+ ```
62
+
63
+ **REST API との比較:**
64
+
65
+ | 特徴 | REST API | gRPC |
66
+ |------|----------|------|
67
+ | プロトコル | HTTP/1.1 | HTTP/2 |
68
+ | データ形式 | JSON (テキスト) | Protocol Buffers (バイナリ) |
69
+ | スキーマ | OpenAPI (任意) | .proto (必須) |
70
+ | ストリーミング | WebSocket 別実装 | ネイティブサポート |
71
+ | コード生成 | 手動/ツール | 自動生成 |
72
+ | パフォーマンス | 標準 | 高速 |
73
+
74
+ ### 42.2 4つの通信パターン
75
+
76
+ gRPC は 4 つの通信パターンをサポートします:
77
+
78
+ ```plantuml
79
+ @startuml grpc_patterns
80
+ skinparam backgroundColor #FEFEFE
81
+
82
+ rectangle "1. Unary RPC\n(単項)" as unary {
83
+ (Client) --> (Server) : Request
84
+ (Server) --> (Client) : Response
85
+ }
86
+
87
+ rectangle "2. Server Streaming\n(サーバーストリーミング)" as server_stream {
88
+ (Client2) --> (Server2) : Request
89
+ (Server2) --> (Client2) : Response 1
90
+ (Server2) --> (Client2) : Response 2
91
+ (Server2) --> (Client2) : Response N
92
+ }
93
+
94
+ rectangle "3. Client Streaming\n(クライアントストリーミング)" as client_stream {
95
+ (Client3) --> (Server3) : Request 1
96
+ (Client3) --> (Server3) : Request 2
97
+ (Client3) --> (Server3) : Request N
98
+ (Server3) --> (Client3) : Response
99
+ }
100
+
101
+ rectangle "4. Bidirectional Streaming\n(双方向ストリーミング)" as bidi {
102
+ (Client4) <--> (Server4) : Messages
103
+ }
104
+
105
+ @enduml
106
+ ```
107
+
108
+ **用途:**
109
+
110
+ 1. **Unary RPC**: 通常の API 呼び出し(CRUD 操作)
111
+ 2. **Server Streaming**: 大量データの配信(MRP 実行結果)
112
+ 3. **Client Streaming**: バッチ登録(複数品目の一括登録)
113
+ 4. **Bidirectional Streaming**: リアルタイム通信(進捗監視)
114
+
115
+ ### 42.3 gRPC におけるヘキサゴナルアーキテクチャ
116
+
117
+ gRPC を導入しても、第32章で構築したヘキサゴナルアーキテクチャ(ドメイン層・アプリケーション層)はそのまま共有し、**Input Adapter として gRPC サービス層のみを追加**します。
118
+
119
+ ```plantuml
120
+ @startuml hexagonal_grpc
121
+ !define RECTANGLE class
122
+
123
+ package "Hexagonal Architecture (gRPC版)" {
124
+
125
+ RECTANGLE "Application Core\n(Domain + Use Cases)" as core {
126
+ - Item (品目)
127
+ - Bom (部品構成表)
128
+ - Order (オーダ)
129
+ - Stock (在庫)
130
+ - ItemUseCase
131
+ - OrderUseCase
132
+ - InventoryUseCase
133
+ }
134
+
135
+ RECTANGLE "Input Adapters\n(Driving Side)" as input {
136
+ - REST Controller(既存)
137
+ - gRPC Service(新規追加)
138
+ - Proto Mapper
139
+ - Interceptor
140
+ }
141
+
142
+ RECTANGLE "Output Adapters\n(Driven Side)" as output {
143
+ - MyBatis Repository
144
+ - Database Access
145
+ - Entity Mapping
146
+ }
147
+ }
148
+
149
+ input --> core : "Input Ports\n(Use Cases)"
150
+ core --> output : "Output Ports\n(Repository Interfaces)"
151
+
152
+ note top of core
153
+ 既存のビジネスロジック
154
+ REST API 版と完全に共有
155
+ gRPC 固有のコードは含まない
156
+ end note
157
+
158
+ note left of input
159
+ gRPC サービスを
160
+ Input Adapter として追加
161
+ 既存の REST API と共存可能
162
+ end note
163
+
164
+ note right of output
165
+ 既存の Repository を
166
+ そのまま使用
167
+ 変更不要
168
+ end note
169
+
170
+ @enduml
171
+ ```
172
+
173
+ **gRPC でもヘキサゴナルアーキテクチャを維持する理由:**
174
+
175
+ 1. **再利用性**: 既存の UseCase/Repository をそのまま活用
176
+ 2. **並行運用**: REST API と gRPC API の両方を提供可能
177
+ 3. **テスト容易性**: ドメインロジックは通信プロトコルに依存しない
178
+ 4. **移行容易性**: 段階的に REST から gRPC へ移行可能
179
+
180
+ ### 42.4 ディレクトリ構成
181
+
182
+ 既存の構成に `infrastructure/grpc/` を追加するだけです。
183
+
184
+ ```
185
+ src/main/java/com/example/production/
186
+ ├── domain/ # ドメイン層(API版と共通)
187
+ │ ├── model/
188
+ │ │ ├── item/
189
+ │ │ ├── bom/
190
+ │ │ ├── order/
191
+ │ │ └── inventory/
192
+ │ └── exception/
193
+
194
+ ├── application/ # アプリケーション層(API版と共通)
195
+ │ ├── port/
196
+ │ │ ├── in/ # Input Port(ユースケース)
197
+ │ │ └── out/ # Output Port(リポジトリ)
198
+ │ └── service/
199
+
200
+ ├── infrastructure/
201
+ │ ├── persistence/ # Output Adapter(DB実装)- 既存
202
+ │ │ ├── mapper/
203
+ │ │ └── repository/
204
+ │ ├── rest/ # Input Adapter(REST実装)- 既存
205
+ │ │ ├── controller/
206
+ │ │ ├── dto/
207
+ │ │ └── exception/
208
+ │ └── grpc/ # Input Adapter(gRPC実装)- 新規追加
209
+ │ ├── service/ # gRPC Service 実装
210
+ │ ├── mapper/ # Proto ⇔ Domain 変換
211
+ │ └── interceptor/ # 共通処理(ログ、エラー等)
212
+
213
+ ├── config/
214
+
215
+ └── src/main/proto/ # Protocol Buffers 定義
216
+ ├── common.proto
217
+ ├── item.proto
218
+ ├── bom.proto
219
+ ├── purchase_order.proto
220
+ └── mrp.proto
221
+ ```
222
+
223
+ ### 42.5 技術スタックの追加
224
+
225
+ 既存の `build.gradle.kts` に gRPC 関連の依存関係を追加します。
226
+
227
+ <details>
228
+ <summary>build.gradle.kts(差分)</summary>
229
+
230
+ ```kotlin
231
+ import com.google.protobuf.gradle.*
232
+
233
+ plugins {
234
+ // 既存のプラグイン...
235
+ id("com.google.protobuf") version "0.9.4" // 追加
236
+ }
237
+
238
+ dependencies {
239
+ // 既存の依存関係(Spring Boot, MyBatis, PostgreSQL等)はそのまま
240
+
241
+ // gRPC 関連を追加
242
+ implementation("net.devh:grpc-spring-boot-starter:3.0.0.RELEASE")
243
+ implementation("io.grpc:grpc-protobuf:1.60.0")
244
+ implementation("io.grpc:grpc-stub:1.60.0")
245
+ implementation("io.grpc:grpc-services:1.60.0") // Health check, Reflection
246
+
247
+ // Protocol Buffers
248
+ implementation("com.google.protobuf:protobuf-java:3.25.1")
249
+ implementation("com.google.protobuf:protobuf-java-util:3.25.1")
250
+
251
+ // Test
252
+ testImplementation("io.grpc:grpc-testing:1.60.0")
253
+ }
254
+
255
+ // Protocol Buffers コンパイル設定
256
+ protobuf {
257
+ protoc {
258
+ artifact = "com.google.protobuf:protoc:3.25.1"
259
+ }
260
+ plugins {
261
+ id("grpc") {
262
+ artifact = "io.grpc:protoc-gen-grpc-java:1.60.0"
263
+ }
264
+ }
265
+ generateProtoTasks {
266
+ all().forEach { task ->
267
+ task.plugins {
268
+ id("grpc")
269
+ }
270
+ }
271
+ }
272
+ }
273
+ ```
274
+
275
+ </details>
276
+
277
+ **追加パッケージの説明:**
278
+
279
+ | パッケージ | 用途 |
280
+ |-----------|------|
281
+ | grpc-spring-boot-starter | Spring Boot との統合 |
282
+ | grpc-protobuf | Protocol Buffers サポート |
283
+ | grpc-services | ヘルスチェック、リフレクション |
284
+ | protobuf-java-util | JSON ⇔ Proto 変換 |
285
+
286
+ ### 38.6 Protocol Buffers 定義
287
+
288
+ <details>
289
+ <summary>src/main/proto/common.proto</summary>
290
+
291
+ ```protobuf
292
+ syntax = "proto3";
293
+
294
+ package production;
295
+
296
+ option java_package = "com.example.production.grpc";
297
+ option java_multiple_files = true;
298
+
299
+ // 共通メッセージ
300
+
301
+ message Empty {}
302
+
303
+ message Timestamp {
304
+ int64 seconds = 1;
305
+ int32 nanos = 2;
306
+ }
307
+
308
+ message Date {
309
+ int32 year = 1;
310
+ int32 month = 2;
311
+ int32 day = 3;
312
+ }
313
+
314
+ message Decimal {
315
+ string value = 1; // 文字列で精度を維持
316
+ }
317
+
318
+ message PageRequest {
319
+ int32 page = 1;
320
+ int32 size = 2;
321
+ }
322
+
323
+ message PageResponse {
324
+ int32 total_elements = 1;
325
+ int32 total_pages = 2;
326
+ int32 current_page = 3;
327
+ }
328
+
329
+ // エラーレスポンス
330
+ message ErrorDetail {
331
+ string code = 1;
332
+ string message = 2;
333
+ map<string, string> metadata = 3;
334
+ }
335
+ ```
336
+
337
+ </details>
338
+
339
+ <details>
340
+ <summary>src/main/proto/item.proto</summary>
341
+
342
+ ```protobuf
343
+ syntax = "proto3";
344
+
345
+ package production;
346
+
347
+ import "common.proto";
348
+
349
+ option java_package = "com.example.production.grpc";
350
+ option java_multiple_files = true;
351
+
352
+ // 品目区分
353
+ enum ItemCategory {
354
+ ITEM_CATEGORY_UNSPECIFIED = 0;
355
+ PRODUCT = 1; // 製品
356
+ SEMI_PRODUCT = 2; // 半製品
357
+ PART = 3; // 部品
358
+ MATERIAL = 4; // 材料
359
+ }
360
+
361
+ // 品目メッセージ
362
+ message Item {
363
+ string item_code = 1;
364
+ Date effective_date = 2;
365
+ string item_name = 3;
366
+ ItemCategory category = 4;
367
+ string item_group_code = 5;
368
+ string unit_code = 6;
369
+ string location_code = 7;
370
+ int32 lead_time = 8;
371
+ int32 safety_stock = 9;
372
+ }
373
+
374
+ // リクエスト/レスポンス
375
+ message GetItemRequest {
376
+ string item_code = 1;
377
+ }
378
+
379
+ message GetItemsRequest {
380
+ ItemCategory category = 1; // optional filter
381
+ PageRequest page = 2;
382
+ }
383
+
384
+ message GetItemsResponse {
385
+ repeated Item items = 1;
386
+ PageResponse page = 2;
387
+ }
388
+
389
+ message CreateItemRequest {
390
+ string item_code = 1;
391
+ string item_name = 2;
392
+ ItemCategory category = 3;
393
+ string item_group_code = 4;
394
+ string unit_code = 5;
395
+ string location_code = 6;
396
+ int32 lead_time = 7;
397
+ int32 safety_stock = 8;
398
+ }
399
+
400
+ message UpdateItemRequest {
401
+ string item_code = 1;
402
+ string item_name = 2;
403
+ ItemCategory category = 3;
404
+ int32 lead_time = 4;
405
+ int32 safety_stock = 5;
406
+ }
407
+
408
+ message DeleteItemRequest {
409
+ string item_code = 1;
410
+ }
411
+
412
+ message BatchCreateResponse {
413
+ int32 success_count = 1;
414
+ int32 failed_count = 2;
415
+ repeated string failed_codes = 3;
416
+ }
417
+
418
+ // 品目サービス
419
+ service ItemService {
420
+ // Unary RPC
421
+ rpc GetItem(GetItemRequest) returns (Item);
422
+ rpc CreateItem(CreateItemRequest) returns (Item);
423
+ rpc UpdateItem(UpdateItemRequest) returns (Item);
424
+ rpc DeleteItem(DeleteItemRequest) returns (Empty);
425
+
426
+ // Server Streaming - 品目一覧のストリーム配信
427
+ rpc StreamItems(GetItemsRequest) returns (stream Item);
428
+
429
+ // Client Streaming - バッチ登録
430
+ rpc BatchCreateItems(stream CreateItemRequest) returns (BatchCreateResponse);
431
+ }
432
+ ```
433
+
434
+ </details>
435
+
436
+ ### 38.7 API サーバー版との Controller の違い
437
+
438
+ **API サーバー版(REST Controller)**
439
+
440
+ ```java
441
+ @RestController // JSON を返す
442
+ @RequestMapping("/api/items")
443
+ public class ItemApiController {
444
+
445
+ private final ItemUseCase itemUseCase; // 共有
446
+
447
+ @GetMapping("/{itemCode}")
448
+ public ResponseEntity<ItemResponse> getItem(@PathVariable String itemCode) {
449
+ Item item = itemUseCase.getItemByCode(itemCode);
450
+ return ResponseEntity.ok(ItemResponse.from(item));
451
+ }
452
+ }
453
+ ```
454
+
455
+ **gRPC 版(gRPC Service)**
456
+
457
+ ```java
458
+ @GrpcService // gRPC サービスとして公開
459
+ public class ItemGrpcService extends ItemServiceGrpc.ItemServiceImplBase {
460
+
461
+ private final ItemUseCase itemUseCase; // 共有(同じインスタンス)
462
+ private final ProtoMapper mapper;
463
+
464
+ @Override
465
+ public void getItem(GetItemRequest request,
466
+ StreamObserver<Item> responseObserver) {
467
+ // 同じ UseCase を呼び出し
468
+ var item = itemUseCase.getItemByCode(request.getItemCode());
469
+ responseObserver.onNext(mapper.toProto(item));
470
+ responseObserver.onCompleted();
471
+ }
472
+ }
473
+ ```
474
+
475
+ **共通点と相違点:**
476
+
477
+ | 観点 | REST Controller | gRPC Service |
478
+ |------|-----------------|--------------|
479
+ | **UseCase** | 共有(同一インスタンス) | 共有(同一インスタンス) |
480
+ | **アノテーション** | `@RestController` | `@GrpcService` |
481
+ | **リクエスト** | DTO(JSON) | Proto Message |
482
+ | **レスポンス** | `ResponseEntity<T>` | `StreamObserver<T>` |
483
+ | **変換** | DTO ⇔ Domain | Proto ⇔ Domain |
484
+ | **エラー処理** | 例外ハンドラ | `Status` + `onError` |
485
+
486
+ ---
487
+
488
+ ## 第43章:マスタ API の実装
489
+
490
+ ### 43.1 Proto マッパーの実装
491
+
492
+ 既存のドメインモデルと Protocol Buffers メッセージ間の変換を行います。
493
+
494
+ <details>
495
+ <summary>ProtoMapper.java</summary>
496
+
497
+ ```java
498
+ package com.example.production.infrastructure.grpc.mapper;
499
+
500
+ import com.example.production.domain.model.item.Item;
501
+ import com.example.production.domain.model.item.ItemCategory;
502
+ import com.example.production.grpc.*;
503
+ import org.springframework.stereotype.Component;
504
+
505
+ import java.math.BigDecimal;
506
+ import java.time.LocalDate;
507
+
508
+ /**
509
+ * ドメインモデルと Protocol Buffers メッセージ間の変換
510
+ */
511
+ @Component
512
+ public class ProtoMapper {
513
+
514
+ // ========== Item ==========
515
+
516
+ public com.example.production.grpc.Item toProto(Item domain) {
517
+ return com.example.production.grpc.Item.newBuilder()
518
+ .setItemCode(domain.getItemCode())
519
+ .setEffectiveDate(toProtoDate(domain.getEffectiveDate()))
520
+ .setItemName(domain.getItemName())
521
+ .setCategory(toProtoCategory(domain.getCategory()))
522
+ .setItemGroupCode(nullToEmpty(domain.getItemGroupCode()))
523
+ .setUnitCode(nullToEmpty(domain.getUnitCode()))
524
+ .setLocationCode(nullToEmpty(domain.getLocationCode()))
525
+ .setLeadTime(nullToZero(domain.getLeadTime()))
526
+ .setSafetyStock(nullToZero(domain.getSafetyStock()))
527
+ .build();
528
+ }
529
+
530
+ public Item toDomain(CreateItemRequest request) {
531
+ return Item.builder()
532
+ .itemCode(request.getItemCode())
533
+ .effectiveDate(LocalDate.now())
534
+ .itemName(request.getItemName())
535
+ .category(toDomainCategory(request.getCategory()))
536
+ .itemGroupCode(emptyToNull(request.getItemGroupCode()))
537
+ .unitCode(emptyToNull(request.getUnitCode()))
538
+ .locationCode(emptyToNull(request.getLocationCode()))
539
+ .leadTime(zeroToNull(request.getLeadTime()))
540
+ .safetyStock(zeroToNull(request.getSafetyStock()))
541
+ .build();
542
+ }
543
+
544
+ // ========== Date ==========
545
+
546
+ public Date toProtoDate(LocalDate date) {
547
+ if (date == null) {
548
+ return Date.getDefaultInstance();
549
+ }
550
+ return Date.newBuilder()
551
+ .setYear(date.getYear())
552
+ .setMonth(date.getMonthValue())
553
+ .setDay(date.getDayOfMonth())
554
+ .build();
555
+ }
556
+
557
+ public LocalDate toDomainDate(Date protoDate) {
558
+ if (protoDate.getYear() == 0) {
559
+ return null;
560
+ }
561
+ return LocalDate.of(
562
+ protoDate.getYear(),
563
+ protoDate.getMonth(),
564
+ protoDate.getDay()
565
+ );
566
+ }
567
+
568
+ // ========== Decimal ==========
569
+
570
+ public Decimal toProtoDecimal(BigDecimal value) {
571
+ if (value == null) {
572
+ return Decimal.getDefaultInstance();
573
+ }
574
+ return Decimal.newBuilder()
575
+ .setValue(value.toPlainString())
576
+ .build();
577
+ }
578
+
579
+ public BigDecimal toDomainDecimal(Decimal protoDecimal) {
580
+ if (protoDecimal.getValue().isEmpty()) {
581
+ return null;
582
+ }
583
+ return new BigDecimal(protoDecimal.getValue());
584
+ }
585
+
586
+ // ========== ItemCategory ==========
587
+
588
+ public com.example.production.grpc.ItemCategory toProtoCategory(ItemCategory domain) {
589
+ if (domain == null) {
590
+ return com.example.production.grpc.ItemCategory.ITEM_CATEGORY_UNSPECIFIED;
591
+ }
592
+ return switch (domain) {
593
+ case PRODUCT -> com.example.production.grpc.ItemCategory.PRODUCT;
594
+ case SEMI_PRODUCT -> com.example.production.grpc.ItemCategory.SEMI_PRODUCT;
595
+ case PART -> com.example.production.grpc.ItemCategory.PART;
596
+ case MATERIAL -> com.example.production.grpc.ItemCategory.MATERIAL;
597
+ };
598
+ }
599
+
600
+ public ItemCategory toDomainCategory(com.example.production.grpc.ItemCategory proto) {
601
+ return switch (proto) {
602
+ case PRODUCT -> ItemCategory.PRODUCT;
603
+ case SEMI_PRODUCT -> ItemCategory.SEMI_PRODUCT;
604
+ case PART -> ItemCategory.PART;
605
+ case MATERIAL -> ItemCategory.MATERIAL;
606
+ default -> null;
607
+ };
608
+ }
609
+
610
+ // ========== Utility ==========
611
+
612
+ private String nullToEmpty(String value) {
613
+ return value == null ? "" : value;
614
+ }
615
+
616
+ private String emptyToNull(String value) {
617
+ return value == null || value.isEmpty() ? null : value;
618
+ }
619
+
620
+ private int nullToZero(Integer value) {
621
+ return value == null ? 0 : value;
622
+ }
623
+
624
+ private Integer zeroToNull(int value) {
625
+ return value == 0 ? null : value;
626
+ }
627
+ }
628
+ ```
629
+
630
+ </details>
631
+
632
+ ### 43.2 品目 gRPC サービスの TDD 実装
633
+
634
+ #### Red: 失敗するテストを書く
635
+
636
+ <details>
637
+ <summary>ItemGrpcServiceTest.java</summary>
638
+
639
+ ```java
640
+ package com.example.production.infrastructure.grpc.service;
641
+
642
+ import com.example.production.domain.model.item.Item;
643
+ import com.example.production.domain.model.item.ItemCategory;
644
+ import com.example.production.grpc.*;
645
+ import com.example.production.infrastructure.persistence.mapper.ItemMapper;
646
+ import io.grpc.ManagedChannel;
647
+ import io.grpc.ManagedChannelBuilder;
648
+ import io.grpc.StatusRuntimeException;
649
+ import org.junit.jupiter.api.*;
650
+ import org.springframework.beans.factory.annotation.Autowired;
651
+ import org.springframework.boot.test.context.SpringBootTest;
652
+ import org.springframework.test.context.DynamicPropertyRegistry;
653
+ import org.springframework.test.context.DynamicPropertySource;
654
+ import org.testcontainers.containers.PostgreSQLContainer;
655
+ import org.testcontainers.junit.jupiter.Container;
656
+ import org.testcontainers.junit.jupiter.Testcontainers;
657
+
658
+ import java.time.LocalDate;
659
+ import java.util.ArrayList;
660
+ import java.util.Iterator;
661
+ import java.util.List;
662
+ import java.util.concurrent.CountDownLatch;
663
+ import java.util.concurrent.TimeUnit;
664
+
665
+ import static org.assertj.core.api.Assertions.*;
666
+
667
+ @SpringBootTest(properties = {
668
+ "grpc.server.port=9090",
669
+ "grpc.server.in-process-name=test"
670
+ })
671
+ @Testcontainers
672
+ @DisplayName("品目 gRPC サービス")
673
+ class ItemGrpcServiceTest {
674
+
675
+ @Container
676
+ static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16")
677
+ .withDatabaseName("production_test")
678
+ .withUsername("test")
679
+ .withPassword("test");
680
+
681
+ @DynamicPropertySource
682
+ static void configureProperties(DynamicPropertyRegistry registry) {
683
+ registry.add("spring.datasource.url", postgres::getJdbcUrl);
684
+ registry.add("spring.datasource.username", postgres::getUsername);
685
+ registry.add("spring.datasource.password", postgres::getPassword);
686
+ }
687
+
688
+ @Autowired
689
+ private ItemMapper itemMapper;
690
+
691
+ private ManagedChannel channel;
692
+ private ItemServiceGrpc.ItemServiceBlockingStub blockingStub;
693
+ private ItemServiceGrpc.ItemServiceStub asyncStub;
694
+
695
+ @BeforeEach
696
+ void setUp() {
697
+ channel = ManagedChannelBuilder.forAddress("localhost", 9090)
698
+ .usePlaintext()
699
+ .build();
700
+ blockingStub = ItemServiceGrpc.newBlockingStub(channel);
701
+ asyncStub = ItemServiceGrpc.newStub(channel);
702
+
703
+ // テストデータをクリア
704
+ itemMapper.deleteAll();
705
+ }
706
+
707
+ @AfterEach
708
+ void tearDown() {
709
+ channel.shutdownNow();
710
+ }
711
+
712
+ @Nested
713
+ @DisplayName("GetItem (Unary)")
714
+ class GetItemTests {
715
+
716
+ @Test
717
+ @DisplayName("品目コードで品目を取得できる")
718
+ void shouldGetItemByCode() {
719
+ // Arrange
720
+ insertTestItem("PROD-001", "テスト製品", ItemCategory.PRODUCT);
721
+
722
+ // Act
723
+ var request = GetItemRequest.newBuilder()
724
+ .setItemCode("PROD-001")
725
+ .build();
726
+ var response = blockingStub.getItem(request);
727
+
728
+ // Assert
729
+ assertThat(response.getItemCode()).isEqualTo("PROD-001");
730
+ assertThat(response.getItemName()).isEqualTo("テスト製品");
731
+ assertThat(response.getCategory())
732
+ .isEqualTo(com.example.production.grpc.ItemCategory.PRODUCT);
733
+ }
734
+
735
+ @Test
736
+ @DisplayName("存在しない品目はNOT_FOUNDを返す")
737
+ void shouldThrowNotFoundForNonExistentItem() {
738
+ var request = GetItemRequest.newBuilder()
739
+ .setItemCode("NOT-EXIST")
740
+ .build();
741
+
742
+ assertThatThrownBy(() -> blockingStub.getItem(request))
743
+ .isInstanceOf(StatusRuntimeException.class)
744
+ .hasMessageContaining("NOT_FOUND");
745
+ }
746
+ }
747
+
748
+ @Nested
749
+ @DisplayName("StreamItems (Server Streaming)")
750
+ class StreamItemsTests {
751
+
752
+ @Test
753
+ @DisplayName("品目一覧をストリームで取得できる")
754
+ void shouldStreamItems() {
755
+ // Arrange
756
+ for (int i = 1; i <= 5; i++) {
757
+ insertTestItem("ITEM-" + String.format("%03d", i),
758
+ "品目" + i, ItemCategory.PRODUCT);
759
+ }
760
+
761
+ // Act
762
+ var request = GetItemsRequest.newBuilder().build();
763
+ Iterator<com.example.production.grpc.Item> iterator =
764
+ blockingStub.streamItems(request);
765
+
766
+ // Assert
767
+ List<com.example.production.grpc.Item> items = new ArrayList<>();
768
+ iterator.forEachRemaining(items::add);
769
+
770
+ assertThat(items).hasSize(5);
771
+ }
772
+ }
773
+
774
+ @Nested
775
+ @DisplayName("BatchCreateItems (Client Streaming)")
776
+ class BatchCreateItemsTests {
777
+
778
+ @Test
779
+ @DisplayName("バッチで品目を登録できる")
780
+ void shouldBatchCreateItems() throws InterruptedException {
781
+ CountDownLatch latch = new CountDownLatch(1);
782
+ final BatchCreateResponse[] result = new BatchCreateResponse[1];
783
+
784
+ var requestObserver = asyncStub.batchCreateItems(
785
+ new io.grpc.stub.StreamObserver<BatchCreateResponse>() {
786
+ @Override
787
+ public void onNext(BatchCreateResponse response) {
788
+ result[0] = response;
789
+ }
790
+
791
+ @Override
792
+ public void onError(Throwable t) {
793
+ latch.countDown();
794
+ }
795
+
796
+ @Override
797
+ public void onCompleted() {
798
+ latch.countDown();
799
+ }
800
+ });
801
+
802
+ // Act - 3件の品目を送信
803
+ for (int i = 1; i <= 3; i++) {
804
+ requestObserver.onNext(CreateItemRequest.newBuilder()
805
+ .setItemCode("BATCH-" + String.format("%03d", i))
806
+ .setItemName("バッチ品目" + i)
807
+ .setCategory(com.example.production.grpc.ItemCategory.PRODUCT)
808
+ .build());
809
+ }
810
+ requestObserver.onCompleted();
811
+
812
+ // Assert
813
+ assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue();
814
+ assertThat(result[0].getSuccessCount()).isEqualTo(3);
815
+ }
816
+ }
817
+
818
+ private void insertTestItem(String code, String name, ItemCategory category) {
819
+ itemMapper.insert(Item.builder()
820
+ .itemCode(code)
821
+ .effectiveDate(LocalDate.of(2025, 1, 1))
822
+ .itemName(name)
823
+ .category(category)
824
+ .build());
825
+ }
826
+ }
827
+ ```
828
+
829
+ </details>
830
+
831
+ #### Green: gRPC サービスの実装
832
+
833
+ <details>
834
+ <summary>ItemGrpcService.java</summary>
835
+
836
+ ```java
837
+ package com.example.production.infrastructure.grpc.service;
838
+
839
+ import com.example.production.application.port.in.*;
840
+ import com.example.production.domain.exception.DuplicateItemException;
841
+ import com.example.production.domain.exception.ItemNotFoundException;
842
+ import com.example.production.domain.model.item.Item;
843
+ import com.example.production.grpc.*;
844
+ import com.example.production.infrastructure.grpc.mapper.ProtoMapper;
845
+ import io.grpc.Status;
846
+ import io.grpc.stub.StreamObserver;
847
+ import net.devh.boot.grpc.server.service.GrpcService;
848
+ import org.springframework.transaction.annotation.Transactional;
849
+
850
+ import java.util.ArrayList;
851
+ import java.util.List;
852
+
853
+ /**
854
+ * 品目 gRPC サービス実装
855
+ * 既存の ItemUseCase を Input Adapter として呼び出す
856
+ */
857
+ @GrpcService
858
+ public class ItemGrpcService extends ItemServiceGrpc.ItemServiceImplBase {
859
+
860
+ private final ItemUseCase itemUseCase; // 既存の UseCase を注入
861
+ private final ProtoMapper mapper;
862
+
863
+ public ItemGrpcService(ItemUseCase itemUseCase, ProtoMapper mapper) {
864
+ this.itemUseCase = itemUseCase;
865
+ this.mapper = mapper;
866
+ }
867
+
868
+ /**
869
+ * 品目取得(Unary RPC)
870
+ */
871
+ @Override
872
+ public void getItem(GetItemRequest request,
873
+ StreamObserver<com.example.production.grpc.Item> responseObserver) {
874
+ try {
875
+ // 既存の UseCase を呼び出し
876
+ Item item = itemUseCase.getItemByCode(request.getItemCode());
877
+ responseObserver.onNext(mapper.toProto(item));
878
+ responseObserver.onCompleted();
879
+ } catch (ItemNotFoundException e) {
880
+ responseObserver.onError(Status.NOT_FOUND
881
+ .withDescription(e.getMessage())
882
+ .asRuntimeException());
883
+ }
884
+ }
885
+
886
+ /**
887
+ * 品目登録(Unary RPC)
888
+ */
889
+ @Override
890
+ @Transactional
891
+ public void createItem(CreateItemRequest request,
892
+ StreamObserver<com.example.production.grpc.Item> responseObserver) {
893
+ try {
894
+ // Proto → Command 変換
895
+ CreateItemCommand command = CreateItemCommand.builder()
896
+ .itemCode(request.getItemCode())
897
+ .itemName(request.getItemName())
898
+ .category(mapper.toDomainCategory(request.getCategory()))
899
+ .itemGroupCode(emptyToNull(request.getItemGroupCode()))
900
+ .unitCode(emptyToNull(request.getUnitCode()))
901
+ .locationCode(emptyToNull(request.getLocationCode()))
902
+ .leadTime(zeroToNull(request.getLeadTime()))
903
+ .safetyStock(zeroToNull(request.getSafetyStock()))
904
+ .build();
905
+
906
+ // 既存の UseCase を呼び出し
907
+ Item item = itemUseCase.createItem(command);
908
+ responseObserver.onNext(mapper.toProto(item));
909
+ responseObserver.onCompleted();
910
+ } catch (DuplicateItemException e) {
911
+ responseObserver.onError(Status.ALREADY_EXISTS
912
+ .withDescription(e.getMessage())
913
+ .asRuntimeException());
914
+ }
915
+ }
916
+
917
+ /**
918
+ * 品目更新(Unary RPC)
919
+ */
920
+ @Override
921
+ @Transactional
922
+ public void updateItem(UpdateItemRequest request,
923
+ StreamObserver<com.example.production.grpc.Item> responseObserver) {
924
+ try {
925
+ UpdateItemCommand command = UpdateItemCommand.builder()
926
+ .itemCode(request.getItemCode())
927
+ .itemName(emptyToNull(request.getItemName()))
928
+ .category(mapper.toDomainCategory(request.getCategory()))
929
+ .leadTime(zeroToNull(request.getLeadTime()))
930
+ .safetyStock(zeroToNull(request.getSafetyStock()))
931
+ .build();
932
+
933
+ Item item = itemUseCase.updateItem(command);
934
+ responseObserver.onNext(mapper.toProto(item));
935
+ responseObserver.onCompleted();
936
+ } catch (ItemNotFoundException e) {
937
+ responseObserver.onError(Status.NOT_FOUND
938
+ .withDescription(e.getMessage())
939
+ .asRuntimeException());
940
+ }
941
+ }
942
+
943
+ /**
944
+ * 品目削除(Unary RPC)
945
+ */
946
+ @Override
947
+ @Transactional
948
+ public void deleteItem(DeleteItemRequest request,
949
+ StreamObserver<Empty> responseObserver) {
950
+ try {
951
+ itemUseCase.deleteItem(request.getItemCode());
952
+ responseObserver.onNext(Empty.getDefaultInstance());
953
+ responseObserver.onCompleted();
954
+ } catch (ItemNotFoundException e) {
955
+ responseObserver.onError(Status.NOT_FOUND
956
+ .withDescription(e.getMessage())
957
+ .asRuntimeException());
958
+ }
959
+ }
960
+
961
+ /**
962
+ * 品目一覧のストリーム配信(Server Streaming RPC)
963
+ */
964
+ @Override
965
+ public void streamItems(GetItemsRequest request,
966
+ StreamObserver<com.example.production.grpc.Item> responseObserver) {
967
+ try {
968
+ List<Item> items;
969
+
970
+ if (request.getCategory() !=
971
+ com.example.production.grpc.ItemCategory.ITEM_CATEGORY_UNSPECIFIED) {
972
+ items = itemUseCase.getItemsByCategory(
973
+ mapper.toDomainCategory(request.getCategory()));
974
+ } else {
975
+ items = itemUseCase.getAllItems();
976
+ }
977
+
978
+ // ストリーミング配信
979
+ for (Item item : items) {
980
+ responseObserver.onNext(mapper.toProto(item));
981
+ }
982
+ responseObserver.onCompleted();
983
+ } catch (Exception e) {
984
+ responseObserver.onError(Status.INTERNAL
985
+ .withDescription(e.getMessage())
986
+ .asRuntimeException());
987
+ }
988
+ }
989
+
990
+ /**
991
+ * バッチ登録(Client Streaming RPC)
992
+ */
993
+ @Override
994
+ @Transactional
995
+ public StreamObserver<CreateItemRequest> batchCreateItems(
996
+ StreamObserver<BatchCreateResponse> responseObserver) {
997
+
998
+ return new StreamObserver<>() {
999
+ private final List<String> successCodes = new ArrayList<>();
1000
+ private final List<String> failedCodes = new ArrayList<>();
1001
+
1002
+ @Override
1003
+ public void onNext(CreateItemRequest request) {
1004
+ try {
1005
+ CreateItemCommand command = CreateItemCommand.builder()
1006
+ .itemCode(request.getItemCode())
1007
+ .itemName(request.getItemName())
1008
+ .category(mapper.toDomainCategory(request.getCategory()))
1009
+ .build();
1010
+
1011
+ itemUseCase.createItem(command);
1012
+ successCodes.add(request.getItemCode());
1013
+ } catch (Exception e) {
1014
+ failedCodes.add(request.getItemCode());
1015
+ }
1016
+ }
1017
+
1018
+ @Override
1019
+ public void onError(Throwable t) {
1020
+ responseObserver.onError(Status.INTERNAL
1021
+ .withDescription(t.getMessage())
1022
+ .asRuntimeException());
1023
+ }
1024
+
1025
+ @Override
1026
+ public void onCompleted() {
1027
+ responseObserver.onNext(BatchCreateResponse.newBuilder()
1028
+ .setSuccessCount(successCodes.size())
1029
+ .setFailedCount(failedCodes.size())
1030
+ .addAllFailedCodes(failedCodes)
1031
+ .build());
1032
+ responseObserver.onCompleted();
1033
+ }
1034
+ };
1035
+ }
1036
+
1037
+ private String emptyToNull(String value) {
1038
+ return value == null || value.isEmpty() ? null : value;
1039
+ }
1040
+
1041
+ private Integer zeroToNull(int value) {
1042
+ return value == 0 ? null : value;
1043
+ }
1044
+ }
1045
+ ```
1046
+
1047
+ </details>
1048
+
1049
+ ### 43.3 BOM gRPC サービスの実装
1050
+
1051
+ <details>
1052
+ <summary>BomGrpcService.java</summary>
1053
+
1054
+ ```java
1055
+ package com.example.production.infrastructure.grpc.service;
1056
+
1057
+ import com.example.production.application.service.BomNode;
1058
+ import com.example.production.application.service.BomService;
1059
+ import com.example.production.application.service.WhereUsedResult;
1060
+ import com.example.production.grpc.*;
1061
+ import com.example.production.infrastructure.grpc.mapper.ProtoMapper;
1062
+ import io.grpc.Status;
1063
+ import io.grpc.stub.StreamObserver;
1064
+ import net.devh.boot.grpc.server.service.GrpcService;
1065
+
1066
+ import java.util.List;
1067
+
1068
+ /**
1069
+ * BOM gRPC サービス実装
1070
+ * 既存の BomService を Input Adapter として呼び出す
1071
+ */
1072
+ @GrpcService
1073
+ public class BomGrpcService extends BomServiceGrpc.BomServiceImplBase {
1074
+
1075
+ private final BomService bomService; // 既存のサービスを注入
1076
+ private final ProtoMapper mapper;
1077
+
1078
+ public BomGrpcService(BomService bomService, ProtoMapper mapper) {
1079
+ this.bomService = bomService;
1080
+ this.mapper = mapper;
1081
+ }
1082
+
1083
+ /**
1084
+ * 部品展開(Server Streaming)
1085
+ */
1086
+ @Override
1087
+ public void explodeBom(ExplodeBomRequest request,
1088
+ StreamObserver<com.example.production.grpc.BomNode> responseObserver) {
1089
+ try {
1090
+ BomNode root = bomService.explodeBom(request.getItemCode());
1091
+
1092
+ // 深さ優先でストリーミング配信
1093
+ streamBomNode(root, responseObserver);
1094
+ responseObserver.onCompleted();
1095
+ } catch (Exception e) {
1096
+ responseObserver.onError(Status.INTERNAL
1097
+ .withDescription(e.getMessage())
1098
+ .asRuntimeException());
1099
+ }
1100
+ }
1101
+
1102
+ private void streamBomNode(BomNode node,
1103
+ StreamObserver<com.example.production.grpc.BomNode> observer) {
1104
+ observer.onNext(toProtoBomNode(node));
1105
+
1106
+ if (node.getChildren() != null) {
1107
+ for (BomNode child : node.getChildren()) {
1108
+ streamBomNode(child, observer);
1109
+ }
1110
+ }
1111
+ }
1112
+
1113
+ private com.example.production.grpc.BomNode toProtoBomNode(BomNode domain) {
1114
+ var builder = com.example.production.grpc.BomNode.newBuilder()
1115
+ .setItemCode(domain.getItemCode())
1116
+ .setItemName(domain.getItemName())
1117
+ .setRequiredQuantity(mapper.toProtoDecimal(domain.getRequiredQuantity()))
1118
+ .setLevel(domain.getLevel());
1119
+
1120
+ if (domain.getChildren() != null) {
1121
+ for (BomNode child : domain.getChildren()) {
1122
+ builder.addChildren(toProtoBomNode(child));
1123
+ }
1124
+ }
1125
+
1126
+ return builder.build();
1127
+ }
1128
+
1129
+ /**
1130
+ * 使用先照会
1131
+ */
1132
+ @Override
1133
+ public void whereUsed(WhereUsedRequest request,
1134
+ StreamObserver<WhereUsedResponse> responseObserver) {
1135
+ try {
1136
+ List<WhereUsedResult> results = bomService.whereUsed(request.getItemCode());
1137
+
1138
+ var response = WhereUsedResponse.newBuilder();
1139
+ for (WhereUsedResult result : results) {
1140
+ response.addResults(com.example.production.grpc.WhereUsedResult.newBuilder()
1141
+ .setParentItemCode(result.getParentItemCode())
1142
+ .setItemName(result.getItemName())
1143
+ .setRequiredQuantity(mapper.toProtoDecimal(result.getRequiredQuantity()))
1144
+ .build());
1145
+ }
1146
+
1147
+ responseObserver.onNext(response.build());
1148
+ responseObserver.onCompleted();
1149
+ } catch (Exception e) {
1150
+ responseObserver.onError(Status.INTERNAL
1151
+ .withDescription(e.getMessage())
1152
+ .asRuntimeException());
1153
+ }
1154
+ }
1155
+ }
1156
+ ```
1157
+
1158
+ </details>
1159
+
1160
+ ---
1161
+
1162
+ ## 第44章:トランザクション API の実装
1163
+
1164
+ ### 44.1 発注 gRPC サービス
1165
+
1166
+ <details>
1167
+ <summary>src/main/proto/purchase_order.proto</summary>
1168
+
1169
+ ```protobuf
1170
+ syntax = "proto3";
1171
+
1172
+ package production;
1173
+
1174
+ import "common.proto";
1175
+
1176
+ option java_package = "com.example.production.grpc";
1177
+ option java_multiple_files = true;
1178
+
1179
+ // 発注ステータス
1180
+ enum OrderStatus {
1181
+ ORDER_STATUS_UNSPECIFIED = 0;
1182
+ DRAFT = 1;
1183
+ CONFIRMED = 2;
1184
+ CANCELLED = 3;
1185
+ COMPLETED = 4;
1186
+ }
1187
+
1188
+ // 発注ヘッダ
1189
+ message PurchaseOrder {
1190
+ string order_number = 1;
1191
+ string supplier_code = 2;
1192
+ Date order_date = 3;
1193
+ OrderStatus status = 4;
1194
+ repeated PurchaseOrderDetail details = 5;
1195
+ Decimal total_amount = 6;
1196
+ }
1197
+
1198
+ // 発注明細
1199
+ message PurchaseOrderDetail {
1200
+ int32 line_number = 1;
1201
+ string item_code = 2;
1202
+ Decimal order_quantity = 3;
1203
+ Decimal unit_price = 4;
1204
+ Date delivery_date = 5;
1205
+ Decimal received_quantity = 6;
1206
+ }
1207
+
1208
+ // リクエスト
1209
+ message GetOrderRequest {
1210
+ string order_number = 1;
1211
+ }
1212
+
1213
+ message GetOrdersRequest {
1214
+ OrderStatus status = 1;
1215
+ PageRequest page = 2;
1216
+ }
1217
+
1218
+ message CreateOrderRequest {
1219
+ string supplier_code = 1;
1220
+ repeated CreateOrderDetailRequest details = 2;
1221
+ }
1222
+
1223
+ message CreateOrderDetailRequest {
1224
+ string item_code = 1;
1225
+ Decimal order_quantity = 2;
1226
+ Decimal unit_price = 3;
1227
+ Date delivery_date = 4;
1228
+ }
1229
+
1230
+ message ConfirmOrderRequest {
1231
+ string order_number = 1;
1232
+ }
1233
+
1234
+ // 入荷登録(双方向ストリーミング)
1235
+ message RecordReceivingRequest {
1236
+ string order_number = 1;
1237
+ int32 line_number = 2;
1238
+ Decimal received_quantity = 3;
1239
+ Date receiving_date = 4;
1240
+ }
1241
+
1242
+ message RecordReceivingResponse {
1243
+ string order_number = 1;
1244
+ int32 line_number = 2;
1245
+ Decimal total_received = 3;
1246
+ bool is_completed = 4;
1247
+ }
1248
+
1249
+ // 発注サービス
1250
+ service PurchaseOrderService {
1251
+ rpc GetOrder(GetOrderRequest) returns (PurchaseOrder);
1252
+ rpc StreamOrders(GetOrdersRequest) returns (stream PurchaseOrder);
1253
+ rpc CreateOrder(CreateOrderRequest) returns (PurchaseOrder);
1254
+ rpc ConfirmOrder(ConfirmOrderRequest) returns (PurchaseOrder);
1255
+ rpc CancelOrder(GetOrderRequest) returns (Empty);
1256
+
1257
+ // 入荷登録(双方向ストリーミング)
1258
+ rpc RecordReceiving(stream RecordReceivingRequest) returns (stream RecordReceivingResponse);
1259
+ }
1260
+ ```
1261
+
1262
+ </details>
1263
+
1264
+ <details>
1265
+ <summary>PurchaseOrderGrpcService.java</summary>
1266
+
1267
+ ```java
1268
+ package com.example.production.infrastructure.grpc.service;
1269
+
1270
+ import com.example.production.application.port.in.*;
1271
+ import com.example.production.domain.model.purchase.PurchaseOrder;
1272
+ import com.example.production.grpc.*;
1273
+ import com.example.production.infrastructure.grpc.mapper.ProtoMapper;
1274
+ import io.grpc.Status;
1275
+ import io.grpc.stub.StreamObserver;
1276
+ import net.devh.boot.grpc.server.service.GrpcService;
1277
+ import org.springframework.transaction.annotation.Transactional;
1278
+
1279
+ import java.util.List;
1280
+
1281
+ /**
1282
+ * 発注 gRPC サービス実装
1283
+ * 既存の PurchaseOrderUseCase を Input Adapter として呼び出す
1284
+ */
1285
+ @GrpcService
1286
+ public class PurchaseOrderGrpcService
1287
+ extends PurchaseOrderServiceGrpc.PurchaseOrderServiceImplBase {
1288
+
1289
+ private final PurchaseOrderUseCase useCase; // 既存の UseCase
1290
+ private final ProtoMapper mapper;
1291
+
1292
+ public PurchaseOrderGrpcService(PurchaseOrderUseCase useCase, ProtoMapper mapper) {
1293
+ this.useCase = useCase;
1294
+ this.mapper = mapper;
1295
+ }
1296
+
1297
+ @Override
1298
+ public void getOrder(GetOrderRequest request,
1299
+ StreamObserver<com.example.production.grpc.PurchaseOrder> responseObserver) {
1300
+ try {
1301
+ PurchaseOrder order = useCase.getOrder(request.getOrderNumber());
1302
+ responseObserver.onNext(toProto(order));
1303
+ responseObserver.onCompleted();
1304
+ } catch (Exception e) {
1305
+ responseObserver.onError(Status.NOT_FOUND
1306
+ .withDescription(e.getMessage())
1307
+ .asRuntimeException());
1308
+ }
1309
+ }
1310
+
1311
+ @Override
1312
+ public void streamOrders(GetOrdersRequest request,
1313
+ StreamObserver<com.example.production.grpc.PurchaseOrder> responseObserver) {
1314
+ try {
1315
+ List<PurchaseOrder> orders = useCase.getAllOrders();
1316
+
1317
+ for (PurchaseOrder order : orders) {
1318
+ responseObserver.onNext(toProto(order));
1319
+ }
1320
+ responseObserver.onCompleted();
1321
+ } catch (Exception e) {
1322
+ responseObserver.onError(Status.INTERNAL
1323
+ .withDescription(e.getMessage())
1324
+ .asRuntimeException());
1325
+ }
1326
+ }
1327
+
1328
+ @Override
1329
+ @Transactional
1330
+ public void createOrder(CreateOrderRequest request,
1331
+ StreamObserver<com.example.production.grpc.PurchaseOrder> responseObserver) {
1332
+ try {
1333
+ CreatePurchaseOrderCommand command = CreatePurchaseOrderCommand.builder()
1334
+ .supplierCode(request.getSupplierCode())
1335
+ .details(request.getDetailsList().stream()
1336
+ .map(d -> CreatePurchaseOrderCommand.PurchaseOrderDetailCommand.builder()
1337
+ .itemCode(d.getItemCode())
1338
+ .orderQuantity(mapper.toDomainDecimal(d.getOrderQuantity()))
1339
+ .unitPrice(mapper.toDomainDecimal(d.getUnitPrice()))
1340
+ .deliveryDate(mapper.toDomainDate(d.getDeliveryDate()))
1341
+ .build())
1342
+ .toList())
1343
+ .build();
1344
+
1345
+ PurchaseOrder order = useCase.createOrder(command);
1346
+ responseObserver.onNext(toProto(order));
1347
+ responseObserver.onCompleted();
1348
+ } catch (Exception e) {
1349
+ responseObserver.onError(Status.INTERNAL
1350
+ .withDescription(e.getMessage())
1351
+ .asRuntimeException());
1352
+ }
1353
+ }
1354
+
1355
+ /**
1356
+ * 入荷登録(双方向ストリーミング)
1357
+ */
1358
+ @Override
1359
+ public StreamObserver<RecordReceivingRequest> recordReceiving(
1360
+ StreamObserver<RecordReceivingResponse> responseObserver) {
1361
+
1362
+ return new StreamObserver<>() {
1363
+ @Override
1364
+ public void onNext(RecordReceivingRequest request) {
1365
+ try {
1366
+ var result = useCase.recordReceiving(
1367
+ request.getOrderNumber(),
1368
+ request.getLineNumber(),
1369
+ mapper.toDomainDecimal(request.getReceivedQuantity()),
1370
+ mapper.toDomainDate(request.getReceivingDate())
1371
+ );
1372
+
1373
+ // 即座にレスポンス
1374
+ responseObserver.onNext(RecordReceivingResponse.newBuilder()
1375
+ .setOrderNumber(request.getOrderNumber())
1376
+ .setLineNumber(request.getLineNumber())
1377
+ .setTotalReceived(mapper.toProtoDecimal(result.getTotalReceived()))
1378
+ .setIsCompleted(result.isCompleted())
1379
+ .build());
1380
+ } catch (Exception e) {
1381
+ responseObserver.onNext(RecordReceivingResponse.newBuilder()
1382
+ .setOrderNumber(request.getOrderNumber())
1383
+ .setLineNumber(request.getLineNumber())
1384
+ .setIsCompleted(false)
1385
+ .build());
1386
+ }
1387
+ }
1388
+
1389
+ @Override
1390
+ public void onError(Throwable t) {
1391
+ responseObserver.onError(Status.INTERNAL
1392
+ .withDescription(t.getMessage())
1393
+ .asRuntimeException());
1394
+ }
1395
+
1396
+ @Override
1397
+ public void onCompleted() {
1398
+ responseObserver.onCompleted();
1399
+ }
1400
+ };
1401
+ }
1402
+
1403
+ private com.example.production.grpc.PurchaseOrder toProto(PurchaseOrder domain) {
1404
+ var builder = com.example.production.grpc.PurchaseOrder.newBuilder()
1405
+ .setOrderNumber(domain.getOrderNumber())
1406
+ .setSupplierCode(domain.getSupplierCode())
1407
+ .setOrderDate(mapper.toProtoDate(domain.getOrderDate()))
1408
+ .setStatus(toProtoStatus(domain.getStatus()))
1409
+ .setTotalAmount(mapper.toProtoDecimal(domain.getTotalAmount()));
1410
+
1411
+ if (domain.getDetails() != null) {
1412
+ for (var detail : domain.getDetails()) {
1413
+ builder.addDetails(PurchaseOrderDetail.newBuilder()
1414
+ .setLineNumber(detail.getLineNumber())
1415
+ .setItemCode(detail.getItemCode())
1416
+ .setOrderQuantity(mapper.toProtoDecimal(detail.getOrderQuantity()))
1417
+ .setUnitPrice(mapper.toProtoDecimal(detail.getUnitPrice()))
1418
+ .setDeliveryDate(mapper.toProtoDate(detail.getDeliveryDate()))
1419
+ .setReceivedQuantity(mapper.toProtoDecimal(detail.getReceivedQuantity()))
1420
+ .build());
1421
+ }
1422
+ }
1423
+
1424
+ return builder.build();
1425
+ }
1426
+
1427
+ private OrderStatus toProtoStatus(
1428
+ com.example.production.domain.model.purchase.OrderStatus domain) {
1429
+ return switch (domain) {
1430
+ case DRAFT -> OrderStatus.DRAFT;
1431
+ case CONFIRMED -> OrderStatus.CONFIRMED;
1432
+ case CANCELLED -> OrderStatus.CANCELLED;
1433
+ case COMPLETED -> OrderStatus.COMPLETED;
1434
+ };
1435
+ }
1436
+ }
1437
+ ```
1438
+
1439
+ </details>
1440
+
1441
+ ### 44.2 MRP gRPC サービス
1442
+
1443
+ <details>
1444
+ <summary>MrpGrpcService.java</summary>
1445
+
1446
+ ```java
1447
+ package com.example.production.infrastructure.grpc.service;
1448
+
1449
+ import com.example.production.application.service.MrpService;
1450
+ import com.example.production.grpc.*;
1451
+ import com.example.production.infrastructure.grpc.mapper.ProtoMapper;
1452
+ import io.grpc.stub.StreamObserver;
1453
+ import net.devh.boot.grpc.server.service.GrpcService;
1454
+
1455
+ import java.util.concurrent.CompletableFuture;
1456
+ import java.util.concurrent.Executors;
1457
+
1458
+ /**
1459
+ * MRP gRPC サービス実装
1460
+ * 既存の MrpService を Input Adapter として呼び出す
1461
+ */
1462
+ @GrpcService
1463
+ public class MrpGrpcService extends MrpServiceGrpc.MrpServiceImplBase {
1464
+
1465
+ private final MrpService mrpService; // 既存のサービス
1466
+ private final ProtoMapper mapper;
1467
+
1468
+ public MrpGrpcService(MrpService mrpService, ProtoMapper mapper) {
1469
+ this.mrpService = mrpService;
1470
+ this.mapper = mapper;
1471
+ }
1472
+
1473
+ /**
1474
+ * MRP 実行(進捗をストリーミング)
1475
+ */
1476
+ @Override
1477
+ public void executeMrp(ExecuteMrpRequest request,
1478
+ StreamObserver<MrpProgress> responseObserver) {
1479
+
1480
+ var executor = Executors.newSingleThreadExecutor();
1481
+
1482
+ CompletableFuture.runAsync(() -> {
1483
+ try {
1484
+ // フェーズ1: 需要取得
1485
+ sendProgress(responseObserver, "需要取得", 0, 4,
1486
+ "基準生産計画から需要を取得中...");
1487
+
1488
+ // フェーズ2: BOM 展開
1489
+ sendProgress(responseObserver, "BOM展開", 1, 4,
1490
+ "部品構成表を展開中...");
1491
+
1492
+ // フェーズ3: 正味所要量計算
1493
+ sendProgress(responseObserver, "正味所要量計算", 2, 4,
1494
+ "在庫と照合して正味所要量を計算中...");
1495
+
1496
+ // フェーズ4: 計画オーダ生成
1497
+ sendProgress(responseObserver, "計画オーダ生成", 3, 4,
1498
+ "ロットサイズを考慮して計画オーダを生成中...");
1499
+
1500
+ // 実際の MRP 実行
1501
+ var startDate = mapper.toDomainDate(request.getStartDate());
1502
+ var endDate = mapper.toDomainDate(request.getEndDate());
1503
+ mrpService.execute(startDate, endDate);
1504
+
1505
+ // 完了
1506
+ sendProgress(responseObserver, "完了", 4, 4,
1507
+ "MRP 実行が完了しました");
1508
+ responseObserver.onCompleted();
1509
+ } catch (Exception e) {
1510
+ responseObserver.onError(io.grpc.Status.INTERNAL
1511
+ .withDescription(e.getMessage())
1512
+ .asRuntimeException());
1513
+ }
1514
+ }, executor).whenComplete((v, t) -> executor.shutdown());
1515
+ }
1516
+
1517
+ private void sendProgress(StreamObserver<MrpProgress> observer,
1518
+ String phase, int current, int total, String message) {
1519
+ observer.onNext(MrpProgress.newBuilder()
1520
+ .setPhase(phase)
1521
+ .setCurrent(current)
1522
+ .setTotal(total)
1523
+ .setMessage(message)
1524
+ .build());
1525
+ }
1526
+
1527
+ /**
1528
+ * MRP 実行(同期)
1529
+ */
1530
+ @Override
1531
+ public void executeMrpSync(ExecuteMrpRequest request,
1532
+ StreamObserver<MrpResult> responseObserver) {
1533
+ try {
1534
+ var startDate = mapper.toDomainDate(request.getStartDate());
1535
+ var endDate = mapper.toDomainDate(request.getEndDate());
1536
+
1537
+ long startTime = System.currentTimeMillis();
1538
+ var result = mrpService.execute(startDate, endDate);
1539
+ long executionTime = System.currentTimeMillis() - startTime;
1540
+
1541
+ var response = MrpResult.newBuilder()
1542
+ .setPeriodStart(request.getStartDate())
1543
+ .setPeriodEnd(request.getEndDate())
1544
+ .setStatistics(MrpStatistics.newBuilder()
1545
+ .setTotalItemsProcessed(result.getPlannedOrders().size())
1546
+ .setShortageItemCount(result.getShortageItems().size())
1547
+ .setExecutionTimeMs(executionTime)
1548
+ .build());
1549
+
1550
+ for (var order : result.getPlannedOrders()) {
1551
+ response.addPlannedOrders(toProtoPlannedOrder(order));
1552
+ }
1553
+
1554
+ for (var item : result.getShortageItems()) {
1555
+ response.addShortageItems(toProtoShortageItem(item));
1556
+ }
1557
+
1558
+ responseObserver.onNext(response.build());
1559
+ responseObserver.onCompleted();
1560
+ } catch (Exception e) {
1561
+ responseObserver.onError(io.grpc.Status.INTERNAL
1562
+ .withDescription(e.getMessage())
1563
+ .asRuntimeException());
1564
+ }
1565
+ }
1566
+
1567
+ private PlannedOrder toProtoPlannedOrder(
1568
+ com.example.production.application.service.PlannedOrder domain) {
1569
+ return PlannedOrder.newBuilder()
1570
+ .setItemCode(domain.getItemCode())
1571
+ .setItemName(domain.getItemName())
1572
+ .setQuantity(mapper.toProtoDecimal(domain.getQuantity()))
1573
+ .setDueDate(mapper.toProtoDate(domain.getDueDate()))
1574
+ .build();
1575
+ }
1576
+
1577
+ private ShortageItem toProtoShortageItem(
1578
+ com.example.production.application.service.ShortageItem domain) {
1579
+ return ShortageItem.newBuilder()
1580
+ .setItemCode(domain.getItemCode())
1581
+ .setItemName(domain.getItemName())
1582
+ .setShortageQuantity(mapper.toProtoDecimal(domain.getShortageQuantity()))
1583
+ .setRecommendedOrderDate(mapper.toProtoDate(domain.getRecommendedOrderDate()))
1584
+ .build();
1585
+ }
1586
+ }
1587
+ ```
1588
+
1589
+ </details>
1590
+
1591
+ ---
1592
+
1593
+ ## 第45章:エラーハンドリングとストリーミング
1594
+
1595
+ ### 45.1 gRPC ステータスコード
1596
+
1597
+ gRPC は標準化されたステータスコードを使用します:
1598
+
1599
+ | コード | 説明 | 使用例 |
1600
+ |--------|------|--------|
1601
+ | `OK` | 成功 | 正常完了 |
1602
+ | `INVALID_ARGUMENT` | 無効な引数 | バリデーションエラー |
1603
+ | `NOT_FOUND` | 見つからない | 品目が存在しない |
1604
+ | `ALREADY_EXISTS` | 既に存在 | 品目コード重複 |
1605
+ | `FAILED_PRECONDITION` | 前提条件エラー | 発注確定済みの取消 |
1606
+ | `INTERNAL` | 内部エラー | サーバー側エラー |
1607
+
1608
+ ### 45.2 グローバルインターセプター
1609
+
1610
+ <details>
1611
+ <summary>LoggingInterceptor.java</summary>
1612
+
1613
+ ```java
1614
+ package com.example.production.infrastructure.grpc.interceptor;
1615
+
1616
+ import io.grpc.*;
1617
+ import net.devh.boot.grpc.server.interceptor.GrpcGlobalServerInterceptor;
1618
+ import org.slf4j.Logger;
1619
+ import org.slf4j.LoggerFactory;
1620
+
1621
+ import java.time.Duration;
1622
+ import java.time.Instant;
1623
+
1624
+ /**
1625
+ * ロギング & エラーハンドリングインターセプター
1626
+ */
1627
+ @GrpcGlobalServerInterceptor
1628
+ public class LoggingInterceptor implements ServerInterceptor {
1629
+
1630
+ private static final Logger log = LoggerFactory.getLogger(LoggingInterceptor.class);
1631
+
1632
+ @Override
1633
+ public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
1634
+ ServerCall<ReqT, RespT> call,
1635
+ Metadata headers,
1636
+ ServerCallHandler<ReqT, RespT> next) {
1637
+
1638
+ String methodName = call.getMethodDescriptor().getFullMethodName();
1639
+ Instant startTime = Instant.now();
1640
+
1641
+ log.info("gRPC Request: {}", methodName);
1642
+
1643
+ ServerCall<ReqT, RespT> wrappedCall = new ForwardingServerCall
1644
+ .SimpleForwardingServerCall<>(call) {
1645
+ @Override
1646
+ public void close(Status status, Metadata trailers) {
1647
+ Duration duration = Duration.between(startTime, Instant.now());
1648
+ log.info("gRPC Response: {} - Status: {} - Duration: {}ms",
1649
+ methodName, status.getCode(), duration.toMillis());
1650
+ super.close(status, trailers);
1651
+ }
1652
+ };
1653
+
1654
+ return next.startCall(wrappedCall, headers);
1655
+ }
1656
+ }
1657
+ ```
1658
+
1659
+ </details>
1660
+
1661
+ ### 45.3 ヘルスチェックの実装
1662
+
1663
+ <details>
1664
+ <summary>HealthGrpcService.java</summary>
1665
+
1666
+ ```java
1667
+ package com.example.production.infrastructure.grpc.service;
1668
+
1669
+ import io.grpc.health.v1.HealthCheckRequest;
1670
+ import io.grpc.health.v1.HealthCheckResponse;
1671
+ import io.grpc.health.v1.HealthGrpc;
1672
+ import io.grpc.stub.StreamObserver;
1673
+ import net.devh.boot.grpc.server.service.GrpcService;
1674
+
1675
+ import javax.sql.DataSource;
1676
+ import java.sql.Connection;
1677
+
1678
+ /**
1679
+ * gRPC ヘルスチェックサービス
1680
+ */
1681
+ @GrpcService
1682
+ public class HealthGrpcService extends HealthGrpc.HealthImplBase {
1683
+
1684
+ private final DataSource dataSource;
1685
+
1686
+ public HealthGrpcService(DataSource dataSource) {
1687
+ this.dataSource = dataSource;
1688
+ }
1689
+
1690
+ @Override
1691
+ public void check(HealthCheckRequest request,
1692
+ StreamObserver<HealthCheckResponse> responseObserver) {
1693
+
1694
+ HealthCheckResponse.ServingStatus status = checkHealth()
1695
+ ? HealthCheckResponse.ServingStatus.SERVING
1696
+ : HealthCheckResponse.ServingStatus.NOT_SERVING;
1697
+
1698
+ responseObserver.onNext(HealthCheckResponse.newBuilder()
1699
+ .setStatus(status)
1700
+ .build());
1701
+ responseObserver.onCompleted();
1702
+ }
1703
+
1704
+ private boolean checkHealth() {
1705
+ try (Connection conn = dataSource.getConnection()) {
1706
+ return conn.isValid(5);
1707
+ } catch (Exception e) {
1708
+ return false;
1709
+ }
1710
+ }
1711
+ }
1712
+ ```
1713
+
1714
+ </details>
1715
+
1716
+ ### 45.4 設定ファイル
1717
+
1718
+ <details>
1719
+ <summary>application.yml(gRPC 追加設定)</summary>
1720
+
1721
+ ```yaml
1722
+ grpc:
1723
+ server:
1724
+ port: 9090
1725
+ reflection-service-enabled: true # 開発時にリフレクション有効化
1726
+
1727
+ # 既存の設定はそのまま
1728
+ spring:
1729
+ datasource:
1730
+ url: jdbc:postgresql://localhost:5432/production
1731
+ username: postgres
1732
+ password: postgres
1733
+
1734
+ mybatis:
1735
+ mapper-locations: classpath:mapper/*.xml
1736
+ ```
1737
+
1738
+ </details>
1739
+
1740
+ ### 45.5 gRPC クライアントからの呼び出し
1741
+
1742
+ ```bash
1743
+ # サービス一覧
1744
+ grpcurl -plaintext localhost:9090 list
1745
+
1746
+ # 品目取得
1747
+ grpcurl -plaintext -d '{"item_code": "PROD-001"}' \
1748
+ localhost:9090 production.ItemService/GetItem
1749
+
1750
+ # 品目一覧(ストリーミング)
1751
+ grpcurl -plaintext \
1752
+ localhost:9090 production.ItemService/StreamItems
1753
+ ```
1754
+
1755
+ ---
1756
+
1757
+ ## まとめ
1758
+
1759
+ 本研究では、gRPC による生産管理システム API を実装しました。
1760
+
1761
+ ### API サーバー版との比較
1762
+
1763
+ | 観点 | REST API(第32章) | gRPC(本研究) |
1764
+ |------|-------------------|-----------------|
1765
+ | **プロトコル** | HTTP/1.1 + JSON | HTTP/2 + Protobuf |
1766
+ | **スキーマ** | OpenAPI(任意) | .proto(必須) |
1767
+ | **ストリーミング** | WebSocket 別実装 | ネイティブ |
1768
+ | **パフォーマンス** | 標準 | 高速 |
1769
+ | **ドメイン層** | 共有 | 共有 |
1770
+ | **アプリケーション層** | 共有 | 共有 |
1771
+ | **Input Adapter** | REST Controller | gRPC Service |
1772
+
1773
+ ### 実装した gRPC サービス
1774
+
1775
+ | サービス | メソッド | パターン |
1776
+ |---------|---------|---------|
1777
+ | **ItemService** | GetItem, CreateItem, UpdateItem, DeleteItem | Unary |
1778
+ | | StreamItems | Server Streaming |
1779
+ | | BatchCreateItems | Client Streaming |
1780
+ | **BomService** | ExplodeBom | Server Streaming |
1781
+ | | WhereUsed | Unary |
1782
+ | **PurchaseOrderService** | GetOrder, CreateOrder, ConfirmOrder | Unary |
1783
+ | | StreamOrders | Server Streaming |
1784
+ | | RecordReceiving | Bidirectional |
1785
+ | **MrpService** | ExecuteMrp | Server Streaming |
1786
+ | | ExecuteMrpSync | Unary |
1787
+
1788
+ ### 技術スタック
1789
+
1790
+ - **grpc-spring-boot-starter**: Spring Boot 統合
1791
+ - **Protocol Buffers 3**: スキーマ定義
1792
+ - **io.grpc**: gRPC Java 実装
1793
+ - **gRPC Health Check**: ヘルスチェック
1794
+
1795
+ ### gRPC を選択すべき場面
1796
+
1797
+ 1. **マイクロサービス間通信**: 高パフォーマンスが必要
1798
+ 2. **リアルタイム通信**: 進捗通知、チャット等
1799
+ 3. **大量データ転送**: ストリーミングで効率的に
1800
+ 4. **多言語クライアント**: Proto からコード生成
1801
+ 5. **型安全性重視**: スキーマ駆動開発
1802
+
1803
+ ---
1804
+
1805
+ [目次へ戻る](../index.md)