Spring Cloudの概要
Spring Cloudは分散システムインフラストラクチャ開発を簡素化するフレームワーク群です。サービスディスカバリ、設定管理、メッセージングなどの機能をSpring Bootスタイルで実装でき、既存の安定したサービスフレームワークを統合しています。
サービス間通信
異なるサービス間でデータを連携する例として、注文サービスがユーザーサービスから情報を取得するシナリオを考えます。RestTemplateを使用したHTTP通信実装例:
@Bean
public RestTemplate restTemplateBuilder() {
return new RestTemplate();
}
@Service
public class OrderService {
@Autowired
private RestTemplate restTemplate;
public Order fetchOrderDetails(Long orderId) {
Order order = orderRepository.retrieveById(orderId);
String apiEndpoint = "http://localhost:8081/users/" + order.getUserId();
User userData = restTemplate.getForObject(apiEndpoint, User.class);
order.setUserDetails(userData);
return order;
}
}
サービスディスカバリ(Eureka)
サービス登録と発見のメカニズムを提供します。クライアント実装例:
@SpringBootApplication
@EnableEurekaClient
public class UserServiceApp {
public static void main(String[] args) {
SpringApplication.run(UserServiceApp.class, args);
}
}
設定ファイル(application.yml):
spring:
application:
name: user-service
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
Nacosによる設定管理
設定の集中管理と動的更新を実現します。Bootstrap設定例:
spring:
application:
name: config-demo
cloud:
nacos:
config:
server-addr: 127.0.0.1:8848
file-extension: yaml
Feignクライアント
宣言型サービス呼び出しを簡素化します。実装例:
@FeignClient(name = "inventory-service")
public interface StockClient {
@GetMapping("/stock/{itemId}")
ItemStock checkAvailability(@PathVariable("itemId") String itemId);
}
APIゲートウェイ(Spring Cloud Gateway)
ルーティング設定例:
spring:
cloud:
gateway:
routes:
- id: payment-route
uri: lb://payment-service
predicates:
- Path=/payments/**
カスタムフィルター実装:
@Component
public class AuthFilter implements GlobalFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String authToken = exchange.getRequest().getHeaders().getFirst("Authorization");
if (validateToken(authToken)) {
return chain.filter(exchange);
}
exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
return exchange.getResponse().setComplete();
}
}