Maison  >  Article  >  Java  >  Construire votre premier système de microservices avec Spring Boot : un guide du débutant

Construire votre premier système de microservices avec Spring Boot : un guide du débutant

WBOY
WBOYoriginal
2024-08-12 22:47:32725parcourir

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

Introduction

Dans ce guide, nous expliquerons la création d'un système de microservices simple mais complet à l'aide de Spring Boot. Nous couvrirons les bases des microservices, la configuration de l'environnement requis et la mise en œuvre de deux microservices : OrderService et InventoryService. De plus, nous intégrerons la découverte de services à l'aide d'Eureka et d'une passerelle API pour gérer le routage entre les services.

Qu'est-ce qu'un microservice ?

Les microservices sont un style d'architecture logicielle dans lequel une application est construite comme un ensemble de petits services indépendants qui fonctionnent ensemble. Chaque service est autonome et communique avec les autres via des API bien définies, rendant le système plus flexible, évolutif et plus facile à gérer.

Architecture du système

L'architecture de notre système sera composée de deux microservices : OrderService et InventoryService. Le OrderService utilisera une base de données relationnelle (MySQL) pour stocker les détails de la commande, tandis que l'InventoryService utilisera une base de données NoSQL (MongoDB) pour gérer les données d'inventaire. Nous mettrons également en œuvre la découverte de services avec Eureka et utiliserons une passerelle API pour le routage des requêtes.

Configuration du projet

Avant de commencer, assurez-vous que les outils suivants sont installés :

  • IDE : IntelliJ IDEA (de préférence) ou Eclipse
  • JDK : Version 17 ou ultérieure
  • Outil de construction : Maven
  • Bases de données : MySQL et MongoDB

Microservice 1 : service de commande

Étape 1 : initialiser le projet

  1. Allez sur Spring Initializr.
  2. Remplissez les détails du projet :
    • Projet : Projet Maven
    • Langage : Java
    • Spring Boot : 2.5.7 (ou une version compatible)
    • Groupe : com.ordersystem
    • Artefact : service de commande
    • Nom : service-de-commande
    • Nom du package : com.ordersystem.orderservice
    • Conditionnement : Pot
    • Java : 17
  3. Ajoutez les dépendances suivantes :
    • Web de printemps
    • Données de printemps JPA
    • Pilote MySQL
    • Lombok
  4. Cliquez sur Générer pour télécharger le projet. Extrayez le fichier zip téléchargé et ouvrez-le dans votre IDE.

Étape 2 : configurer l'application

Ouvrez le fichier application.properties dans src/main/resources et ajoutez la configuration suivante :

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

Étape 3 : mettre en œuvre le modèle

Créez la classe d'entité Order dans src/main/java/com/ordersystem/orderservice/model/Order.java :

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;
}

Étape 4 : Créer le référentiel

Créez l'interface OrderRepository dans src/main/java/com/ordersystem/orderservice/repository/OrderRepository.java :

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> {
}

Étape 5 : implémenter le service

Créez la classe OrderService dans src/main/java/com/ordersystem/orderservice/service/OrderService.java :

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);
    }
}

Étape 6 : Créer le contrôleur

Créez la classe OrderController dans src/main/java/com/ordersystem/orderservice/controller/OrderController.java :

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);
    }
}

Microservice 2 : service d'inventaire

Étape 1 : initialiser le projet

  1. Allez sur Spring Initializr.
  2. Remplissez les détails du projet :
    • Projet : Projet Maven
    • Langage : Java
    • Spring Boot : 2.5.7 (ou une version compatible)
    • Groupe : com.ordersystem
    • Artefact : inventaire-service
    • Nom : inventaire-service
    • Nom du package : com.ordersystem.inventoryservice
    • Conditionnement : Pot
    • Java : 17
  3. Ajoutez les dépendances suivantes :
    • Web de printemps
    • Données de printemps MongoDB
    • Lombok
  4. Cliquez sur Générer pour télécharger le projet. Extrayez le fichier zip téléchargé et ouvrez-le dans votre IDE.

Étape 2 : configurer l'application

Ouvrez le fichier application.properties dans src/main/resources et ajoutez la configuration suivante :

spring.data.mongodb.uri=mongodb://localhost:27017/inventoryservice
server.port=8082

Étape 3 : mettre en œuvre le modèle

Créez la classe d'entité InventoryItem dans src/main/java/com/ordersystem/inventoryservice/model/InventoryItem.java :

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;
}

Étape 4 : Créer le référentiel

Créez l'interface InventoryRepository dans src/main/java/com/ordersystem/inventoryservice/repository/InventoryRepository.java :

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.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn