Skip to content

以下是使用 Spring Cloud 搭建微服务架构的详细步骤,涵盖服务注册中心、配置中心、API 网关、服务间通信等核心组件。我们将创建一个包含以下模块的示例项目:

  1. 服务注册中心(Eureka Server)
  2. 配置中心(Spring Cloud Config Server)
  3. API 网关(Spring Cloud Gateway)
  4. 用户服务(User Service)
  5. 订单服务(Order Service)

一、环境准备

• JDK 11+
• Maven 3.6+
• IDE(IntelliJ IDEA 或 Eclipse)
• Spring Boot 2.7.x
• Spring Cloud 2021.0.x


二、项目结构

bash
microservices-demo/
├── config-server/           # 配置中心
├── eureka-server/           # 服务注册中心
├── api-gateway/             # API 网关
├── user-service/            # 用户服务
└── order-service/           # 订单服务

三、详细步骤

1. 服务注册中心(Eureka Server)

作用:管理所有微服务的注册与发现。

(1) 创建 Eureka Server 项目

使用 Spring Initializr 生成项目,添加依赖:
Eureka Server

(2) 主类配置
java
// EurekaServerApplication.java
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}
(3) 配置文件 application.yml
yaml
server:
  port: 8761

eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: false  # 不向自己注册
    fetch-registry: false        # 不从自己获取注册表
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
(4) 启动并访问

访问 http://localhost:8761,可以看到 Eureka 控制台。


2. 配置中心(Spring Cloud Config Server)

作用:集中管理所有微服务的配置文件。

(1) 创建 Config Server 项目

添加依赖:
Config Server

(2) 主类配置
java
// ConfigServerApplication.java
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication.class, args);
    }
}
(3) 配置文件 application.yml
yaml
server:
  port: 8888

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/your-repo/config-repo  # Git 仓库地址
          search-paths: configs                          # 配置文件目录
(4) Git 仓库配置

在 Git 仓库中创建配置文件(如 user-service-dev.yml):

yaml
# user-service-dev.yml
server:
  port: 8081

spring:
  application:
    name: user-service
(5) 启动配置中心

启动后,其他服务将通过 http://localhost:8888 获取配置。


3. 用户服务(User Service)

作用:提供用户相关接口。

(1) 创建 User Service 项目

添加依赖:
Eureka Discovery Client
Config Client
Spring Web

(2) 主类配置
java
// UserServiceApplication.java
@SpringBootApplication
@EnableDiscoveryClient
public class UserServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserServiceApplication.class, args);
    }
}
(3) 配置文件 bootstrap.yml
yaml
spring:
  application:
    name: user-service    # 与服务注册中心的应用名一致
  cloud:
    config:
      uri: http://localhost:8888  # 配置中心地址
      profile: dev                # 激活的配置环境
(4) 创建用户接口
java
// UserController.java
@RestController
@RequestMapping("/users")
public class UserController {
    @GetMapping("/{id}")
    public String getUser(@PathVariable Long id) {
        return "User " + id;
    }
}
(5) 启动服务

服务将自动注册到 Eureka,并从配置中心加载配置。


4. 订单服务(Order Service)

作用:提供订单接口,并调用用户服务。

(1) 创建 Order Service 项目

添加依赖:
Eureka Discovery Client
Config Client
Spring Web
OpenFeign

(2) 主类配置
java
// OrderServiceApplication.java
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class OrderServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderServiceApplication.class, args);
    }
}
(3) 配置文件 bootstrap.yml
yaml
spring:
  application:
    name: order-service
  cloud:
    config:
      uri: http://localhost:8888
      profile: dev
(4) 使用 Feign 调用用户服务
java
// UserServiceClient.java
@FeignClient(name = "user-service", fallback = UserServiceFallback.class)
public interface UserServiceClient {
    @GetMapping("/users/{id}")
    String getUser(@PathVariable Long id);
}

// UserServiceFallback.java
@Component
public class UserServiceFallback implements UserServiceClient {
    @Override
    public String getUser(Long id) {
        return "Fallback: User service is unavailable";
    }
}
(5) 订单接口
java
// OrderController.java
@RestController
@RequestMapping("/orders")
public class OrderController {
    @Autowired
    private UserServiceClient userServiceClient;

    @GetMapping("/{id}")
    public String getOrder(@PathVariable Long id) {
        String user = userServiceClient.getUser(1L);
        return "Order " + id + " for " + user;
    }
}
(6) 启动服务

订单服务将注册到 Eureka,并通过 Feign 调用用户服务。


5. API 网关(Spring Cloud Gateway)

作用:统一入口,路由、鉴权、限流等。

(1) 创建 Gateway 项目

添加依赖:
Gateway
Eureka Discovery Client

(2) 主类配置
java
// ApiGatewayApplication.java
@SpringBootApplication
@EnableDiscoveryClient
public class ApiGatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(ApiGatewayApplication.class, args);
    }
}
(3) 配置文件 application.yml
yaml
server:
  port: 8080

spring:
  cloud:
    gateway:
      routes:
        - id: user-service
          uri: lb://user-service
          predicates:
            - Path=/api/users/**
          filters:
            - StripPrefix=2
        - id: order-service
          uri: lb://order-service
          predicates:
            - Path=/api/orders/**
          filters:
            - StripPrefix=2
(4) 启动网关

通过 http://localhost:8080/api/users/1 访问用户服务,http://localhost:8080/api/orders/1 访问订单服务。


四、验证与测试

  1. 检查 Eureka 控制台
    访问 http://localhost:8761,确认所有服务已注册。

  2. 测试服务调用
    • 直接调用用户服务:http://localhost:8081/users/1
    • 通过网关调用订单服务:http://localhost:8080/api/orders/1

  3. 验证熔断
    停止用户服务后,调用订单服务应返回回退信息。


五、关键配置说明

组件核心配置项作用
Eureka Servereureka.client.register-with-eureka=false禁止自身注册
Config Serverspring.cloud.config.server.git.uri指定 Git 仓库地址
Feign Client@FeignClient(name = "user-service")声明式服务调用
Gatewayspring.cloud.gateway.routes.uri=lb://user-service负载均衡路由到服务

六、扩展功能

  1. 分布式追踪
    集成 Sleuth + Zipkin,追踪请求链路。
  2. 安全认证
    使用 Spring Security + OAuth2 保护 API。
  3. 服务监控
    集成 Spring Boot Actuator + Prometheus + Grafana。
  4. 容器化部署
    使用 Docker 和 Kubernetes 编排服务。

七、常见问题

  1. 服务未注册到 Eureka
    • 检查 @EnableDiscoveryClient 注解是否添加。
    • 确认 bootstrap.yml 中的服务名与 Eureka 配置一致。

  2. 配置中心无法加载配置
    • 检查 Git 仓库路径是否正确。
    • 确认 bootstrap.yml 中的 spring.cloud.config.uri 指向 Config Server。

  3. Feign 调用失败
    • 确认 @EnableFeignClients 注解已启用。
    • 检查服务名是否与 Eureka 注册的名称一致。



通过以上步骤,成功搭建一个基于 Spring Cloud 的微服务架构,涵盖服务注册、配置管理、API 网关和容错机制。下一步可以结合 Docker 和 Kubernetes 实现容器化部署,进一步提升系统的弹性和可维护性。

✨ 网站运行时间: 3年11月15天 ❤️ 道阻且长,行则将至 - 微信号: heikedreamer