首頁 > Java > java教程 > 使用 Spring Boot 建立您的第一個微服務系統:初學者指南

使用 Spring Boot 建立您的第一個微服務系統:初學者指南

WBOY
發布: 2024-08-12 22:47:32
原創
866 人瀏覽過

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

介紹

在本指南中,我們將逐步介紹如何使用 Spring Boot 建立一個簡單但全面的微服務系統。我們將介紹微服務的基礎知識,設定所需的環境,並實作兩個微服務:OrderService 和 InventoryService。此外,我們將使用 Eureka 和 API 閘道整合服務發現來管理服務之間的路由。

什麼是微服務?

微服務是一種軟體架構風格,其中應用程式被建構為協同工作的小型獨立服務的集合。每個服務都是獨立的,並透過明確定義的 API 與其他服務進行通信,使系統更加靈活、可擴展且更易於管理。

系統架構

我們系統的架構將由兩個微服務組成:OrderService 和 InventoryService。 OrderService 將使用關聯式資料庫 (MySQL) 來儲存訂單詳細信息,而 InventoryService 將使用 NoSQL 資料庫 (MongoDB) 來管理庫存資料。我們還將使用 Eureka 實作服務發現,並使用 API 閘道來路由請求。

項目設定

在我們開始之前,請確保您已安裝以下工具:

  • IDE:IntelliJ IDEA(首選)或 Eclipse
  • JDK:版本 17 或更高版本
  • 建置工具:Maven
  • 資料庫:MySQL 和 MongoDB

微服務一:訂單服務

第 1 步:初始化項目

  1. 前往 Spring Initializr。
  2. 填寫項目詳細資料:
    • 專案:Maven 專案
    • 語言:Java
    • Spring Boot:2.5.7(或相容版本)
    • :com.ordersystem
    • 神器:訂單服務
    • 名稱:訂單服務
    • 套件名稱:com.ordersystem.orderservice
    • 包裝:罐子
    • Java:17
  3. 新增以下相依性:
    • Spring Web
    • 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
    • 包裝:罐子
    • Java:17
  3. 新增以下相依性:
    • Spring Web
    • 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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板