”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 使用 Spring Boot 构建您的第一个微服务系统:初学者指南

使用 Spring Boot 构建您的第一个微服务系统:初学者指南

发布于2024-11-07
浏览:593

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

Introduction

In this guide, we'll walk through the creation of a simple yet comprehensive microservices system using Spring Boot. We will cover the basics of microservices, setting up the required environment, and implementing two microservices: OrderService and InventoryService. Additionally, we'll integrate service discovery using Eureka and an API Gateway to manage routing between the services.

What is a Microservice?

Microservices are a software architecture style where an application is built as a collection of small, independent services that work together. Each service is self-contained and communicates with others through well-defined APIs, making the system more flexible, scalable, and easier to manage.

System Architecture

The architecture of our system will consist of two microservices: OrderService and InventoryService. The OrderService will use a relational database (MySQL) to store order details, while the InventoryService will use a NoSQL database (MongoDB) for managing inventory data. We'll also implement service discovery with Eureka and use an API Gateway for routing requests.

Project Setup

Before we begin, ensure you have the following tools installed:

  • IDE: IntelliJ IDEA (preferred) or Eclipse
  • JDK: Version 17 or later
  • Build Tool: Maven
  • Databases: MySQL and MongoDB

Microservice 1: Order Service

Step 1: Initialize the Project

  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: order-service
    • Name: order-service
    • Package name: com.ordersystem.orderservice
    • Packaging: Jar
    • Java: 17
  3. Add the following dependencies:
    • Spring Web
    • Spring Data JPA
    • MySQL Driver
    • Lombok
  4. Click Generate to download the project. Extract the downloaded zip file and open it in your IDE.

Step 2: Configure the Application

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

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

Step 3: Implement the Model

Create the Order entity class in 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;
}

Step 4: Create the Repository

Create the OrderRepository interface in 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 {
}

Step 5: Implement the Service

Create the OrderService class in 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 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);
    }
}

Step 6: Create the Controller

Create the OrderController class in 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 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: Inventory Service

Step 1: Initialize the Project

  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: inventory-service
    • Name: inventory-service
    • Package name: com.ordersystem.inventoryservice
    • Packaging: Jar
    • Java: 17
  3. Add the following dependencies:
    • Spring Web
    • Spring Data MongoDB
    • Lombok
  4. Click Generate to download the project. Extract the downloaded zip file and open it in your IDE.

Step 2: Configure the Application

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

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

Step 3: Implement the Model

Create the InventoryItem entity class in 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;
}

Step 4: Create the Repository

Create the InventoryRepository interface in 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 {
}

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 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 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:


    org.springframework.cloud
    spring-cloud-starter-netflix-eureka-client

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.

