Spring Boot 3.2 结合 Spring Cloud 微服务架构实操指南 现代分布式应用系统构建实战教程

本文涉及的产品
RDS DuckDB + QuickBI 企业套餐,8核32GB + QuickBI 专业版
RDS MySQL DuckDB 分析主实例,基础系列 4核8GB
RDS AI 助手,专业版
简介: Spring Boot 3.2 + Spring Cloud 2023.0 微服务架构实践摘要 本文基于Spring Boot 3.2.5和Spring Cloud 2023.0.1最新稳定版本,演示现代微服务架构的构建过程。主要内容包括: 技术栈选择:采用Spring Cloud Netflix Eureka 4.1.0作为服务注册中心,Resilience4j 2.1.0替代Hystrix实现熔断机制,配合OpenFeign和Gateway等组件。 核心实操步骤: 搭建Eureka注册中心服务 构建商品

Spring Boot 3.2 + Spring Cloud 2023.0 实操指南:构建现代微服务架构

技术栈选择说明

本文将基于最新稳定版本构建完整微服务体系:

  • Spring Boot 3.2.5(最新稳定版)
  • Spring Cloud 2023.0.1(代号"Ilford",与Boot 3.2.x兼容)
  • 服务注册发现:Spring Cloud Netflix Eureka 4.1.0
  • 服务调用:Spring Cloud OpenFeign 4.1.0
  • API网关:Spring Cloud Gateway 4.1.0
  • 配置中心:Spring Cloud Config 4.1.0
  • 服务熔断:Resilience4j 2.1.0(替代Hystrix)

选择理由:Spring Cloud 2023.0.x是目前最新的稳定版本系列,全面支持Spring Boot 3.2.x,移除了大量过时组件,采用Resilience4j作为官方推荐的熔断方案,更符合现代微服务架构需求。

实操步骤:构建基础微服务架构

1. 搭建Eureka服务注册中心

服务注册中心是微服务架构的核心基础设施,负责服务地址的管理。

步骤1:创建Maven项目,添加依赖

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.2.5</version>
</parent>

<dependencies>
    <!-- Eureka Server -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>

    <!--  actuator用于监控 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>2023.0.1</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

步骤2:创建启动类,添加@EnableEurekaServer注解

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

@SpringBootApplication
@EnableEurekaServer // 启用Eureka服务注册中心功能
public class EurekaServerApplication {
   
    public static void main(String[] args) {
   
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}

步骤3:配置application.yml

server:
  port: 8761  # Eureka默认端口

eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: false  # 自身不注册到注册中心
    fetch-registry: false        # 不需要从注册中心获取服务信息
    service-url:
      defaultZone: http://${
   eureka.instance.hostname}:${
   server.port}/eureka/
  server:
    enable-self-preservation: false  # 关闭自我保护模式(生产环境建议开启)
    eviction-interval-timer-in-ms: 30000  # 清理无效节点的间隔时间

启动验证:访问 http://localhost:8761 可看到Eureka控制台界面,此时还没有服务注册。

2. 构建服务提供者

我们创建一个简单的商品服务(product-service)作为服务提供者。

步骤1:添加依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
</dependencies>

步骤2:创建启动类

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

@SpringBootApplication
@EnableDiscoveryClient // 启用服务发现客户端功能
public class ProductServiceApplication {
   
    public static void main(String[] args) {
   
        SpringApplication.run(ProductServiceApplication.class, args);
    }
}

步骤3:配置application.yml

server:
  port: 8081

spring:
  application:
    name: product-service  # 服务名称,消费者将通过此名称调用

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true  # 注册时使用IP地址
    instance-id: ${
   spring.cloud.client.ip-address}:${
   server.port}  # 显示IP和端口

步骤4:创建业务接口

import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/products")
public class ProductController {
   

    // 模拟数据库存储
    private static final Map<Long, Product> productMap = new HashMap<>();

    static {
   
        productMap.put(1L, new Product(1L, "Spring Boot实战", 59.9));
        productMap.put(2L, new Product(2L, "Spring Cloud微服务", 69.9));
    }

    @GetMapping("/{id}")
    public Product getProduct(@PathVariable Long id) {
   
        // 模拟服务调用延迟
        try {
   
            Thread.sleep(500);
        } catch (InterruptedException e) {
   
            Thread.currentThread().interrupt();
        }

        Product product = productMap.get(id);
        if (product == null) {
   
            throw new RuntimeException("产品不存在");
        }
        return product;
    }

