Skip to content

可用性设计 ​

高可用设计是系统架构的重要目标,确保系统持续可用。

📋 核心要素 ​

  • 高可用架构:通过冗余和故障切换保证可用性
  • 熔断机制:防止级联故障,快速失败
  • 降级策略:在系统过载时,优先保证核心功能

🎯 高可用架构 ​

高可用架构设计:

🎯 熔断机制 ​

熔断器状态转换:

熔断器实现示例:

java
/**
 * 熔断器实现
 */
public class CircuitBreaker {
    private enum State {
        CLOSED,    // 关闭状态:正常处理请求
        OPEN,      // 打开状态:快速失败
        HALF_OPEN  // 半开状态:测试恢复
    }
    
    private State state = State.CLOSED;
    private int failureCount = 0;
    private int successCount = 0;
    private long lastFailureTime = 0;
    
    // 配置参数
    private final int failureThreshold = 5;      // 失败阈值
    private final long timeout = 60000;          // 超时时间(60秒)
    private final int halfOpenMaxRequests = 3;   // 半开状态最大请求数
    private int halfOpenRequestCount = 0;
    
    /**
     * 执行操作
     */
    public <T> T execute(Supplier<T> operation) {
        // 检查熔断器状态
        if (state == State.OPEN) {
            // 检查是否超时,转为半开状态
            if (System.currentTimeMillis() - lastFailureTime > timeout) {
                state = State.HALF_OPEN;
                halfOpenRequestCount = 0;
                successCount = 0;
            } else {
                // 快速失败
                throw new CircuitBreakerOpenException("Circuit breaker is OPEN");
            }
        }
        
        try {
            // 半开状态限制请求数
            if (state == State.HALF_OPEN) {
                if (halfOpenRequestCount >= halfOpenMaxRequests) {
                    throw new CircuitBreakerHalfOpenException("Too many requests in HALF_OPEN state");
                }
                halfOpenRequestCount++;
            }
            
            // 执行操作
            T result = operation.get();
            
            // 成功处理
            onSuccess();
            return result;
            
        } catch (Exception e) {
            // 失败处理
            onFailure();
            throw e;
        }
    }
    
    /**
     * 成功回调
     */
    private void onSuccess() {
        failureCount = 0;
        successCount++;
        
        // 半开状态下,如果连续成功,转为关闭状态
        if (state == State.HALF_OPEN) {
            if (successCount >= halfOpenMaxRequests) {
                state = State.CLOSED;
                halfOpenRequestCount = 0;
                successCount = 0;
            }
        }
    }
    
    /**
     * 失败回调
     */
    private void onFailure() {
        failureCount++;
        lastFailureTime = System.currentTimeMillis();
        
        // 失败次数超过阈值,打开熔断器
        if (failureCount >= failureThreshold) {
            state = State.OPEN;
        }
        
        // 半开状态下失败,重新打开熔断器
        if (state == State.HALF_OPEN) {
            state = State.OPEN;
            halfOpenRequestCount = 0;
        }
    }
    
    public State getState() {
        return state;
    }
}

🎯 降级策略 ​

降级策略示例:

java
/**
 * 带降级功能的服务
 */
@Service
public class ProductService {
    @Autowired
    private ProductRepository productRepository;
    
    @Autowired
    private RedisTemplate<String, Product> redisTemplate;
    
    /**
     * 获取商品详情(带降级)
     */
    @CircuitBreaker(fallbackMethod = "getProductFallback")
    public Product getProduct(Long id) {
        // 优先从缓存获取
        String cacheKey = "product:" + id;
        Product product = redisTemplate.opsForValue().get(cacheKey);
        if (product != null) {
            return product;
        }
        
        // 缓存未命中,从数据库获取
        product = productRepository.findById(id)
            .orElseThrow(() -> new ProductNotFoundException("Product not found: " + id));
        
        // 写入缓存
        redisTemplate.opsForValue().set(cacheKey, product, 3600, TimeUnit.SECONDS);
        
        return product;
    }
    
    /**
     * 降级方法:返回默认商品
     */
    public Product getProductFallback(Long id, Exception e) {
        logger.warn("Product service fallback for id: {}", id, e);
        
        // 降级策略1:返回默认商品
        Product defaultProduct = new Product();
        defaultProduct.setId(id);
        defaultProduct.setName("默认商品");
        defaultProduct.setPrice(BigDecimal.ZERO);
        defaultProduct.setDescription("服务暂时不可用,请稍后再试");
        
        return defaultProduct;
    }
}

上一章节:扩展性设计
下一章节:可靠性设计
返回目录:系统架构能力