Spring Boot 4.0 与 Spring Cloud Alibaba 2025 整合完整指南

Spring Boot 4.0 与 Spring Cloud Alibaba 2025 整合完整指南

Spring Cloud全栈实战:手撸企业级项目,从入门到架构师!

概述

本文将详细介绍如何在 Spring Boot 4.0 中整合 Spring Cloud Alibaba 2025 最新版本。Spring Cloud Alibaba 为分布式应用开发提供了一站式解决方案,包含服务发现、配置管理、流量控制等核心功能。

环境要求

Spring Cloud全栈实战:手撸企业级项目,从入门到架构师!

  • JDK: 21+ (Spring Boot 4.0 要求)
  • Maven: 3.6+ 或 Gradle 7.x+
  • Spring Boot: 4.0.0
  • Spring Cloud: 2025.0.0 (假设版本号)
  • Spring Cloud Alibaba: 2025.0.0 (假设版本号)

项目结构

Spring Cloud全栈实战:手撸企业级项目,从入门到架构师!

复制代码
springboot4-sc-alibaba-demo/
├── src/
│   └── main/
│       ├── java/
│       │   └── com/
│       │       └── example/
│       │           ├── Springboot4ScAlibabaApplication.java
│       │           ├── controller/
│       │           ├── service/
│       │           └── config/
│       └── resources/
│           ├── application.yml
│           └── bootstrap.yml
├── pom.xml
└── README.md

第一步:创建项目并配置依赖

Spring Cloud全栈实战:手撸企业级项目,从入门到架构师!

1.1 使用 Spring Initializr 创建项目

访问 https://start.spring.io/ 创建基础项目,选择:

  • Spring Boot: 4.0.0
  • 打包方式: Maven/Gradle
  • Java: 21

1.2 完整 pom.xml 配置

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>4.0.0</version>
        <relativePath/>
    </parent>
    
    <groupId>com.example</groupId>
    <artifactId>springboot4-sc-alibaba-demo</artifactId>
    <version>1.0.0</version>
    <name>springboot4-sc-alibaba-demo</name>
    <description>Spring Boot 4.0 with Spring Cloud Alibaba 2025</description>
    
    <properties>
        <java.version>21</java.version>
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        
        <!-- Spring Cloud 版本 -->
        <spring-cloud.version>2025.0.0</spring-cloud.version>
        <!-- Spring Cloud Alibaba 版本 -->
        <spring-cloud-alibaba.version>2025.0.0</spring-cloud-alibaba.version>
    </properties>
    
    <dependencyManagement>
        <dependencies>
            <!-- Spring Cloud 依赖管理 -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            
            <!-- Spring Cloud Alibaba 依赖管理 -->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    
    <dependencies>
        <!-- Spring Boot Starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <!-- Spring Boot Actuator -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        
        <!-- Spring Cloud Alibaba Nacos Discovery -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        
        <!-- Spring Cloud Alibaba Nacos Config -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        
        <!-- Spring Cloud Alibaba Sentinel -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>
        
        <!-- Spring Cloud OpenFeign -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        
        <!-- Spring Cloud LoadBalancer -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-loadbalancer</artifactId>
        </dependency>
        
        <!-- Spring Boot Test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

第二步:配置文件

Spring Cloud全栈实战:手撸企业级项目,从入门到架构师!

2.1 bootstrap.yml (应用启动配置)

yaml 复制代码
spring:
  application:
    name: demo-service
  profiles:
    active: dev
  cloud:
    nacos:
      config:
        server-addr: localhost:8848
        file-extension: yaml
        namespace: dev-namespace
        group: DEFAULT_GROUP
        extension-configs:
          - data-id: shared-config.yaml
            group: SHARED_GROUP
            refresh: true
      discovery:
        server-addr: localhost:8848
        namespace: dev-namespace
        group: DEFAULT_GROUP
        metadata:
          version: 1.0
    sentinel:
      transport:
        dashboard: localhost:8080
      eager: true
      datasource:
        ds1:
          nacos:
            server-addr: localhost:8848
            data-id: ${spring.application.name}-sentinel
            group-id: DEFAULT_GROUP
            data-type: json
            rule-type: flow

