适用对象:5年经验Java开发者,目标薪资18-22K
课时:约4小时 | 理论30% + 实战40% + 面试20% + 练习10%
┌───────────────────────────────────────────────────┐
│ Spring Cloud Alibaba │
├───────────────────────────────────────────────────┤
│ Nacos │ 服务注册 + 配置中心(替代Eureka+Config) │
│ Sentinel │ 流量控制 + 熔断降级(替代Hystrix) │
│ Seata │ 分布式事务(替代自行实现) │
│ Gateway │ API网关(路由、鉴权、限流) │
│ Dubbo │ RPC框架(可选,替代Feign) │
│ RocketMQ │ 消息队列(异步解耦、事务消息) │
└───────────────────────────────────────────────────┘
┌──────────────┐
│ Gateway │ :8080
│ (路由+鉴权) │
└──────┬───────┘
│
┌────────────┼────────────┐
↓ ↓ ↓
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ order-service│ │ inv-service │ │ pay-service │
│ 订单服务 │ │ 库存服务 │ │ 支付服务 │
│ :8081 │ │ :8082 │ │ :8083 │
└──────┬───────┘ └──────┬───────┘ └──────┬───────┘
│ │ │
└────────────────┼────────────────┘
│
┌─────────┼─────────┐
↓ ↓ ↓
┌─────────┐ ┌────────┐ ┌────────┐
│ Nacos │ │Sentinel│ │ Seata │
│ :8848 │ │ :8080 │ │ :8091 │
└─────────┘ └────────┘ └────────┘
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.5</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2022.0.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2022.0.4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
# ========== order-service的bootstrap.yml ==========
spring:
application:
name: order-service
cloud:
nacos:
# 配置中心
config:
server-addr: 127.0.0.1:8848
namespace: dev
group: DEFAULT_GROUP
file-extension: yml
# 共享配置(数据库、Redis等公共配置)
shared-configs:
- data-id: common-db.yml
group: DEFAULT_GROUP
refresh: true
- data-id: common-redis.yml
group: DEFAULT_GROUP
refresh: true
# 服务注册发现
discovery:
server-addr: 127.0.0.1:8848
namespace: dev
group: DEFAULT_GROUP
cluster-name: BJ # 机房标识
# ========== Nacos上 common-db.yml 的内容 ==========
spring:
datasource:
url: jdbc:mysql://localhost:3306/order_db?useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: ${MYSQL_PASSWORD}
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
maximum-pool-size: 20
minimum-idle: 5
connection-timeout: 30000
# ========== Nacos上 order-service.yml 的内容 ==========
server:
port: 8081
seata:
enabled: true
application-id: order-service
tx-service-group: my-tx-group
service:
vgroup-mapping:
my-tx-group: default
spring:
cloud:
sentinel:
transport:
dashboard: 127.0.0.1:8080
port: 8719
eager: true
# 自定义业务配置(支持动态刷新)
order:
max-retry: 3
timeout: 30000
enable-async: true
@RestController
@RequestMapping("/api/order/config")
@RefreshScope // Nacos配置变更时自动刷新
public class OrderConfigController {
@Value("${order.max-retry:3}")
private Integer maxRetry;
@Value("${order.timeout:30000}")
private Integer timeout;
@Value("${order.enable-async:true}")
private Boolean enableAsync;
@GetMapping("/info")
public Map<String, Object> getConfig() {
Map<String, Object> config = new HashMap<>();
config.put("maxRetry", maxRetry);
config.put("timeout", timeout);
config.put("enableAsync", enableAsync);
return config;
}
}
// =================== 启动类 ===================
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients(basePackages = "com.example.order.client")
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}
// =================== 远程调用客户端 ===================
@FeignClient(
name = "inventory-service",
fallbackFactory = InventoryClientFallback.class
)
public interface InventoryClient {
@PostMapping("/api/inventory/deduct")
Result<Void> deduct(@RequestBody InventoryDTO dto);
@GetMapping("/api/inventory/stock/{productId}")
Result<Integer> getStock(@PathVariable String productId);
}
// =================== Feign降级工厂 ===================
@Component
@Slf4j
public class InventoryClientFallback
implements FallbackFactory<InventoryClient> {
@Override
public InventoryClient create(Throwable cause) {
log.error("库存服务调用失败", cause);
return new InventoryClient() {
@Override
public Result<Void> deduct(InventoryDTO dto) {
return Result.fail("库存服务不可用,请稍后重试");
}
@Override
public Result<Integer> getStock(String productId) {
return Result.fail("库存服务不可用");
}
};
}
}
// =================== 订单业务服务 ===================
@Service
@Slf4j
public class OrderService {
@Autowired
private OrderMapper orderMapper;
@Autowired
private InventoryClient inventoryClient;
@Autowired
private PaymentClient paymentClient;
/**
* 创建订单 - 全局事务
*/
@GlobalTransactional(name = "create-order", rollbackFor = Exception.class)
@SentinelResource(value = "order.create",
blockHandler = "createBlockHandler")
public OrderVO createOrder(CreateOrderRequest request) {
log.info("创建订单: {}", request);
// 1. 创建订单
Order order = new Order();
order.setOrderNo(IdWorker.getIdStr());
order.setUserId(request.getUserId());
order.setProductId(request.getProductId());
order.setQuantity(request.getQuantity());
order.setAmount(request.getAmount());
order.setStatus(OrderStatus.CREATED);
order.setCreateTime(LocalDateTime.now());
orderMapper.insert(order);
// 2. 远程调用:扣减库存
InventoryDTO invDTO = new InventoryDTO();
invDTO.setProductId(order.getProductId());
invDTO.setQuantity(order.getQuantity());
invDTO.setOrderNo(order.getOrderNo());
Result<Void> invResult = inventoryClient.deduct(invDTO);
if (!invResult.isSuccess()) {
throw new BusinessException("库存扣减失败");
}
// 3. 远程调用:冻结支付金额
PaymentDTO payDTO = new PaymentDTO();
payDTO.setUserId(order.getUserId());
payDTO.setAmount(order.getAmount());
payDTO.setOrderNo(order.getOrderNo());
Result<Void> payResult = paymentClient.freeze(payDTO);
if (!payResult.isSuccess()) {
throw new BusinessException("支付冻结失败");
}
// 4. 更新订单状态
order.setStatus(OrderStatus.PAID);
orderMapper.updateStatus(order.getOrderNo(), OrderStatus.PAID);
return OrderVO.from(order);
}
public OrderVO createBlockHandler(CreateOrderRequest request,
BlockException ex) {
throw new BusinessException("系统繁忙,请稍后重试");
}
}
# ========== inventory-service bootstrap.yml ==========
spring:
application:
name: inventory-service
cloud:
nacos:
config:
server-addr: 127.0.0.1:8848
namespace: dev
file-extension: yml
shared-configs:
- data-id: common-db.yml
group: DEFAULT_GROUP
refresh: true
discovery:
server-addr: 127.0.0.1:8848
namespace: dev
@Service
@Slf4j
public class InventoryService {
@Autowired
private InventoryMapper inventoryMapper;
@SentinelResource(value = "inventory.deduct",
blockHandler = "deductBlockHandler",
fallback = "deductFallback")
@Transactional(rollbackFor = Exception.class)
public void deduct(String productId, Integer quantity, String orderNo) {
log.info("扣减库存: productId={}, quantity={}", productId, quantity);
int rows = inventoryMapper.deductStock(productId, quantity);
if (rows == 0) {
throw new BusinessException("库存不足");
}
// 记录操作流水
InventoryLog log = new InventoryLog();
log.setOrderNo(orderNo);
log.setProductId(productId);
log.setQuantity(quantity);
log.setType("DEDUCT");
inventoryMapper.insertLog(log);
}
public void deductBlockHandler(String productId, Integer quantity,
String orderNo, BlockException ex) {
throw new BusinessException("库存服务限流中");
}
public void deductFallback(String productId, Integer quantity,
String orderNo, Throwable t) {
log.error("库存扣降级: productId={}", productId, t);
throw new BusinessException("库存服务异常");
}
}
@RestController
@RequestMapping("/api/inventory")
public class InventoryController {
@Autowired
private InventoryService inventoryService;
@PostMapping("/deduct")
public Result<Void> deduct(@RequestBody InventoryDTO dto) {
inventoryService.deduct(dto.getProductId(),
dto.getQuantity(), dto.getOrderNo());
return Result.success();
}
}
@Service
@Slf4j
public class PaymentService {
@Autowired
private AccountMapper accountMapper;
@Transactional(rollbackFor = Exception.class)
public void freeze(Long userId, BigDecimal amount, String orderNo) {
log.info("冻结金额: userId={}, amount={}", userId, amount);
Account account = accountMapper.selectByUserId(userId);
if (account == null) {
throw new BusinessException("账户不存在");
}
if (account.getAvailableAmount().compareTo(amount) < 0) {
throw new BusinessException("余额不足");
}
accountMapper.freezeAmount(userId, amount);
}
}
# ========== gateway-service application.yml ==========
server:
port: 8000
spring:
application:
name: gateway-service
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
namespace: dev
gateway:
# 路由配置
routes:
- id: order-service
uri: lb://order-service
predicates:
- Path=/api/order/**
filters:
- StripPrefix=0
- name: CircuitBreaker
args:
name: orderCircuit
fallbackUri: forward:/fallback/order
- id: inventory-service
uri: lb://inventory-service
predicates:
- Path=/api/inventory/**
filters:
- StripPrefix=0
- id: payment-service
uri: lb://payment-service
predicates:
- Path=/api/payment/**
filters:
- StripPrefix=0
# 全局CORS配置
globalcors:
cors-configurations:
'[/**]':
allowed-origins: "*"
allowed-methods: "*"
allowed-headers: "*"
# Sentinel网关限流
sentinel:
transport:
dashboard: 127.0.0.1:8080
eager: true
# 网关限流规则(在Nacos或Sentinel Dashboard配置)
scg:
fallback:
mode: response
response-status: 429
response-body: '{"code":429,"message":"请求过于频繁"}'
@Component
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {
private static final List<String> WHITE_LIST = Arrays.asList(
"/api/user/login",
"/api/user/register",
"/api/seckill/token"
);
@Override
public Mono<Void> filter(ServerWebExchange exchange,
GatewayFilterChain chain) {
String path = exchange.getRequest().getURI().getPath();
// 白名单放行
if (WHITE_LIST.stream().anyMatch(path::startsWith)) {
return chain.filter(exchange);
}
// 获取Token
String token = exchange.getRequest().getHeaders()
.getFirst("Authorization");
if (StringUtils.isBlank(token) || !token.startsWith("Bearer ")) {
log.warn("请求未携带Token: path={}", path);
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
try {
// 解析JWT Token
String jwt = token.substring(7);
Claims claims = JwtUtil.parseToken(jwt);
String userId = claims.getSubject();
// 将用户信息传递到下游服务
ServerHttpRequest request = exchange.getRequest()
.mutate()
.header("X-User-Id", userId)
.build();
return chain.filter(exchange.mutate().request(request).build());
} catch (JwtException e) {
log.warn("Token无效: path={}", path);
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
}
@Override
public int getOrder() {
return -100; // 优先级最高
}
}
回答要点:
1. 客户端通过长轮询(Long Polling)监听配置变化
2. Nacos 2.x使用gRPC长连接替代长轮询,实时性更高
3. 配置变更时,服务端推送变更通知给客户端
4. 客户端收到通知后拉取最新配置
5. Spring Cloud通过@RefreshScope注解或@NacosValue(autoRefreshed=true)实现Bean的动态刷新
6. 注意:@Value需要配合@RefreshScope才能动态刷新,否则只在启动时读取一次
回答要点:
spring.cloud.nacos.discovery.ephemeral=false| 维度 | Gateway | Nginx |
|---|---|---|
| 语言 | Java | C |
| 性能 | 中 | 极高 |
| 扩展性 | 强(Java过滤器) | 中(Lua脚本) |
| 鉴权集成 | 直接集成Spring Security | 需额外模块 |
| 路由动态更新 | 支持(Nacos联动) | 需重载配置 |
| 适用层级 | 应用层网关 | 流量层网关 |
最佳实践:Nginx在最前端做负载均衡和静态资源,Gateway在应用层做路由、鉴权、限流。
实现基于Nacos元数据的灰度路由。
要求:
1. 库存服务部署v1和v2两个版本
2. v2版本在Nacos元数据中标记version=v2
3. Gateway根据请求头X-Gray-Version路由到对应版本
4. 请实现Gateway的自定义路由过滤器
将单机限流升级为集群限流。
# 提示:配置Sentinel集群限流Server
# 需要指定一个节点作为Token Server
spring:
cloud:
sentinel:
datasource:
flow:
nacos:
server-addr: 127.0.0.1:8848
data-id: sentinel-flow-rules
rule-type: flow
集成SkyWalking或Zipkin,实现三服务调用的全链路追踪。
要求:
1. 每个服务接入agent
2. 能看到完整的调用链路和耗时
3. 配置告警规则:RT > 1s 告警
| Spring Boot | Spring Cloud | Spring Cloud Alibaba |
|---|---|---|
| 3.1.x | 2022.0.x | 2022.0.0.0 |
| 3.0.x | 2022.0.x | 2022.0.0.0 |
| 2.7.x | 2021.0.x | 2021.0.5.0 |
| 2.6.x | 2021.0.x | 2021.0.5.0 |
上一篇:P4-03-分布式事务实战
下一篇:P4-05-DDD架构实践