【Java】Spring Cloud 微服务架构入门:五大核心组件与分布式系统搭建
·
Spring Cloud 核心组件概述
Spring Cloud 为分布式系统开发提供了一套工具集,以下五大组件是微服务架构的核心:
- 服务注册与发现(Eureka):用于服务的自动注册与发现,实现动态扩容。
- 客户端负载均衡(Ribbon):在服务消费者端实现负载均衡策略。
- 声明式 REST 客户端(Feign):简化服务间的 HTTP 调用。
- 断路器(Hystrix):提供容错机制,防止服务雪崩。
- API 网关(Zuul/Gateway):统一路由、过滤和监控请求。
服务注册与发现(Eureka)
搭建 Eureka Server
- 添加 Maven 依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
- 主类启用 Eureka Server:
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
- 配置
application.yml:
server:
port: 8761
eureka:
client:
register-with-eureka: false # 不向自身注册
fetch-registry: false
服务注册(客户端)
- 客户端添加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
- 配置
application.yml:
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
客户端负载均衡(Ribbon)
Ribbon 默认集成在 Eureka 客户端中。通过 @LoadBalanced 注解启用:
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
调用服务时直接使用服务名(如 http://service-name/api),Ribbon 会自动负载均衡。
声明式调用(Feign)
- 添加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
- 主类启用 Feign:
@EnableFeignClients
@SpringBootApplication
public class Application { /* ... */ }
- 定义接口:
@FeignClient(name = "order-service")
public interface OrderClient {
@GetMapping("/orders")
List<Order> getOrders();
}
断路器(Hystrix)
- 添加依赖(已包含在
spring-cloud-starter-netflix-hystrix中):
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
- 主类启用 Hystrix:
@EnableCircuitBreaker
@SpringBootApplication
public class Application { /* ... */ }
- 在方法上添加
@HystrixCommand定义降级逻辑:
@HystrixCommand(fallbackMethod = "fallbackGetOrders")
public List<Order> getOrders() {
// 远程调用逻辑
}
API 网关(Spring Cloud Gateway)
- 添加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
- 配置路由规则(
application.yml):
spring:
cloud:
gateway:
routes:
- id: order-service
uri: lb://order-service
predicates:
- Path=/orders/**
分布式系统搭建流程
- 启动 Eureka Server 作为注册中心。
- 开发微服务(如订单服务、用户服务),注册到 Eureka。
- 通过 Feign 或 Ribbon 实现服务间调用。
- 使用 Hystrix 添加熔断保护。
- 通过 Gateway 统一暴露 API,实现鉴权、限流等。
注意事项
- 服务命名需唯一,避免冲突。
- 生产环境需配置 Eureka 高可用集群。
- 结合 Spring Cloud Config 实现配置中心管理。
更多推荐
所有评论(0)