版本声明 本文转载于:https://dev.to/isaactony/building-your-first-microservice-system-with-spring-boot-a-beginners-guide-3b28?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 如何同步迭代并从PHP中的两个等级阵列打印值?
    如何同步迭代并从PHP中的两个等级阵列打印值?
    同步的迭代和打印值来自相同大小的两个数组使用两个数组相等大小的selectbox时,一个包含country代码的数组,另一个包含乡村代码,另一个包含其相应名称的数组,可能会因不当提供了exply for for for the uncore for the forsion for for ytry...
    编程 发布于2025-04-03
  • 为什么不使用CSS`content'属性显示图像?
    为什么不使用CSS`content'属性显示图像?
    在Firefox extemers属性为某些图像很大,&& && && &&华倍华倍[华氏华倍华氏度]很少见,却是某些浏览属性很少,尤其是特定于Firefox的某些浏览器未能在使用内容属性引用时未能显示图像的情况。这可以在提供的CSS类中看到:。googlepic { 内容:url(&#...
    编程 发布于2025-04-03
  • 如何在无序集合中为元组实现通用哈希功能?
    如何在无序集合中为元组实现通用哈希功能?
    在未订购的集合中的元素要纠正此问题,一种方法是手动为特定元组类型定义哈希函数,例如: template template template 。 struct std :: hash { size_t operator()(std :: tuple const&tuple)const {...
    编程 发布于2025-04-03
  • 如何在GO编译器中自定义编译优化?
    如何在GO编译器中自定义编译优化?
    在GO编译器中自定义编译优化 GO中的默认编译过程遵循特定的优化策略。 However, users may need to adjust these optimizations for specific requirements.Optimization Control in Go Compi...
    编程 发布于2025-04-03
  • 如何从Python中的字符串中删除表情符号:固定常见错误的初学者指南?
    如何从Python中的字符串中删除表情符号:固定常见错误的初学者指南?
    从python import codecs import codecs import codecs 导入 text = codecs.decode('这狗\ u0001f602'.encode('utf-8'),'utf-8') 印刷(文字)#带有...
    编程 发布于2025-04-03
  • 我可以将加密从McRypt迁移到OpenSSL,并使用OpenSSL迁移MCRYPT加密数据?
    我可以将加密从McRypt迁移到OpenSSL,并使用OpenSSL迁移MCRYPT加密数据?
    将我的加密库从mcrypt升级到openssl 问题:是否可以将我的加密库从McRypt升级到OpenSSL?如果是这样,如何?答案:是的,可以将您的Encryption库从McRypt升级到OpenSSL。可以使用openssl。附加说明: [openssl_decrypt()函数要求iv参...
    编程 发布于2025-04-03
  • 为什么不````''{margin:0; }`始终删除CSS中的最高边距?
    为什么不````''{margin:0; }`始终删除CSS中的最高边距?
    在CSS 问题:不正确的代码: 全球范围将所有余量重置为零,如提供的代码所建议的,可能会导致意外的副作用。解决特定的保证金问题是更建议的。 例如,在提供的示例中,将以下代码添加到CSS中,将解决余量问题: body H1 { 保证金顶:-40px; } 此方法更精确,避免了由全局保证金重置引...
    编程 发布于2025-04-03
  • 如何处理PHP文件系统功能中的UTF-8文件名?
    如何处理PHP文件系统功能中的UTF-8文件名?
    在PHP的Filesystem functions中处理UTF-8 FileNames 在使用PHP的MKDIR函数中含有UTF-8字符的文件很多flusf-8字符时,您可能会在Windows Explorer中遇到comploreer grounder grounder grounder gro...
    编程 发布于2025-04-03
  • 为什么我会收到MySQL错误#1089:错误的前缀密钥?
    为什么我会收到MySQL错误#1089:错误的前缀密钥?
    mySQL错误#1089:错误的前缀键错误descript [#1089-不正确的前缀键在尝试在表中创建一个prefix键时会出现。前缀键旨在索引字符串列的特定前缀长度长度,可以更快地搜索这些前缀。了解prefix keys `这将在整个Movie_ID列上创建标准主键。主密钥对于唯一识别...
    编程 发布于2025-04-03
  • 如何使用不同数量列的联合数据库表?
    如何使用不同数量列的联合数据库表?
    合并列数不同的表 当尝试合并列数不同的数据库表时,可能会遇到挑战。一种直接的方法是在列数较少的表中,为缺失的列追加空值。 例如,考虑两个表,表 A 和表 B,其中表 A 的列数多于表 B。为了合并这些表,同时处理表 B 中缺失的列,请按照以下步骤操作: 确定表 B 中缺失的列,并将它们添加到表的末...
    编程 发布于2025-04-03
  • 大批
    大批
    [2 数组是对象,因此它们在JS中也具有方法。 切片(开始):在新数组中提取部分数组,而无需突变原始数组。 令ARR = ['a','b','c','d','e']; // USECASE:提取直到索引作...
    编程 发布于2025-04-03
  • 可以在纯CS中将多个粘性元素彼此堆叠在一起吗?
    可以在纯CS中将多个粘性元素彼此堆叠在一起吗?
    [2这里: https://webthemez.com/demo/sticky-multi-header-scroll/index.html </main> <section> { display:grid; grid-template-...
    编程 发布于2025-04-03
  • 如何使用node-mysql在单个查询中执行多个SQL语句?
    如何使用node-mysql在单个查询中执行多个SQL语句?
    在node-mysql node-mysql文档最初出于安全原因最初禁用多个语句支持,因为它可能导致SQL注入攻击。要启用此功能,您需要在创建连接时将倍增设置设置为true: var connection = mysql.createconnection({{multipleStatement:...
    编程 发布于2025-04-03
  • 如何使用Python有效地以相反顺序读取大型文件?
    如何使用Python有效地以相反顺序读取大型文件?
    在python 中,如果您使用一个大文件,并且需要从最后一行读取其内容,则在第一行到第一行,Python的内置功能可能不合适。这是解决此任务的有效解决方案:反向行读取器生成器 == ord('\ n'): 缓冲区=缓冲区[:-1] ...
    编程 发布于2025-04-03

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3