Spring Cloud从零开始:微服务入门指南

·赵建国
2025-06-18 08:28
阅读 5198

开篇:什么是Spring Cloud?它能做什么?

开篇:什么是Spring Cloud?它能做什么?

想象一下,你开发了一个大型网站或应用程序,用户越来越多,功能也越来越多。这时候你发现一个问题:系统越来越慢、越来越难维护,一旦某个功能出问题,整个系统都可能崩溃。

为了解决这个问题,软件行业提出了一种新的架构模式 —— 微服务(Microservices)。

简单来说,微服务就是把一个大项目拆分成多个小项目,每个小项目专注于一件事,并可以独立运行和部署。这种架构的好处是:

  • 系统更容易扩展
  • 便于团队协作
  • 出问题时影响范围更小
  • 可以灵活使用不同技术栈

而我们今天要学习的 Spring Cloud,就是用来帮助你构建和管理这些“小项目”的工具集。你可以把它理解成一套“微服务管家”,它帮你搞定服务注册与发现、配置中心、负载均衡、熔断降级等一系列复杂的工作。


环境准备:搭建我们的开发环境

环境准备:搭建我们的开发环境

在正式开始前,我们需要准备好以下开发环境。别担心,这一步虽然看起来有点多,但跟着步骤一步步来,很简单!

1. 安装Java

Spring Cloud 是建立在 Java 基础上的,所以首先确保你安装了 JDK 8 或更高版本。

验证是否安装成功:

java -version

你应该看到类似这样的输出:

openjdk version "17.0.4" 2022-07-19
OpenJDK Runtime Environment (build 17.0.4+8-Ubuntu-22.04)
OpenJDK 64-Bit Server VM (build 17.0.4+8-Ubuntu-22.04, mixed mode, sharing)

2. 安装Maven

Maven是用来管理项目的依赖和构建项目的工具。

下载地址:https://maven.apache.org/download.cgi

安装完成后执行命令查看版本:

mvn -v

3. 安装IDE(推荐IntelliJ IDEA)

推荐使用 IntelliJ IDEA 社区版,免费且功能强大。

下载地址:https://www.jetbrains.com/idea/download/

安装完成后打开并安装Spring Boot插件(Preferences -> Plugins 搜索 “Spring Boot”)

4. 创建一个空工程

打开IDEA,选择 New Project -> Maven -> 勾选 Create from archetype -> 选择 maven-archetype-quickstart,填写groupId(例如com.example)、artifactId(如spring-cloud-demo),点击Finish。

现在我们已经拥有了一个基础的Maven项目结构,接下来就可以开始编写Spring Cloud代码了!


核心概念:通俗易懂地理解微服务的关键点

为了更好地理解Spring Cloud,先来了解几个核心概念。

1. 服务注册与发现(Service Registry & Discovery)

你可以想象这是一个公司内部的员工通讯录。每个微服务启动后都会去注册自己(告诉大家我是谁,在哪),其他服务想调用它时就查这个通讯录。

📌 工具:Eureka(Netflix开源组件)

2. 负载均衡(Load Balancer)

当你有多个相同功能的服务实例(比如商品服务跑在三台服务器上),客户端请求过来的时候,需要决定该发给哪个实例。负载均衡器会帮你自动分配流量。

📌 工具:Ribbon 或 LoadBalancer(Spring 自带)

3. 熔断机制(Circuit Breaker)

有时候某一个服务可能会卡住或者崩溃,这时候如果不做处理,就会导致整个系统变慢甚至宕机。熔断机制就像是电路中的保险丝,在检测到失败超过阈值时自动“断开”请求,防止雪崩效应。

📌 工具:Hystrix(已过时),推荐使用 Resilience4j

4. API网关(API Gateway)

网关就像小区门口的保安,所有请求都要经过它。它可以统一处理权限控制、限流、路由等功能。

📌 工具:Zuul(旧)或 Spring Cloud Gateway(新)

5. 分布式配置中心(Config Server)

以前你改个配置得进服务器改文件,重启应用。配置中心可以集中管理配置,并支持动态刷新。

📌 工具:Spring Cloud Config + Git仓库


实战项目:一步一步搭建你的第一个微服务系统

我们将搭建一个简单的电商系统,包含以下三个服务:

系统架构设计图-2

  • 商品服务(Product Service)
  • 订单服务(Order Service)
  • 注册中心(Eureka Server)

最终效果:订单服务调用商品服务获取商品信息。

第一步:创建父工程项目(可跳过,用于统一管理子模块)

