Spring Cloud进阶:熔断、限流与链路追踪
Spring Cloud进阶:熔断、限流与链路追踪
概述
微服务架构需要完善的治理机制。本教程介绍熔断、限流和链路追踪的实现。
1. 熔断器(Resilience4j)
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.retry.annotation.Retry;
import io.github.resilience4j.timelimiter.annotation.TimeLimiter;
import org.springframework.stereotype.Service;
@Service
public class ResilienceService {
@CircuitBreaker(name = "userService", fallbackMethod = "fallback")
public String callExternalService() {
// 可能失败的外部调用
return restTemplate.getForObject("http://external-service/api", String.class);
}
@Retry(name = "userService")
public String retryableService() {
// 可重试的操作
return callExternalService();
}
public String fallback(Throwable t) {
return "降级响应";
}
}
# application.yml
resilience4j:
circuitbreaker:
instances:
userService:
slidingWindowSize: 10
failureRateThreshold: 50
waitDurationInOpenState: 10s
permittedNumberOfCallsInHalfOpenState: 3
retry:
instances:
userService:
maxAttempts: 3
waitDuration: 500
2. 限流(Sentinel)
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.stereotype.Service;
@Service
public class RateLimitingService {
@SentinelResource(value = "limitedResource", blockHandler = "handleBlock")
public String limitedResource() {
return "正常响应";
}
public String handleBlock(BlockException ex) {
return "限流响应";
}
}
# application.yml
spring:
cloud:
sentinel:
transport:
dashboard: localhost:8080
datasource:
flow:
nacos:
server-addr: localhost:8848
data-id: flow-rules
group-id: SENTINEL_GROUP
3. 链路追踪(Sleuth + Zipkin)
import brave.sampler.Sampler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TracingConfig {
@Bean
public Sampler defaultSampler() {
return Sampler.ALWAYS_SAMPLE;
}
}
# application.yml
spring:
sleuth:
sampler:
probability: 1.0
zipkin:
base-url: http://localhost:9411
4. 实际应用示例
熔断降级
@Service
public class OrderService {
private final UserClient userClient;
private final ProductClient productClient;
@CircuitBreaker(name = "user-service", fallbackMethod = "getUserFallback")
public User getUser(Long userId) {
return userClient.getUser(userId);
}
@CircuitBreaker(name = "product-service", fallbackMethod = "getProductFallback")
public Product getProduct(Long productId) {
return productClient.getProduct(productId);
}
public User getUserFallback(Long userId, Throwable t) {
return new User(userId, "未知用户", 0);
}
public Product getProductFallback(Long productId, Throwable t) {
return new Product(productId, "未知商品", 0.0);
}
}
分布式日志
import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;
public class TracingFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) {
String traceId = request.getHeader("X-Trace-Id");
MDC.put("traceId", traceId);
try {
filterChain.doFilter(request, response);
} finally {
MDC.clear();
}
}
}
5. 最佳实践
- 熔断降级:保护系统免受级联故障
- 限流控制:防止系统过载
- 链路追踪:快速定位问题
- 监控告警:实时监控系统状态
- 容错设计:设计高可用的微服务
总结
熔断、限流和链路追踪是微服务治理的重要组成部分。掌握这些技术,可以构建稳定、可靠的微服务系统。