引言
Spring Cloud是微服务开发的全家桶。本文介绍其核心组件和应用。
一、服务注册与发现(Eureka)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @EnableEurekaServer @SpringBootApplication public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } }
server: port: 8761 eureka: client: register-with-eureka: false fetch-registry: false
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @EnableEurekaClient @SpringBootApplication public class ServiceApplication { public static void main(String[] args) { SpringApplication.run(ServiceApplication.class, args); } }
spring: application: name: user-service eureka: client: service-url: defaultZone: http:
|
二、服务调用(Feign)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| @FeignClient(name = "user-service") public interface UserClient { @GetMapping("/users/{id}") User getUser(@PathVariable Long id); }
@RestController public class OrderController { @Autowired private UserClient userClient; @GetMapping("/orders/{id}") public Order getOrder(@PathVariable Long id) { User user = userClient.getUser(id); return order; } }
|
三、API网关(Gateway)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| @SpringBootApplication public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } }
spring: cloud: gateway: routes: - id: user-service uri: lb: predicates: - Path=/api/users
|
四、配置中心(Config)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| @EnableConfigServer @SpringBootApplication public class ConfigServerApplication {}
@SpringBootApplication public class ServiceApplication { @Value("${my.config}") private String config; }
spring: cloud: config: uri: http: name: application profile: dev
|
五、熔断器(Resilience4j)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| @Service public class UserService { @Autowired private UserClient userClient; @CircuitBreaker(name = "userService", fallbackMethod = "fallback") public User getUser(Long id) { return userClient.getUser(id); } public User fallback(Long id, Exception e) { return new User(id, "Default User"); } }
resilience4j: circuitbreaker: instances: userService: failure-rate-threshold: 50 wait-duration-in-open-state: 10s
|
总结
Spring Cloud核心组件:
- Eureka:服务注册与发现
- Feign:声明式HTTP客户端
- Gateway:API网关
- Config:配置中心
- Resilience4j:熔断降级
参考资料