在之前的spring-cloud-demo中,我们将其作为父项目。

修改pom.xml,添加Spring Cloud依赖:

<!-- spring-cloud-demo/pom.xml -->
<project ...>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>spring-cloud-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <modules>
        <module>eureka-server</module>
        <module>product-service</module>
        <module>order-service</module>
    </modules>

    <properties>
        <java.version>17</java.version>
        <spring-cloud.version>2022.0.3</spring-cloud.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

第二步:创建 Eureka 服务注册中心

新建一个模块:右键项目 -> New -> Module -> Maven,名称 eureka-server,勾选create from archetype。

编辑 eureka-server/pom.xml 添加以下依赖:

<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-server</artifactId>
    </dependency>
</dependencies>

创建启动类:

// EurekaServerApplication.java
package com.example.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);
    }
}

修改 application.yml 配置:

server:
  port: 8761

eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

运行这个服务,访问 http://localhost:8761,你会看到Eureka的首页界面,目前还没有服务注册进来。

第三步:创建商品服务(Product Service)

创建模块 product-service,添加依赖:

<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>
</dependencies>

数据流转过程-1

创建启动类:

package com.example.productservice;

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

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

添加一个简单的Controller:

@RestController
@RequestMapping("/products")
public class ProductController {
    @GetMapping("/{id}")
    public String getProduct(@PathVariable String id) {
        return "Product ID: " + id;
    }
}

配置文件application.yml:

spring:
  application:
    name: product-service

server:
  port: 8081

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

启动后访问 http://localhost:8761,你会看到 product-service 已经注册上去了!

第四步:创建订单服务(Order Service),调用商品服务

创建模块 order-service,同样引入web和eureka客户端依赖:

<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>
</dependencies>

启动类加Feign支持:

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

写一个Feign客户端接口,让订单服务调用商品服务:

@FeignClient(name = "product-service")
public interface ProductClient {
    @GetMapping("/products/{id}")
    String getProduct(@PathVariable("id") String id);
}

创建Controller进行测试:

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

    private final ProductClient productClient;

    public OrderController(ProductClient productClient) {
        this.productClient = productClient;
    }

    @GetMapping("/product/{id}")
    public String getOrderProduct(@PathVariable String id) {
        return "Order calls Product: " + productClient.getProduct(id);
    }
}

配置文件:

spring:
  application:
    name: order-service

server:
  port: 8082

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

全部启动后,访问:http://localhost:8082/orders/product/1001,输出结果应该是:

Order calls Product: Product ID: 1001

恭喜!你现在拥有一个基本的微服务系统啦!


常见问题解答

Q1:我启动服务时报错“UnknownHostException: product-service”

答: 这说明服务没在Eureka上注册好,检查:

  1. 是否启用了 @EnableEurekaClient
  2. Eureka的地址是否正确
  3. 各个服务是否正常启动,日志是否有错误
  4. 等待几秒钟再试(Eureka同步有一定延迟)

Q2:@FeignClient调用失败,返回500或404?

答: 这可能是因为Feign没有正确整合Ribbon+Eureka。检查:

  1. 有没有开启 @EnableFeignClients
  2. Feign客户端的name是否对应服务名(如 name = "product-service")
  3. 两边路径是否一致(如@GetMapping("/products/{id}")

Q3:能不能不注册Eureka,直接调用?

答: 当然可以!但在真实环境中,这样做不具备扩展性和灵活性。强烈建议使用服务注册发现机制,否则后期很难维护。


学习建议:下一步学什么?

恭喜你完成了第一个Spring Cloud微服务项目!接下来你可以继续深入学习以下内容:

  1. Spring Cloud Gateway – 学习如何构建统一的API入口
  2. Resilience4j / Sentinel – 掌握服务容错能力
  3. Spring Cloud Alibaba Nacos – 国内流行的服务发现与配置中心
  4. 分布式事务 – Seata 等解决方案
  5. Docker 和 Kubernetes 基础知识 – 微服务最终要容器化部署

✅ 小提示:不要急于求成,先把本教程练熟,然后每学一个组件都在项目里集成尝试。


结语

学习微服务是一个循序渐进的过程,不要被各种专业术语吓退。记住一句话:微服务的本质就是把大系统变成小系统组合起来。

希望这篇《Spring Cloud从零开始》教程能为你打开通往微服务世界的大门。继续加油,下一个Spring Cloud高手就是你!💪

评论 0

最热最新
暂无评论
·赵建国Lv.1
0
影响力
0
文章
0
粉丝