Spring Boot を使用した最初のマイクロサービス システムの構築: 初心者ガイド

WBOY
リリース: 2024-08-12 22:47:32
オリジナル
750 人が閲覧しました

Building Your First Microservice System with Spring Boot: A Beginners Guide

導入

このガイドでは、Spring Boot を使用したシンプルかつ包括的なマイクロサービス システムの作成について説明します。マイクロサービスの基本、必要な環境のセットアップ、2 つのマイクロサービス (OrderService と InventoryService) の実装について説明します。さらに、Eureka と API ゲートウェイを使用してサービス検出を統合し、サービス間のルーティングを管理します。

マイクロサービスとは何ですか?

マイクロサービスは、連携して動作する小さな独立したサービスの集合としてアプリケーションが構築されるソフトウェア アーキテクチャ スタイルです。各サービスは自己完結型であり、明確に定義された API を通じて他のサービスと通信するため、システムの柔軟性、拡張性が向上し、管理が容易になります。

システムアーキテクチャ

私たちのシステムのアーキテクチャは、OrderService と InventoryService という 2 つのマイクロサービスで構成されます。 OrderService はリレーショナル データベース (MySQL) を使用して注文の詳細を保存し、InventoryService は NoSQL データベース (MongoDB) を使用して在庫データを管理します。また、Eureka を使用してサービス検出を実装し、リクエストのルーティングに API ゲートウェイを使用します。

プロジェクトのセットアップ

始める前に、次のツールがインストールされていることを確認してください:

  • IDE: IntelliJ IDEA (推奨) または Eclipse
  • JDK: バージョン 17 以降
  • ビルドツール: Maven
  • データベース: MySQL と MongoDB

マイクロサービス 1: 注文サービス

ステップ 1: プロジェクトを初期化する

  1. Spring Initializr に移動します。
  2. プロジェクトの詳細を入力します:
    • プロジェクト: Maven プロジェクト
    • 言語: Java
    • Spring Boot: 2.5.7 (または互換バージョン)
    • グループ: com.ordersystem
    • アーティファクト: オーダーサービス
    • 名前: 注文サービス
    • パッケージ名: com.ordersystem.orderservice
    • 包装: 瓶
    • ジャワ: 17
  3. 次の依存関係を追加します。
    • スプリングウェブ
    • Spring Data JPA
    • MySQL ドライバー
    • ロンボク島
  4. 生成 をクリックしてプロジェクトをダウンロードします。ダウンロードした zip ファイルを解凍し、IDE で開きます。

ステップ 2: アプリケーションを構成する

src/main/resources にある application.properties ファイルを開き、次の構成を追加します。

spring.datasource.url=jdbc:mysql://localhost:3306/orderservice
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
server.port=8081
ログイン後にコピー

ステップ 3: モデルを実装する

src/main/java/com/ordersystem/orderservice/model/Order.java に Order エンティティ クラスを作成します。

package com.ordersystem.orderservice.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "orders")
public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String product;
    private int quantity;
    private double price;
}
ログイン後にコピー

ステップ 4: リポジトリを作成する

src/main/java/com/ordersystem/orderservice/repository/OrderRepository.java に OrderRepository インターフェースを作成します。

package com.ordersystem.orderservice.repository;

import com.ordersystem.orderservice.model.Order;
import org.springframework.data.jpa.repository.JpaRepository;

public interface OrderRepository extends JpaRepository<Order, Long> {
}
ログイン後にコピー

ステップ 5: サービスを実装する

src/main/java/com/ordersystem/orderservice/service/OrderService.java に OrderService クラスを作成します。

package com.ordersystem.orderservice.service;

import com.ordersystem.orderservice.model.Order;
import com.ordersystem.orderservice.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OrderService {
    @Autowired
    private OrderRepository orderRepository;

    public List<Order> getAllOrders() {
        return orderRepository.findAll();
    }

    public Order getOrderById(Long id) {
        return orderRepository.findById(id).orElse(null);
    }

    public Order createOrder(Order order) {
        return orderRepository.save(order);
    }

    public void deleteOrder(Long id) {
        orderRepository.deleteById(id);
    }
}
ログイン後にコピー