2.2 application.yml (应用配置)

yaml 复制代码
server:
  port: 8081
  servlet:
    context-path: /demo

spring:
  main:
    allow-bean-definition-overriding: true
  mvc:
    throw-exception-if-no-handler-found: true
  web:
    resources:
      add-mappings: false

management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics
  endpoint:
    health:
      show-details: always

feign:
  sentinel:
    enabled: true
  client:
    config:
      default:
        connect-timeout: 5000
        read-timeout: 5000
        logger-level: basic

logging:
  level:
    com.example: debug
    com.alibaba.nacos: warn

第三步:主应用类

Spring Cloud全栈实战:手撸企业级项目,从入门到架构师!

java 复制代码
package com.example;

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(basePackages = "com.example.service")  // 启用Feign客户端
public class Springboot4ScAlibabaApplication {
    
    public static void main(String[] args) {
        SpringApplication.run(Springboot4ScAlibabaApplication.class, args);
    }
}

第四步:Nacos 服务注册与发现

4.1 服务提供者示例

java 复制代码
package com.example.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class DemoController {
    
    @Value("${server.port}")
    private String port;
    
    @GetMapping("/hello")
    public String hello(@RequestParam String name) {
        return String.format("Hello %s, from port: %s", name, port);
    }
    
    @GetMapping("/health")
    public String health() {
        return "Service is healthy";
    }
}

4.2 服务消费者示例(使用OpenFeign)

4.2.1 创建Feign客户端接口
java 复制代码
package com.example.service;

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

@FeignClient(name = "demo-service", path = "/demo/api")
public interface DemoServiceClient {
    
    @GetMapping("/hello")
    String sayHello(@RequestParam String name);
    
    @GetMapping("/health")
    String healthCheck();
}
4.2.2 创建Fallback类
java 复制代码
package com.example.service;

import org.springframework.stereotype.Component;

@Component
public class DemoServiceFallback implements DemoServiceClient {
    
    @Override
    public String sayHello(String name) {
        return "Fallback: Hello " + name;
    }
    
    @Override
    public String healthCheck() {
        return "Fallback: Service unavailable";
    }
}
4.2.3 更新Feign客户端配置Fallback

Spring Cloud全栈实战:手撸企业级项目,从入门到架构师!

java 复制代码
@FeignClient(
    name = "demo-service", 
    path = "/demo/api",
    fallback = DemoServiceFallback.class
)
public interface DemoServiceClient {
    // 接口方法保持不变
}
4.2.4 消费者控制器
java 复制代码
package com.example.controller;

import com.example.service.DemoServiceClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/consumer")
public class ConsumerController {
    
    @Autowired
    private DemoServiceClient demoServiceClient;
    
    @GetMapping("/call-hello")
    public String callHello(@RequestParam String name) {
        return demoServiceClient.sayHello(name);
    }
}

第五步:Nacos 配置管理

5.1 动态配置示例

java 复制代码
package com.example.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/config")
@RefreshScope  // 支持配置动态刷新
public class ConfigController {
    
    @Value("${app.config.demo:defaultValue}")
    private String demoConfig;
    
    @Value("${app.feature.enabled:false}")
    private boolean featureEnabled;
    
    @GetMapping("/demo")
    public String getDemoConfig() {
        return "Current config: " + demoConfig + ", Feature enabled: " + featureEnabled;
    }
}

5.2 在Nacos中创建配置

在Nacos控制台创建Data ID: demo-service-dev.yaml,配置内容:

yaml 复制代码
app:
  config:
    demo: "This is dynamic config from Nacos"
  feature:
    enabled: true
    
server:
  port: 8081

logging:
  level:
    com.example: info

第六步:Sentinel 流量控制

6.1 Sentinel配置类

