サービスディスカバリの基本概念
分散システムにおけるサービスディスカバリは、動的なサービス位置特定と通信を実現する基盤技術です。Eurekaはこの機能を提供するオープンソースツールであり、サービス登録センターとして機能します。
Eurekaサーバの構築
依存関係の追加
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
設定ファイル
server:
port: 8761
eureka:
client:
self-registration: false
registry-fetch: false
起動クラス
package com.example.discovery;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class DiscoveryServerApp {
public static void main(String[] args) {
SpringApplication.run(DiscoveryServerApp.class, args);
}
}
クライアントサービスの登録
クライアント依存関係
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
クライアント設定
spring:
application:
name: api-service
eureka:
client:
service-url:
registry-url: http://localhost:8761/eureka/
クライアント起動クラス
package com.example.apiservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class ApiServiceApp {
public static void main(String[] args) {
SpringApplication.run(ApiServiceApp.class, args);
}
}
サービス間通信の実装
Feignクライアントの設定
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
APIクライアントインターフェース
package com.example.apiservice.client;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(name = "user-service")
public interface UserServiceClient {
@GetMapping("/users/{id}")
User getUserDetails(@PathVariable Long id);
}
サービス呼び出しの実装
package com.example.apiservice.controller;
import com.example.apiservice.client.UserServiceClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserServiceClient userServiceClient;
@GetMapping("/user-profile/{id}")
public UserProfile getUserProfile(@PathVariable Long id) {
return userServiceClient.getUserDetails(id);
}
}
動作検証方法
Eurekaダッシュボード(http://localhost:8761)に登録サービスが表示された後、APIエンドポイントを通してサービス間通信を検証します。