ステップ 6: コントローラーを作成する

src/main/java/com/ordersystem/orderservice/controller/OrderController.java に OrderController クラスを作成します。

package com.ordersystem.orderservice.controller;

import com.ordersystem.orderservice.model.Order;
import com.ordersystem.orderservice.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/orders")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @GetMapping
    public List<Order> getAllOrders() {
        return orderService.getAllOrders();
    }

    @GetMapping("/{id}")
    public Order getOrderById(@PathVariable Long id) {
        return orderService.getOrderById(id);
    }

    @PostMapping
    public Order createOrder(@RequestBody Order order) {
        return orderService.createOrder(order);
    }

    @DeleteMapping("/{id}")
    public void deleteOrder(@PathVariable Long id) {
        orderService.deleteOrder(id);
    }
}
ログイン後にコピー

マイクロサービス 2: インベントリ サービス

ステップ 1: プロジェクトを初期化する

  1. Spring Initializr に移動します。
  2. プロジェクトの詳細を入力します:
    • プロジェクト: Maven プロジェクト
    • 言語: Java
    • Spring Boot: 2.5.7 (または互換バージョン)
    • グループ: com.ordersystem
    • アーティファクト: インベントリサービス
    • 名前: 在庫サービス
    • パッケージ名: com.ordersystem.inventoryservice
    • 包装: 瓶
    • ジャワ: 17
  3. 次の依存関係を追加します。
    • スプリングウェブ
    • Spring Data MongoDB
    • ロンボク島
  4. 生成 をクリックしてプロジェクトをダウンロードします。ダウンロードした zip ファイルを解凍し、IDE で開きます。

ステップ 2: アプリケーションを構成する

src/main/resources にある application.properties ファイルを開き、次の構成を追加します。

spring.data.mongodb.uri=mongodb://localhost:27017/inventoryservice
server.port=8082
ログイン後にコピー

ステップ 3: モデルを実装する

src/main/java/com/ordersystem/inventoryservice/model/InventoryItem.java に InventoryItem エンティティ クラスを作成します。

package com.ordersystem.inventoryservice.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "inventory")
public class InventoryItem {
    @Id
    private String id;
    private String product;
    private int quantity;
}
ログイン後にコピー

ステップ 4: リポジトリを作成する

src/main/java/com/ordersystem/inventoryservice/repository/InventoryRepository.java に InventoryRepository インターフェースを作成します。

package com.ordersystem.inventoryservice.repository;

import com.ordersystem.inventoryservice.model.InventoryItem;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface InventoryRepository extends MongoRepository<InventoryItem, String> {
}
ログイン後にコピー

Step 5: Implement the Service

Create the InventoryService class in src/main/java/com/ordersystem/inventoryservice/service/InventoryService.java:

package com.ordersystem.inventoryservice.service;

import com.ordersystem.inventoryservice.model.InventoryItem;
import com.ordersystem.inventoryservice.repository.InventoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class InventoryService {
    @Autowired
    private InventoryRepository inventoryRepository;

    public List<InventoryItem> getAllItems() {
        return inventoryRepository.findAll();
    }

    public InventoryItem getItemById(String id) {
        return inventoryRepository.findById(id).orElse(null);
    }

    public InventoryItem createItem(InventoryItem item) {
        return inventoryRepository.save(item);
    }

    public void deleteItem(String id) {
        inventoryRepository.deleteById(id);
    }
}
ログイン後にコピー

Step 6: Create the Controller

Create the InventoryController class in src/main/java/com/ordersystem/inventoryservice/controller/InventoryController.java:

package com.ordersystem.inventoryservice.controller;

import com.ordersystem.inventoryservice.model.InventoryItem;
import com.ordersystem.inventoryservice.service.InventoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/inventory")
public class InventoryController {
    @Autowired
    private InventoryService inventoryService;

