一、微服务厨房理论(秒懂核心组件)
想象你要开一家餐厅:
- 服务员注册表 = Eureka(记录所有服务员信息)
- 传菜机器人 = Ribbon(智能分配任务)
- 对讲机 = Feign(服务间通信)
- 备用厨师 = Hystrix(防止主厨累垮)
二、环境准备(5分钟搞定)
1. 技术选型
3.1.5
2022.0.4
2. 统一父工程(厨房总控台)
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
三、三大核心服务搭建(含完整代码)
1. 服务注册中心(Eureka服务员名单)
// 1. 启动类
@SpringBootApplication
@EnableEurekaServer // 开启注册中心
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
// 2. 配置文件(application.yml)
server:
port: 8761
eureka:
client:
register-with-eureka: false # 自己不注册自己
fetch-registry: false
验证:访问 http://localhost:8761 看到Eureka控制台
2. 订单服务(生产者)
// 1. 启动类
@SpringBootApplication
@EnableDiscoveryClient // 注册到Eureka
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}
// 2. 控制器
@RestController
@RequestMapping("/orders")
public class OrderController {
@GetMapping("/{id}")
public String getOrder(@PathVariable Long id) {
return "订单"+id+": iPhone15 1台";
}
}
// 3. 配置文件
server:
port: 8081
spring:
application:
name: order-service
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
3. 用户服务(消费者)
// 1. 启动类
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients // 开启Feign
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
}
// 2. Feign客户端(自动负载均衡)
@FeignClient(name = "order-service")
public interface OrderClient {
@GetMapping("/orders/{id}")
String getOrder(@PathVariable Long id);
}
// 3. 控制器
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private OrderClient orderClient;
@GetMapping("/{userId}/orders")
public String getUserOrder(@PathVariable Long userId) {
return "用户"+userId+"的订单:" + orderClient.getOrder(1L);
}
}
// 4. 配置文件
server:
port: 8082
spring:
application:
name: user-service
四、服务调用验证(Postman测试)
- 查看注册中心
Eureka控制台显示两个服务:order-service 和 user-service - 直接调用订单服务
GET http://localhost:8081/orders/1 → 返回订单信息 - 通过用户服务间接调用
GET http://localhost:8082/users/1001/orders → 显示用户关联订单
五、熔断保护(Hystrix防雪崩)
// 1. 添加依赖
org.springframework.cloud
spring-cloud-starter-netflix-hystrix
// 2. 启动类添加注解
@EnableCircuitBreaker
// 3. 定义降级方法
@GetMapping("/{userId}/orders")
@HystrixCommand(fallbackMethod = "getOrderFallback")
public String getUserOrder(@PathVariable Long userId) {
// 原始逻辑
}
public String getOrderFallback(Long userId) {
return "服务繁忙,请稍后再试";
}
六、常见报错解决方案
- 服务无法注册
检查Eureka地址是否正确
确认spring.application.name是否唯一 - UnknownHostException
服务名是否拼写错误
Ribbon需要添加负载均衡注解 - Hystrix未生效
检查是否添加@EnableCircuitBreaker
确认方法签名与fallback一致
七、架构升级路线图
- 配置中心 → Spring Cloud Config
- 网关路由 → Spring Cloud Gateway
- 链路追踪 → Sleuth + Zipkin
- 安全认证 → Spring Security OAuth2
跟着这个指南操作,2小时内就能搭建出可商用的微服务基础架构!
如果您觉得不错,请给作者一个三连支持一下~~~~~