Spring Cloud マイクロサービスアーキテクチャの実装例

親プロジェクトの構成

Mavenの親プロジェクトは、サブモジュール間で依存関係とバージョンを一元管理します。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
         https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>cloud-parent</artifactId>
    <version>1.0.0</version>
    <packaging>pom</packaging>

    <modules>
        <module>registry-server</module>
        <module>config-server</module>
        <module>gateway-service</module>
        <module>service-a</module>
        <module>service-b</module>
        <module>common-lib</module>
    </modules>

    <properties>
        <spring-boot.version>2.3.4.RELEASE</spring-boot.version>
        <spring-cloud.version>Hoxton.RELEASE</spring-cloud.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

共通ライブラリモジュール

共通のデータ構造とユーティリティクラスを提供するモジュールです。

package com.example.common;

import java.util.HashMap;
import java.util.Map;

public class ResponseWrapper {
    private int status;
    private String message;
    private Map<String, Object> data = new HashMap<>();

    public static ResponseWrapper success() {
        ResponseWrapper response = new ResponseWrapper();
        response.setStatus(200);
        response.setMessage("成功");
        return response;
    }

    public ResponseWrapper addData(String key, Object value) {
        this.data.put(key, value);
        return this;
    }
    
    // ゲッターとセッター
}

サービスレジストリの設定

Eurekaサーバーによるサービスディスカバリの実装例です。

@SpringBootApplication
@EnableEurekaServer
public class RegistryApplication {
    public static void main(String[] args) {
        SpringApplication.run(RegistryApplication.class, args);
    }
}
server:
  port: 8761
eureka:
  client:
    register-with-eureka: false
    fetch-registry: false

設定サーバーの実装

Gitベースの外部設定管理を提供します。

@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication.class, args);
    }
}

APIゲートウェイの実装

Zuulを使用したルーティングとフィルタリングの例です。

@Component
public class AuthFilter extends ZuulFilter {
    
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String authToken = request.getHeader("Authorization");
        
        if (authToken != null) {
            context.addZuulRequestHeader("Authorization", authToken);
        }
        return null;
    }
}

サービス間通信の実装

Feignクライアントを使用したサービス間呼び出しの例です。

@FeignClient(name = "service-a", fallback = ServiceAClientFallback.class)
public interface ServiceAClient {
    @GetMapping("/api/data/{id}")
    ResponseWrapper getData(@PathVariable("id") Long id);
}

@Component
public class ServiceAClientFallback implements ServiceAClient {
    @Override
    public ResponseWrapper getData(Long id) {
        return ResponseWrapper.fail().addData("error", "サービスが利用できません");
    }
}

タグ: Spring Cloud マイクロサービス Eureka Zuul Feign

6月20日 20:23 投稿