java 复制代码
package com.example.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class SentinelConfig {
    
    @Bean
    public BlockExceptionHandler sentinelBlockExceptionHandler() {
        return new CustomBlockExceptionHandler();
    }
    
    static class CustomBlockExceptionHandler implements BlockExceptionHandler {
        
        @Override
        public void handle(HttpServletRequest request, HttpServletResponse response, 
                          BlockException e) throws Exception {
            Map<String, Object> result = new HashMap<>();
            
            if (e instanceof FlowException) {
                result.put("code", 1001);
                result.put("message", "接口限流");
            } else if (e instanceof DegradeException) {
                result.put("code", 1002);
                result.put("message", "服务降级");
            } else if (e instanceof ParamFlowException) {
                result.put("code", 1003);
                result.put("message", "热点参数限流");
            } else if (e instanceof SystemBlockException) {
                result.put("code", 1004);
                result.put("message", "系统规则限制");
            } else if (e instanceof AuthorityException) {
                result.put("code", 1005);
                result.put("message", "授权规则不通过");
            } else {
                result.put("code", 1000);
                result.put("message", "未知限流");
            }
            
            response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
            response.setCharacterEncoding("UTF-8");
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            
            new ObjectMapper().writeValue(response.getWriter(), result);
        }
    }
}

6.2 使用Sentinel注解进行资源保护

Spring Cloud全栈实战:手撸企业级项目,从入门到架构师!

java 复制代码
package com.example.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/sentinel")
public class SentinelController {
    
    @GetMapping("/resource")
    @SentinelResource(
        value = "protectedResource",
        blockHandler = "handleBlock",
        fallback = "handleFallback"
    )
    public String protectedResource() {
        return "This is a protected resource";
    }
    
    // 限流处理
    public String handleBlock(BlockException ex) {
        return "请求过于频繁,请稍后重试";
    }
    
    // 降级处理
    public String handleFallback(Throwable ex) {
        return "服务暂时不可用,请稍后重试";
    }
}

第七步:高级配置

7.1 自定义Ribbon配置(负载均衡)

java 复制代码
package com.example.config;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Flux;

import java.util.Arrays;
import java.util.List;

@Configuration
public class LoadBalancerConfig {
    
    @Bean
    public ServiceInstanceListSupplier serviceInstanceListSupplier() {
        return new DemoServiceInstanceListSupplier("demo-service");
    }
    
    static class DemoServiceInstanceListSupplier implements ServiceInstanceListSupplier {
        
        private final String serviceId;
        
        public DemoServiceInstanceListSupplier(String serviceId) {
            this.serviceId = serviceId;
        }
        
        @Override
        public String getServiceId() {
            return serviceId;
        }
        
        @Override
        public Flux<List<ServiceInstance>> get() {
            // 这里可以自定义服务实例发现逻辑
            return Flux.just(Arrays.asList());
        }
    }
}

7.2 全局异常处理

Spring Cloud全栈实战:手撸企业级项目,从入门到架构师!

java 复制代码
package com.example.config;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

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

@RestControllerAdvice
public class GlobalExceptionHandler {
    
    @ExceptionHandler(Exception.class)
    public Map<String, Object> handleException(Exception e) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 500);
        result.put("message", "系统异常: " + e.getMessage());
        return result;
    }
}

第八步:部署和测试

8.1 启动Nacos和Sentinel Dashboard

bash 复制代码
# 启动Nacos (需要提前下载)
sh nacos/bin/startup.sh -m standalone

# 启动Sentinel Dashboard (需要提前下载)
java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -jar sentinel-dashboard.jar

8.2 应用启动类增强

java 复制代码
package com.example;

import org.springframework.boot.Banner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.core.env.Environment;

import java.util.Objects;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients(basePackages = "com.example.service")
public class Springboot4ScAlibabaApplication {
    
    public static void main(String[] args) {
        new SpringApplicationBuilder(Springboot4ScAlibabaApplication.class)
            .bannerMode(Banner.Mode.CONSOLE)
            .run(args);
    }
    
    public void printInfo(Environment env) {
        String port = env.getProperty("server.port");
        String contextPath = Objects.requireNonNullElse(
            env.getProperty("server.servlet.context-path"), "");
        
        System.out.println("\n----------------------------------------------------------");
        System.out.println("Application is running! Access URLs:");
        System.out.println("Local: \t\thttp://localhost:" + port + contextPath);
        System.out.println("External: \thttp://" + getHostAddress() + ":" + port + contextPath);
        System.out.println("Profile(s): \t" + String.join(",", env.getActiveProfiles()));
        System.out.println("----------------------------------------------------------\n");
    }
    
