18.9.1 CAP定理与BASE理论应用

1. CAP定理基础概念

1.1 CAP定理原理

public class CAPTheoremPrinciple {
    
    /*
     * CAP定理核心概念:
     * 
     * C - Consistency (一致性)
     *     所有节点在同一时间看到的数据是一致的
     * 
     * A - Availability (可用性)
     *     系统在任何时候都能提供服务
     * 
     * P - Partition Tolerance (分区容错性)
     *     系统能够容忍网络分区故障
     * 
     * CAP定理:分布式系统最多只能满足CAP中的两个特性
     * 
     * 常见组合:
     * - CP系统:强一致性,牺牲可用性(如HBase、Redis Cluster)
     * - AP系统:高可用性,牺牲一致性(如Cassandra、DynamoDB)
     * - CA系统:理论存在,实际不可能(网络分区不可避免)
     */
    
    public void demonstrateCAPTheorem() {
        System.out.println("=== CAP定理演示 ===");
        
        demonstrateCPSystem();
        demonstrateAPSystem();
        demonstratePartitionScenario();
    }
    
    private void demonstrateCPSystem() {
        System.out.println("--- CP系统演示 ---");
        
        CPDistributedSystem cpSystem = new CPDistributedSystem();
        
        System.out.println("1. 正常情况下的读写操作:");
        cpSystem.write("key1", "value1");
        String value = cpSystem.read("key1");
        System.out.println("读取结果: " + value);
        
        System.out.println("\n2. 网络分区情况:");
        cpSystem.simulateNetworkPartition();
        
        try {
            cpSystem.write("key2", "value2");
        } catch (Exception e) {
            System.out.println("写入失败: " + e.getMessage());
        }
        
        System.out.println("CP系统特点: 保证一致性,牺牲可用性\n");
    }
    
    private void demonstrateAPSystem() {
        System.out.println("--- AP系统演示 ---");
        
        APDistributedSystem apSystem = new APDistributedSystem();
        
        System.out.println("1. 正常情况下的读写操作:");
        apSystem.write("key1", "value1");
        String value = apSystem.read("key1");
        System.out.println("读取结果: " + value);
        
        System.out.println("\n2. 网络分区情况:");
        apSystem.simulateNetworkPartition();
        
        apSystem.write("key2", "value2");
        String value2 = apSystem.read("key2");
        System.out.println("分区后读取: " + value2);
        
        System.out.println("AP系统特点: 保证可用性,允许数据不一致\n");
    }
    
    private void demonstratePartitionScenario() {
        System.out.println("--- 网络分区场景分析 ---");
        
        NetworkPartitionSimulator simulator = new NetworkPartitionSimulator();
        
        System.out.println("1. 模拟网络分区:");
        simulator.createPartition();
        
        System.out.println("2. CP系统响应:");
        simulator.testCPSystemInPartition();
        
        System.out.println("3. AP系统响应:");
        simulator.testAPSystemInPartition();
        
        System.out.println("4. 分区恢复:");
        simulator.healPartition();
    }
}

// CP系统实现
class CPDistributedSystem {
    private java.util.Map<String, String> data = new java.util.concurrent.ConcurrentHashMap<>();
    private boolean networkPartitioned = false;
    private int replicationFactor = 3;
    private int requiredAcks = 2; // 需要至少2个节点确认
    
    public void write(String key, String value) {
        if (networkPartitioned) {
            throw new RuntimeException("网络分区,无法保证一致性,拒绝写入");
        }
        
        System.out.println("  执行强一致性写入:");
        System.out.println("    等待 " + requiredAcks + " 个节点确认...");
        
        // 模拟等待多个节点确认
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        
        data.put(key, value);
        System.out.println("    写入成功: " + key + " = " + value);
    }
    
    public String read(String key) {
        if (networkPartitioned) {
            throw new RuntimeException("网络分区,无法保证一致性,拒绝读取");
        }
        
        System.out.println("  执行强一致性读取:");
        System.out.println("    从主节点读取最新数据");
        
        return data.get(key);
    }
    
    public void simulateNetworkPartition() {
        this.networkPartitioned = true;
        System.out.println("  网络分区发生,系统进入只读模式");
    }
}

// AP系统实现
class APDistributedSystem {
    private java.util.Map<String, String> nodeA = new java.util.concurrent.ConcurrentHashMap<>();
    private java.util.Map<String, String> nodeB = new java.util.concurrent.ConcurrentHashMap<>();
    private boolean networkPartitioned = false;
    
