【架构实战】Spring Cloud微服务实战入门

一、Spring Cloud是什么

Spring Cloud是基于Spring Boot的微服务开发框架,它提供了一系列工具,帮助开发者快速构建分布式系统的通用模式。

二、核心组件一览

组件 作用 替代方案
Eureka 服务注册与发现 Nacos、Zookeeper
Ribbon 客户端负载均衡 Feign、Spring Cloud LoadBalancer
Hystrix 熔断器 Sentinel
Zuul/Gateway API网关 Spring Cloud Gateway
Config 分布式配置 Nacos、Apollo
Sleuth 分布式追踪 Zipkin、Jaeger

三、快速开始

1. 服务注册中心 Eureka

xml 复制代码
    org.springframework.cloud
    spring-cloud-starter-netflix-eureka-server
yaml 复制代码
# application.yml
server:
  port: 8761
eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: false
    fetch-registry: false
java 复制代码
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}

2. 服务提供者

yaml 复制代码
# provider.yml
spring:
  application:
    name: user-service
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
java 复制代码
@RestController
@RequestMapping("/user")
public class UserController {
    
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return new User(id, "User" + id, 25);
    }
}

3. 服务消费者

java 复制代码
@RestController
public class OrderController {
    
    @Autowired
    private RestTemplate restTemplate;
    
    @GetMapping("/order/{userId}")
    public Order getOrder(@PathVariable Long userId) {
        // 调用用户服务
        User user = restTemplate.getForObject(
            "http://user-service/user/" + userId, 
            User.class
        );
        return new Order(userId, user.getName());
    }
}

四、服务间通信

RestTemplate方式

java 复制代码
@Configuration
public class RestConfig {
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

Feign方式(推荐)

java 复制代码
@FeignClient(name = "user-service")
public interface UserClient {
    @GetMapping("/user/{id}")
    User getUser(@PathVariable("id") Long id);
}

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private UserClient userClient;
    
    public Order getOrder(Long userId) {
        User user = userClient.getUser(userId);
        return new Order(userId, user.getName());
    }
}

五、熔断器 Hystrix

java 复制代码
@RestController
@RequestMapping("/order")
public class OrderController {
    
    @HystrixCommand(fallbackMethod = "getUserFallback")
    @GetMapping("/user/{id}")
    public User getUser(@PathVariable Long id) {
        return restTemplate.getForObject(
            "http://user-service/user/" + id, 
            User.class
        );
    }
    
    // 降级方法
    public User getUserFallback(Long id) {
        return new User(id, "默认用户", 0);
    }
}

六、总结

Spring Cloud提供了一整套微服务解决方案,但组件众多,需要根据实际需求选择。推荐从Spring Cloud Alibaba开始,它集成度更高,文档更完善。

思考题:在你的项目中使用了哪些Spring Cloud组件?有没有遇到什么坑?


个人观点,仅供参考

相关推荐
深圳尚鼎5 分钟前
芯片新架构大幅降低空间望远镜计算功耗及其与工业防潮柜的关系
架构
weixin1997010801615 分钟前
☁️《抖店API基础¥0.018/百次·增值¥0.05/百次:云内云外价差架构实战》(附Python源码)
开发语言·python·架构
运维行者_1 小时前
网络监控与ITSM集成:从告警到工单,实现运维自动化闭环
开发语言·网络·分布式·后端·架构·flask·php
hhb_6182 小时前
AI编程协同架构:智能驱动开发新时代
架构·ai编程
木叶丸2 小时前
从 Loop 到 Graph:AI 智能体协作系统工程指南
前端·后端·架构
cxr8284 小时前
第四章 查询与推理能力
人工智能·架构·知识图谱·智能体
猿长大人5 小时前
C# | MediatR 入门指南:后端架构解耦
分布式·后端·架构·c#·.net
人间凡尔赛5 小时前
Kubernetes十周年:从Cloud Native到AI Native的架构范式跃迁
后端·云原生·架构
一个天蝎座 白勺 程序猿5 小时前
MongoDB迁移新范式|从烟囱式孤岛到KES-AI融合架构
人工智能·mongodb·架构·kingbasees
AI 小老六5 小时前
Agent Runtime 如何用 Session、Memory、User Profile 和 Skill 实现外部学习
服务器·人工智能·学习·ai·架构·自动化