    private String getHostAddress() {
        try {
            return java.net.InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e) {
            return "127.0.0.1";
        }
    }
}

8.3 测试端点

Spring Cloud全栈实战:手撸企业级项目,从入门到架构师!

java 复制代码
package com.example.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/actuator")
public class ActuatorController {
    
    @Autowired
    private DiscoveryClient discoveryClient;
    
    @GetMapping("/services")
    public List<String> getServices() {
        return discoveryClient.getServices().stream()
                .map(service -> service + ": " + discoveryClient.getInstances(service))
                .collect(Collectors.toList());
    }
    
    @GetMapping("/info")
    public String info() {
        return "Spring Boot 4.0 with Spring Cloud Alibaba 2025";
    }
}

第九步:Docker 部署配置

9.1 Dockerfile

dockerfile 复制代码
FROM openjdk:21-jdk-slim

# 设置工作目录
WORKDIR /app

# 复制JAR文件
COPY target/springboot4-sc-alibaba-demo-1.0.0.jar app.jar

# 暴露端口
EXPOSE 8080

# 设置JVM参数
ENV JAVA_OPTS="-Xmx512m -Xms256m -Djava.security.egd=file:/dev/./urandom"

# 启动应用
ENTRYPOINT ["sh", "-c", "java $JAVA_OPTS -jar app.jar"]

9.2 docker-compose.yml

Spring Cloud全栈实战:手撸企业级项目,从入门到架构师!

yaml 复制代码
version: '3.8'

services:
  nacos:
    image: nacos/nacos-server:latest
    container_name: nacos-server
    environment:
      - MODE=standalone
    ports:
      - "8848:8848"
    networks:
      - sc-alibaba-net

  sentinel:
    image: bladex/sentinel-dashboard:latest
    container_name: sentinel-dashboard
    ports:
      - "8080:8080"
    networks:
      - sc-alibaba-net

  demo-app:
    build: .
    container_name: demo-service
    ports:
      - "8081:8081"
    environment:
      - SPRING_PROFILES_ACTIVE=docker
      - SPRING_CLOUD_NACOS_CONFIG_SERVER-ADDR=nacos:8848
      - SPRING_CLOUD_NACOS_DISCOVERY_SERVER-ADDR=nacos:8848
      - SPRING_CLOUD_SENTINEL_TRANSPORT_DASHBOARD=sentinel:8080
    depends_on:
      - nacos
      - sentinel
    networks:
      - sc-alibaba-net

networks:
  sc-alibaba-net:
    driver: bridge

总结

本文详细介绍了 Spring Boot 4.0 与 Spring Cloud Alibaba 2025 最新版本的完整整合方案,包括:

  1. 项目搭建和依赖配置
  2. Nacos 服务注册与发现
  3. Nacos 配置中心集成
  4. Sentinel 流量控制与熔断降级
  5. OpenFeign 声明式服务调用
  6. 高级配置和最佳实践
  7. Docker 容器化部署

通过这套完整的微服务解决方案,您可以快速构建高可用、可扩展的分布式应用系统。记得根据实际生产环境需求调整配置参数和安全设置。

Spring Cloud全栈实战:手撸企业级项目,从入门到架构师!

相关推荐
毕设源码-邱学长1 小时前
【开题答辩全过程】以 基于Spring Boot的酒店管理系统为例,包含答辩的问题和答案
java·spring boot·后端
catchadmin1 小时前
PHP Fiber 优雅协作式多任务
后端·php
晨晖21 小时前
MyBatisPlus的条件构造器
java·数据库·windows
有味道的男人1 小时前
速卖通商品详情接口(速卖通API系列)
java·大数据·数据库
一只小透明啊啊啊啊1 小时前
垃圾回收算法有哪些
java·jvm
DanB241 小时前
Java(网络编程)
java·网络·php
c***69301 小时前
SDN架构详解
架构
5***84641 小时前
Spring全家桶简介
java·后端·spring
u***1371 小时前
Tomcat的server.xml配置详解
xml·java·tomcat