    @PostMapping
    public Product createProduct(@RequestBody Product product) {
   
        productMap.put(product.getId(), product);
        return product;
    }

    // 内部静态类
    public static class Product {
   
        private Long id;
        private String name;
        private Double price;

        // 构造函数、getter和setter省略
        public Product() {
   }

        public Product(Long id, String name, Double price) {
   
            this.id = id;
            this.name = name;
            this.price = price;
        }

        // getter和setter
        public Long getId() {
    return id; }
        public void setId(Long id) {
    this.id = id; }
        public String getName() {
    return name; }
        public void setName(String name) {
    this.name = name; }
        public Double getPrice() {
    return price; }
        public void setPrice(Double price) {
    this.price = price; }
    }
}

启动验证:启动服务后,访问Eureka控制台(http://localhost:8761),可看到PRODUCT-SERVICE已注册。

3. 构建服务消费者(使用OpenFeign)

创建订单服务(order-service)作为服务消费者,通过OpenFeign调用商品服务。

步骤1:添加依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
    <!-- 熔断依赖 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
</dependencies>

步骤2:创建启动类

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

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients // 启用Feign客户端
public class OrderServiceApplication {
   
    public static void main(String[] args) {
   
        SpringApplication.run(OrderServiceApplication.class, args);
    }
}

步骤3:配置application.yml

server:
  port: 8082

spring:
  application:
    name: order-service

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true
    instance-id: ${
   spring.cloud.client.ip-address}:${
   server.port}

# Resilience4j配置
resilience4j:
  circuitbreaker:
    instances:
      productService:
        sliding-window-size: 10
        failure-rate-threshold: 50
        wait-duration-in-open-state: 10000
        permitted-number-of-calls-in-half-open-state: 3
  retry:
    instances:
      productService:
        max-retry-attempts: 3
        wait-duration: 1000

步骤4:创建Feign客户端

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

// 指定要调用的服务名称
@FeignClient(name = "product-service")
public interface ProductFeignClient {
   

    @GetMapping("/products/{id}")
    Product getProduct(@PathVariable("id") Long id);

    // 产品实体类,与服务提供者保持一致
    class Product {
   
        private Long id;
        private String name;
        private Double price;

        // getter和setter省略
        public Long getId() {
    return id; }
        public void setId(Long id) {
    this.id = id; }
        public String getName() {
    return name; }
        public void setName(String name) {
    this.name = name; }
        public Double getPrice() {
    return price; }
        public void setPrice(Double price) {
    this.price = price; }
    }
}

步骤5:创建服务和控制器

import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.retry.annotation.Retry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/orders")
public class OrderController {
   

    @Autowired
    private ProductFeignClient productFeignClient;

    // 使用熔断和重试机制
    @GetMapping("/{productId}")
    @CircuitBreaker(name = "productService", fallbackMethod = "getOrderFallback")
    @Retry(name = "productService")
    public Order getOrder(@PathVariable Long productId) {
   
        ProductFeignClient.Product product = productFeignClient.getProduct(productId);
        return new Order(System.currentTimeMillis(), productId, product.getName(), 1, product.getPrice());
    }

    // 熔断降级方法
    public Order getOrderFallback(Long productId, Exception e) {
   
        return new Order(System.currentTimeMillis(), productId, "降级商品", 1, 0.0);
    }

    // 订单实体类
    public static class Order {
   
        private Long id;
        private Long productId;
        private String productName;
        private Integer quantity;
        private Double price;

        // 构造函数、getter和setter省略
        public Order(Long id, Long productId, String productName, Integer quantity, Double price) {
   
            this.id = id;
            this.productId = productId;
            this.productName = productName;
            this.quantity = quantity;
            this.price = price;
        }

        // getter和setter
        public Long getId() {
    return id; }
        public void setId(Long id) {
    this.id = id; }
        public Long getProductId() {
    return productId; }
        public void setProductId(Long productId) {
    this.productId = productId; }
        public String getProductName() {
    return productName; }
        public void setProductName(String productName) {
    this.productName = productName; }
        public Integer getQuantity() {
    return quantity; }
        public void setQuantity(Integer quantity) {
    this.quantity = quantity; }
        public Double getPrice() {
    return price; }
        public void setPrice(Double price) {
    this.price = price; }
    }
}

验证服务调用

  1. 启动order-service
  2. 访问 http://localhost:8082/orders/1
  3. 应返回包含产品信息的订单数据

4. 配置Spring Cloud Gateway

API网关作为微服务的入口,负责路由转发、负载均衡、认证授权等功能。

步骤1:创建网关项目,添加依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
</dependencies>

注意:Spring Cloud Gateway基于Netty和WebFlux,不能与spring-boot-starter-web(Servlet)同时使用,会导致冲突。

步骤2:创建启动类

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

@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
   
    public static void main(String[] args) {
   
        SpringApplication.run(GatewayApplication.class, args);
    }
}