    public void write(String key, String value) {
        System.out.println("  执行最终一致性写入:");
        
        if (!networkPartitioned) {
            // 正常情况,写入所有节点
            nodeA.put(key, value);
            nodeB.put(key, value);
            System.out.println("    写入所有节点: " + key + " = " + value);
        } else {
            // 分区情况,只写入可用节点
            nodeA.put(key, value);
            System.out.println("    写入可用节点A: " + key + " = " + value);
            System.out.println("    节点B暂时不可达,稍后同步");
        }
    }
    
    public String read(String key) {
        System.out.println("  执行最终一致性读取:");
        
        if (!networkPartitioned) {
            System.out.println("    从就近节点读取");
            return nodeA.get(key);
        } else {
            System.out.println("    从可用节点A读取");
            return nodeA.get(key);
        }
    }
    
    public void simulateNetworkPartition() {
        this.networkPartitioned = true;
        System.out.println("  网络分区发生,系统继续提供服务");
    }
}

// 网络分区模拟器
class NetworkPartitionSimulator {
    
    public void createPartition() {
        System.out.println("  创建网络分区:");
        System.out.println("    节点A和节点B之间网络中断");
        System.out.println("    客户端只能访问节点A");
    }
    
    public void testCPSystemInPartition() {
        System.out.println("    CP系统: 检测到分区,停止服务保证一致性");
        System.out.println("    优点: 数据强一致");
        System.out.println("    缺点: 服务不可用");
    }
    
    public void testAPSystemInPartition() {
        System.out.println("    AP系统: 继续提供服务,允许数据不一致");
        System.out.println("    优点: 服务持续可用");
        System.out.println("    缺点: 数据可能不一致");
    }
    
    public void healPartition() {
        System.out.println("  网络分区恢复:");
        System.out.println("    节点间网络连接恢复");
        System.out.println("    开始数据同步和一致性修复");
    }
}

2. BASE理论详解

2.1 BASE理论原理

public class BASETheoryPrinciple {
    
    /*
     * BASE理论核心概念:
     * 
     * BA - Basically Available (基本可用)
     *      系统在出现故障时,允许损失部分可用性
     *      如响应时间增加、功能降级等
     * 
     * S - Soft State (软状态)
     *     系统中的数据可以存在中间状态
     *     允许系统在不同节点间的数据副本存在延时
     * 
     * E - Eventually Consistent (最终一致性)
     *     系统中所有数据副本,在经过一段时间后
     *     最终能够达到一致的状态
     * 
     * BASE理论是对CAP定理的延伸,通过牺牲强一致性
     * 来获得更好的可用性,适合大规模分布式系统
     */
    
    public void demonstrateBASETheory() {
        System.out.println("=== BASE理论演示 ===");
        
        demonstrateBasicallyAvailable();
        demonstrateSoftState();
        demonstrateEventualConsistency();
    }
    
    private void demonstrateBasicallyAvailable() {
        System.out.println("--- 基本可用演示 ---");
        
        ECommerceSystem ecommerce = new ECommerceSystem();
        
        System.out.println("1. 正常情况:");
        ecommerce.processOrder("order-001", "user-123");
        
        System.out.println("\n2. 系统负载过高:");
        ecommerce.simulateHighLoad();
        ecommerce.processOrder("order-002", "user-124");
        
        System.out.println("\n3. 部分服务故障:");
        ecommerce.simulatePartialFailure();
        ecommerce.processOrder("order-003", "user-125");
        
        System.out.println("基本可用: 系统在故障时仍能提供核心服务\n");
    }
    
    private void demonstrateSoftState() {
        System.out.println("--- 软状态演示 ---");
        
        DistributedCache cache = new DistributedCache();
        
        System.out.println("1. 数据写入:");
        cache.put("user:123", "张三");
        
        System.out.println("2. 不同节点的状态:");
        cache.showNodeStates();
        
        System.out.println("3. 数据同步过程:");
        cache.syncNodes();
        cache.showNodeStates();
        
        System.out.println("软状态: 允许系统存在中间状态\n");
    }
    
    private void demonstrateEventualConsistency() {
        System.out.println("--- 最终一致性演示 ---");
        
        EventualConsistencyDemo demo = new EventualConsistencyDemo();
        
        System.out.println("1. 用户注册:");
        demo.registerUser("user-001", "alice@example.com");
        
        System.out.println("2. 检查各系统状态:");
        demo.checkSystemStates();
        
        System.out.println("3. 等待数据同步:");
        demo.waitForConsistency();
        
        System.out.println("4. 最终一致性达成:");
        demo.checkFinalConsistency();
        
        System.out.println("最终一致性: 经过时间后所有副本达到一致\n");
    }
}

剩余60%内容,订阅专栏后可继续查看/也可单篇购买

Java面试圣经 文章被收录于专栏

Java面试圣经,带你练透java圣经

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务