首页 > Java > java教程 > 正文

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

WBOY
发布: 2024-08-12 22:47:32
原创
820 人浏览过

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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板