步骤3:配置application.yml

server:
  port: 8080  # 网关端口

spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true  # 启用服务发现定位器
          lower-case-service-id: true  # 服务ID转为小写
      routes:
        - id: product-service
          uri: lb://product-service  # 负载均衡到product-service
          predicates:
            - Path=/api/products/**  # 匹配路径
          filters:
            - StripPrefix=1  # 去除路径前缀/api
            - name: RequestRateLimiter
              args:
                redis-rate-limiter.replenishRate: 10  # 令牌桶填充速率
                redis-rate-limiter.burstCapacity: 20  # 令牌桶容量
                key-resolver: "#{@ipAddressKeyResolver}"  # 基于IP的限流

        - id: order-service
          uri: lb://order-service
          predicates:
            - Path=/api/orders/**
          filters:
            - StripPrefix=1

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true

步骤4:配置限流策略

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

@Configuration
public class GatewayConfig {
   

    // 基于IP地址的限流
    @Bean
    public KeyResolver ipAddressKeyResolver() {
   
        return exchange -> Mono.just(
            exchange.getRequest()
                   .getRemoteAddress()
                   .getAddress()
                   .getHostAddress()
        );
    }
}

验证网关功能

  1. 启动网关服务
  2. 通过网关访问商品服务:http://localhost:8080/api/products/1
  3. 通过网关访问订单服务:http://localhost:8080/api/orders/1

关键技术点说明

  1. 版本兼容性
    Spring Cloud 2023.0.x 与 Spring Boot 3.2.x 完全兼容,但不兼容旧版本Spring Boot。在实际项目中,务必遵循官方的版本兼容矩阵。

  2. Resilience4j替代Hystrix
    从Spring Cloud 2020.0版本开始,Hystrix已被移除,推荐使用Resilience4j。它是一个轻量级、易于使用的熔断库,提供熔断、限流、重试等功能。

  3. Spring Cloud Gateway优势
    相比Zuul网关,Gateway基于非阻塞响应式编程模型,性能更高,支持动态路由、集成Spring生态系统的各种功能,是目前推荐的网关解决方案。

  4. 服务发现机制
    本文使用Eureka作为服务注册中心,在实际项目中也可选择Consul、Nacos等其他方案,配置方式类似,只需替换相应依赖和配置。

扩展与进阶

  1. 配置中心集成
    可添加Spring Cloud Config Server集中管理配置,实现配置的动态更新。

  2. 安全认证
    集成Spring Security和OAuth2,在网关层实现统一的认证授权。

  3. 分布式追踪
    添加Spring Cloud Sleuth和Zipkin实现分布式追踪,便于微服务问题排查。

  4. 监控告警
    结合Spring Boot Actuator、Prometheus和Grafana构建完善的监控告警体系。

通过本文的实操指南,你已掌握基于最新Spring Boot和Spring Cloud构建微服务架构的核心技能。在实际项目中,可根据业务需求进行扩展和优化,构建稳定、高效、可扩展的微服务系统。


Spring Boot 3.2,Spring Cloud 2023.0, 微服务架构,实操指南,分布式应用系统,系统构建,实战教程,微服务开发,分布式架构,Spring 框架,微服务实战,应用系统构建,Java 微服务,Spring 技术栈,分布式开发



代码获取方式
https://pan.quark.cn/s/14fcf913bae6


相关文章
|
6月前
|
算法 Java 微服务
【SpringCloud(1)】初识微服务架构:创建一个简单的微服务;java与Spring与微服务;初入RestTemplate
微服务架构是What?? 微服务架构是一种架构模式,它提出将单一应用程序划分为一组小的服务,服务之间互相协调、互相配合,为用户提供最终价值。 每个服务允许在其独立的进程中,服务于服务间采用轻量级的通信机制互相协作(通常是Http协议的RESTful API或RPC协议)。 每个服务都围绕着具体业务进行构建,并且能够被独立的部署到生产环境、类生产环境等。另外应当尽量避免统一的、集中式的服务管理机制,对具体的一个服务而言,应根据上下文,选择合适的语言、工具对其进行构建
633 126
|
6月前
|
负载均衡 算法 Java
【SpringCloud(2)】微服务注册中心:Eureka、Zookeeper;CAP分析;服务注册与服务发现;单机/集群部署Eureka;连接注册中心
1. 什么是服务治理? SpringCloud封装了Netfix开发的Eureka模块来实现服务治理 在传统pc的远程调用框架中,管理每个服务与服务之间依赖关系比较复杂,管理比较复杂,所以需要使用服务治理,管理服务于服务之间依赖关系,可以实现服务调用、负载均衡、容错等,实现服务发现与注册
409 0
|
6月前
|
监控 Cloud Native Java
Spring Boot 3.x 微服务架构实战指南
🌟蒋星熠Jaxonic,技术宇宙中的星际旅人。深耕Spring Boot 3.x与微服务架构,探索云原生、性能优化与高可用系统设计。以代码为笔,在二进制星河中谱写极客诗篇。关注我,共赴技术星辰大海!(238字)
1187 2
Spring Boot 3.x 微服务架构实战指南
|
6月前
|
负载均衡 Java API
《深入理解Spring》Spring Cloud 构建分布式系统的微服务全家桶
Spring Cloud为微服务架构提供一站式解决方案,涵盖服务注册、配置管理、负载均衡、熔断限流等核心功能,助力开发者构建高可用、易扩展的分布式系统,并持续向云原生演进。
|
7月前
|
消息中间件 Ubuntu Java
SpringBoot整合MQTT实战:基于EMQX实现双向设备通信
本教程指导在Ubuntu上部署EMQX 5.9.0并集成Spring Boot实现MQTT双向通信,涵盖服务器搭建、客户端配置及生产实践,助您快速构建企业级物联网消息系统。
2615 1
|
6月前
|
人工智能 JavaScript 前端开发
GenSX (不一样的AI应用框架)架构学习指南
GenSX 是一个基于 TypeScript 的函数式 AI 工作流框架,以“函数组合替代图编排”为核心理念。它通过纯函数组件、自动追踪与断点恢复等特性,让开发者用自然代码构建可追溯、易测试的 LLM 应用。支持多模型集成与插件化扩展,兼具灵活性与工程化优势。
521 6
|
7月前
|
人工智能 Cloud Native 中间件
划重点|云栖大会「AI 原生应用架构论坛」看点梳理
本场论坛将系统性阐述 AI 原生应用架构的新范式、演进趋势与技术突破,并分享来自真实生产环境下的一线实践经验与思考。
|
7月前
|
Java 数据库 数据安全/隐私保护
Spring Boot四层架构深度解析
本文详解Spring Boot四层架构(Controller-Service-DAO-Database)的核心思想与实战应用,涵盖职责划分、代码结构、依赖注入、事务管理及常见问题解决方案,助力构建高内聚、低耦合的企业级应用。
1468 1
|
7月前
|
机器学习/深度学习 人工智能 vr&ar
H4H:面向AR/VR应用的NPU-CIM异构系统混合卷积-Transformer架构搜索——论文阅读
H4H是一种面向AR/VR应用的混合卷积-Transformer架构,基于NPU-CIM异构系统,通过神经架构搜索实现高效模型设计。该架构结合卷积神经网络(CNN)的局部特征提取与视觉Transformer(ViT)的全局信息处理能力,提升模型性能与效率。通过两阶段增量训练策略,缓解混合模型训练中的梯度冲突问题,并利用异构计算资源优化推理延迟与能耗。实验表明,H4H在相同准确率下显著降低延迟和功耗,为AR/VR设备上的边缘AI推理提供了高效解决方案。
1305 0
|
6月前
|
机器学习/深度学习 自然语言处理 算法
48_动态架构模型:NAS在LLM中的应用
大型语言模型(LLM)在自然语言处理领域的突破性进展,很大程度上归功于其庞大的参数量和复杂的网络架构。然而,随着模型规模的不断增长,计算资源消耗、推理延迟和部署成本等问题日益凸显。如何在保持模型性能的同时,优化模型架构以提高效率,成为2025年大模型研究的核心方向之一。神经架构搜索(Neural Architecture Search, NAS)作为一种自动化的网络设计方法,正在为这一挑战提供创新性解决方案。本文将深入探讨NAS技术如何应用于LLM的架构优化,特别是在层数与维度调整方面的最新进展,并通过代码实现展示简单的NAS实验。
327 0