Spring Cloud
Spring Cloud 是微服务架构的一站式解决方案,提供分布式系统所需的组件。
核心组件
| 组件 | 说明 | 替代方案 |
|---|---|---|
| Eureka | 服务注册与发现 | Nacos、Zookeeper |
| Gateway | API 网关 | 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: truejava
@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.RoundRobinRuleLoadBalancer
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 "系统繁忙";
}
}总结
- 注册中心:Eureka/Nacos 服务注册与发现
- 服务调用:OpenFeign 声明式 HTTP 客户端
- 网关:Gateway 统一入口、路由、过滤
- 负载均衡:Ribbon/LoadBalancer
- 熔断降级:Hystrix/Sentinel
