分散システムにおいてサービス間通信を実現するには、HTTPクライアントライブラリの活用が有効です。SpringフレームワークはRestTemplateというAPIを提供しており、HTTPリクエストの送信を簡潔に実装できます。
RestTemplateによるリクエスト送信は、フロントエンドのAJAXと同様に以下の4要素を必要とします:
- ① HTTPメソッド(GET/POSTなど)
- ② アクセス先URL
- ③ パラメータ情報
- ④ 戻り値の型定義
実装例:
1. Bean登録(Springコンテナへの登録)
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestClientConfig {
@Bean
public RestTemplate restClient() {
return new RestTemplate();
}
}
2. リクエスト処理クラス(商品情報取得例)
private void fetchProductDetails(List cartEntries) {
// TODO 1. 商品IDの抽出
Set productIds = cartEntries.stream()
.map(CartEntry::getItemId)
.collect(Collectors.toSet());
// 2. 商品情報を取得
ResponseEntity> response = restClient.exchange(
"http://api.product-service/v1/products?ids={ids}",
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<ProductData>>(){},
Map.of("ids", String.join(",", productIds.stream().map(String::valueOf).collect(Collectors.toList())))
);
// 3. レスポンス処理
if(!response.getStatusCode().is2xxSuccessful()) {
// エラー時処理
return;
}
List products = response.getBody();
if(Objects.isNull(products) || products.isEmpty()) {
return;
}
// 4. データマッピング
Map<Long, ProductData> productMap = products.stream()
.collect(Collectors.toMap(ProductData::getId, Function.identity()));
// 5. カート情報更新
for(CartEntry entry : cartEntries) {
ProductData data = productMap.get(entry.getItemId());
if(Objects.nonNull(data)) {
entry.setPrice(data.getPrice());
entry.setStatus(data.getStatus());
entry.setStock(data.getStock());
}
}
}
基本的な使用フロー:
- SpringコンテナへのRestTemplate登録
- 主なメソッド一覧:
- getForObject:GETリクエストでオブジェクト取得
- postForEntity:POSTリクエスト送信
- put:PUTリクエスト送信
- delete:DELETEリクエスト送信
- exchange:汎用リクエスト送信(ResponseEntity返却)