    @GetMapping
    public List<InventoryItem> getAllItems() {
        return inventoryService.getAllItems();
    }

    @GetMapping("/{id}")
    public InventoryItem getItemById(@PathVariable String id) {
        return inventoryService.getItemById(id);
    }

    @PostMapping
    public InventoryItem createItem(@RequestBody InventoryItem item) {
        return inventoryService.createItem(item);
    }

    @DeleteMapping("/{id}")
    public void deleteItem(@PathVariable String id) {
        inventoryService.delete

Item(id);
    }
}
ログイン後にコピー

Service Discovery with Eureka

Step 1: Initialize the Eureka Server

  1. Go to Spring Initializr.
  2. Fill in the project details:
    • Project: Maven Project
    • Language: Java
    • Spring Boot: 2.5.7 (or a compatible version)
    • Group: com.ordersystem
    • Artifact: eureka-server
    • Name: eureka-server
    • Package name: com.ordersystem.eurekaserver
    • Packaging: Jar
    • Java: 17
  3. Add the Eureka Server dependency.
  4. Click Generate to download the project. Extract the downloaded zip file and open it in your IDE.

Step 2: Configure the Eureka Server

Open the application.properties file in src/main/resources and add the following configuration:

server.port=8761
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
ログイン後にコピー

Step 3: Enable Eureka Server

Annotate the main application class in src/main/java/com/ordersystem/eurekaserver/EurekaServerApplication.java with @EnableEurekaServer:

package com.ordersystem.eurekaserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}
ログイン後にコピー

Integrate Services with Eureka

Add the Eureka client dependency to both OrderService and InventoryService:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
ログイン後にコピー

Add Eureka client configuration to the application.properties files:

Order Service:

eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
spring.application.name=order-service
ログイン後にコピー

Inventory Service:

eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
spring.application.name=inventory-service
ログイン後にコピー

API Gateway

Step 1: Initialize the API Gateway

  1. Go to Spring Initializr.
  2. Fill in the project details:
    • Project: Maven Project
    • Language: Java
    • Spring Boot: 2.5.7 (or a compatible version)
    • Group: com.ordersystem
    • Artifact: api-gateway
    • Name: api-gateway
    • Package name: com.ordersystem.apigateway
    • Packaging: Jar
    • Java: 17
  3. Add the Gateway and Eureka Discovery Client dependencies.
  4. Click Generate to download the project. Extract the downloaded zip file and open it in your IDE.

Step 2: Configure the API Gateway

Open the application.yml file in src/main/resources and add the following configuration:

server:
  port: 8080

spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        - id: order-service
          uri: lb://order-service
          predicates:
            - Path=/api/orders/**
        - id: inventory-service
          uri: lb://inventory-service
          predicates:
            - Path=/api/inventory/**

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
ログイン後にコピー

Step 3: Enable Discovery Client

Annotate the main application class in src/main/java/com/ordersystem/apigateway/ApiGatewayApplication.java with @EnableDiscoveryClient:

package com.ordersystem.apigateway;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class ApiGatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(ApiGatewayApplication.class, args);
    }
}
ログイン後にコピー

Testing the Microservices

  1. Start Eureka Server: Run the Eureka Server application.
  2. Start Order Service: Run the Order Service application.
  3. Start Inventory Service: Run the Inventory Service application.
  4. Start API Gateway: Run the API Gateway application.

Use Postman or any other API client to test the endpoints through the API Gateway:

  • Create Order: POST http://localhost:8080/api/orders
  • Get Orders: GET http://localhost:8080/api/orders
  • Create Inventory Item: POST http://localhost:8080/api/inventory
  • Get Inventory Items: GET http://localhost:8080/api/inventory

Conclusion

In this guide, we've built a simple microservices system using Spring Boot. We created two microservices (OrderService and InventoryService), integrated service discovery with Eureka, and set up an API Gateway for routing requests. This architecture allows for scalable and maintainable microservices that can be easily extended in the future.

以上がSpring Boot を使用した最初のマイクロサービス システムの構築: 初心者ガイドの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!