Spring全家桶笔记十二:微服务架构与Spring Cloud

Spring全家桶笔记十二:微服务架构与Spring Cloud

微服务概述

微服务是一种架构风格,将单一应用程序划分为一组小的服务,服务之间互相协调、互相配合。

优点

  • 独立部署
  • 技术多样性
  • 故障隔离
  • 快速迭代

挑战

  • 运维复杂度
  • 分布式事务
  • 服务通信
  • 监控排查

Spring Cloud组件

组件 说明
Eureka 服务注册与发现
Ribbon 负载均衡
Feign 声明式HTTP客户端
Hystrix 服务熔断
Zuul API网关
Config 配置中心

服务注册与发现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Eureka Server
spring:
application:
name: eureka-server
server:
port: 8761

# Provider
spring:
application:
name: user-service
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true

服务调用

1
2
3
4
5
@FeignClient(name = "order-service")
public interface OrderClient {
@GetMapping("/order/{id}")
Order getOrder(@PathVariable("id") Long id);
}

配置中心

1
2
3
4
5
6
7
8
9
spring:
cloud:
config:
server:
git:
uri: https://github.com/config-repo
discovery:
enabled: true
service-id: config-server

服务网关

1
2
3
4
5
6
zuul:
routes:
user-service:
path: /user/**
url: http://localhost:8080
prefix: /api

总结

Spring Cloud提供了完整的微服务解决方案,帮助开发者快速构建分布式系统。