Skip to content

Spring Cloud

Spring Cloud 是微服务架构的一站式解决方案,提供分布式系统所需的组件。

核心组件

组件说明替代方案
Eureka服务注册与发现Nacos、Zookeeper
GatewayAPI 网关Spring Cloud Gateway
OpenFeign服务调用Dubbo
Ribbon负载均衡LoadBalancer
Hystrix熔断器Sentinel
Config配置中心Nacos Config
Sleuth链路追踪SkyWalking、Zipkin

快速开始

项目结构

├── cloud-eureka-server      # 注册中心
├── cloud-gateway            # 网关
├── cloud-user-service       # 用户服务
├── cloud-order-service      # 订单服务
└── cloud-common             # 公共模块

注册中心 Eureka

xml
<!-- pom.xml -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
yaml
# application.yml
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/
java
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}

服务提供者

yaml
spring:
  application:
    name: user-service

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true
java
@RestController
@RequestMapping("/users")
public class UserController {
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return new User(id, "User-" + id, 25);
    }
}

服务消费者 OpenFeign

xml
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
java
@EnableFeignClients

@SpringBootApplication
public class OrderApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }
}
java
@FeignClient(name = "user-service", fallback = UserFallback.class)
public interface UserClient {
    @GetMapping("/users/{id}")
    User getUser(@PathVariable("id") Long id);
}

// 降级处理
@Component
public class UserFallback implements UserClient {
    @Override
    public User getUser(Long id) {
        return new User(id, "默认用户", 0);
    }
}
java
@RestController
@RequestMapping("/orders")
public class OrderController {
    @Autowired
    private UserClient userClient;

    @GetMapping("/{userId}")
    public Order getOrder(@PathVariable Long userId) {
        User user = userClient.getUser(userId);
        return new Order(1L, userId, user.getName());
    }
}

API 网关 Gateway

xml
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
yaml
spring:
  cloud:
    gateway:
      routes:
        - id: user-service
          uri: lb://user-service
          predicates:
            - Path=/api/users/**
          filters:
            - StripPrefix=1

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

负载均衡

Ribbon

yaml
user-service:
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule

LoadBalancer

java
@Configuration
public class LoadBalancerConfig {
    @Bean
    public ReactorLoadBalancer<ServiceInstance> random() {
        return new RandomLoadBalancer(
            new DefaultServiceInstanceListTransformer(),
            ServiceInstance.class.getClassLoader()
        );
    }
}

@Service
public class UserService {
    @Autowired
    private LoadBalancerClient loadBalancer;

    public String getServiceUrl() {
        ServiceInstance instance = loadBalancer.choose("user-service");
        return instance.getUri().toString();
    }
}

熔断器 Hystrix

xml
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
java
@RestController
@RequestMapping("/orders")
@DefaultProperties(defaultFallback = "defaultFallback")
public class OrderController {

    @HystrixCommand(fallbackMethod = "getUserFallback",
                     commandProperties = {
        @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
        @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
        @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50")
    })
    @GetMapping("/{userId}")
    public String getOrder(@PathVariable Long userId) {
        return orderService.getOrder(userId);
    }

    public String getUserFallback(Long userId) {
        return "服务暂不可用,请稍后重试";
    }

    public String defaultFallback() {
        return "系统繁忙";
    }
}

总结

  1. 注册中心:Eureka/Nacos 服务注册与发现
  2. 服务调用:OpenFeign 声明式 HTTP 客户端
  3. 网关:Gateway 统一入口、路由、过滤
  4. 负载均衡:Ribbon/LoadBalancer
  5. 熔断降级:Hystrix/Sentinel

基于 VitePress 构建