程序员必备的十大技能(进阶版)之分布式核心技术(四)

简介: 教程来源 http://rvtst.cn/ 本节详解分布式锁与消息中间件核心实践:Redis红锁(RedLock)通过多节点多数派机制保障高可用与互斥性;ZooKeeper锁基于临时顺序节点实现强一致性;消息队列则覆盖可靠性(同步发送+手动确认)、幂等性(Redis/DB去重)及顺序性(有序发送与消费)。

五、分布式锁

5.1 Redis分布式锁(红锁 RedLock)

public class RedisDistributedLock {

    private final StringRedisTemplate redisTemplate;
    private final String lockKeyPrefix = "lock:";
    private final long defaultExpireMs = 30000;  // 默认30秒过期

    // 获取锁(带重试)
    public boolean tryLock(String key, String value, long expireMs, int retryTimes, long retryIntervalMs) {
        for (int i = 0; i < retryTimes; i++) {
            if (tryLock(key, value, expireMs)) {
                return true;
            }
            try {
                Thread.sleep(retryIntervalMs);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return false;
            }
        }
        return false;
    }

    // 获取锁(SET NX EX)
    public boolean tryLock(String key, String value, long expireMs) {
        String fullKey = lockKeyPrefix + key;
        Boolean success = redisTemplate.opsForValue()
            .setIfAbsent(fullKey, value, Duration.ofMillis(expireMs));
        return Boolean.TRUE.equals(success);
    }

    // 释放锁(Lua脚本保证原子性,只释放自己持有的锁)
    public boolean unlock(String key, String value) {
        String fullKey = lockKeyPrefix + key;
        String script = 
            "if redis.call('get', KEYS[1]) == ARGV[1] then " +
            "   return redis.call('del', KEYS[1]) " +
            "else " +
            "   return 0 " +
            "end";

        Long result = redisTemplate.execute(
            new DefaultRedisScript<>(script, Long.class),
            Collections.singletonList(fullKey),
            value
        );
        return result != null && result == 1L;
    }

    // 锁续期(WatchDog机制)
    @Component
    public static class LockRenewalWatchDog {
        private final Map<String, ScheduledFuture<?>> renewalTasks = new ConcurrentHashMap<>();
        private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(10);

        public void startRenewal(String key, String value, long expireMs) {
            ScheduledFuture<?> task = scheduler.scheduleAtFixedRate(() -> {
                String script = 
                    "if redis.call('get', KEYS[1]) == ARGV[1] then " +
                    "   return redis.call('expire', KEYS[1], ARGV[2]) " +
                    "else " +
                    "   return 0 " +
                    "end";

                Long result = redisTemplate.execute(
                    new DefaultRedisScript<>(script, Long.class),
                    Collections.singletonList(lockKeyPrefix + key),
                    value,
                    String.valueOf(expireMs / 1000)
                );

                if (result == 0) {
                    // 锁已被释放,取消续期
                    cancelRenewal(key);
                }
            }, expireMs / 3, expireMs / 3, TimeUnit.MILLISECONDS);  // 每 expireMs/3 续期一次

            renewalTasks.put(key, task);
        }

        public void cancelRenewal(String key) {
            ScheduledFuture<?> task = renewalTasks.remove(key);
            if (task != null) {
                task.cancel(false);
            }
        }
    }
}

// RedLock(多Redis节点)
public class RedLock {

    private final List<RedisDistributedLock> redisLocks;
    private final int quorum;  // 多数派节点数

    public RedLock(List<RedisTemplate> redisTemplates) {
        this.redisLocks = redisTemplates.stream()
            .map(template -> new RedisDistributedLock(template))
            .collect(Collectors.toList());
        this.quorum = redisLocks.size() / 2 + 1;
    }

    public boolean tryLock(String key, String value, long expireMs) {
        int successCount = 0;
        long startTime = System.currentTimeMillis();

        // 向所有Redis节点请求锁
        for (RedisDistributedLock lock : redisLocks) {
            if (lock.tryLock(key, value, expireMs)) {
                successCount++;
            }
        }

        long elapsed = System.currentTimeMillis() - startTime;

        // 成功获取多数派锁,且耗时小于过期时间
        if (successCount >= quorum && elapsed < expireMs) {
            return true;
        }

        // 获取失败,释放已获取的锁
        for (RedisDistributedLock lock : redisLocks) {
            lock.unlock(key, value);
        }
        return false;
    }
}

5.2 ZooKeeper分布式锁

public class ZooKeeperDistributedLock implements AutoCloseable {

    private final CuratorFramework client;
    private final String lockPath;
    private final String lockPrefix = "/locks/";
    private String currentLockNode;

    public ZooKeeperDistributedLock(String connectString, String lockName) {
        this.client = CuratorFrameworkFactory.newClient(connectString, new ExponentialBackoffRetry(1000, 3));
        this.client.start();
        this.lockPath = lockPrefix + lockName;

        try {
            // 创建持久节点
            Stat stat = client.checkExists().forPath(lockPath);
            if (stat == null) {
                client.create().creatingParentsIfNeeded().forPath(lockPath);
            }
        } catch (Exception e) {
            throw new RuntimeException("初始化锁失败", e);
        }
    }

    // 获取锁(顺序临时节点 + 监听前一个节点)
    public void lock() {
        try {
            // 创建顺序临时节点
            currentLockNode = client.create()
                .creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                .forPath(lockPath + "/lock_");

            // 获取所有子节点
            List<String> children = client.getChildren().forPath(lockPath);
            Collections.sort(children);

            String currentNodeName = currentLockNode.substring(currentLockNode.lastIndexOf('/') + 1);
            int currentNodeIndex = children.indexOf(currentNodeName);

            if (currentNodeIndex == 0) {
                // 第一个节点,获得锁
                return;
            }

            // 监听前一个节点
            String previousNode = lockPath + "/" + children.get(currentNodeIndex - 1);
            CountDownLatch latch = new CountDownLatch(1);

            NodeCache nodeCache = new NodeCache(client, previousNode);
            nodeCache.start();
            nodeCache.getListenable().addListener(() -> {
                latch.countDown();
            });

            // 等待前一个节点释放
            latch.await();
            nodeCache.close();

        } catch (Exception e) {
            throw new RuntimeException("获取锁失败", e);
        }
    }

    // 尝试获取锁(非阻塞)
    public boolean tryLock(long timeout, TimeUnit unit) {
        try {
            // 创建顺序临时节点
            currentLockNode = client.create()
                .creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                .forPath(lockPath + "/lock_");

            List<String> children = client.getChildren().forPath(lockPath);
            Collections.sort(children);

            String currentNodeName = currentLockNode.substring(currentLockNode.lastIndexOf('/') + 1);
            int currentNodeIndex = children.indexOf(currentNodeName);

            if (currentNodeIndex == 0) {
                return true;
            }

            // 不是第一个节点,等待一段时间
            String previousNode = lockPath + "/" + children.get(currentNodeIndex - 1);
            CountDownLatch latch = new CountDownLatch(1);

            NodeCache nodeCache = new NodeCache(client, previousNode);
            nodeCache.start();
            nodeCache.getListenable().addListener(() -> latch.countDown());

            boolean acquired = latch.await(timeout, unit);
            nodeCache.close();

            if (!acquired) {
                // 超时未获得锁,删除自己创建的节点
                client.delete().forPath(currentLockNode);
                return false;
            }
            return true;

        } catch (Exception e) {
            return false;
        }
    }

    // 释放锁
    public void unlock() {
        if (currentLockNode != null) {
            try {
                client.delete().forPath(currentLockNode);
                currentLockNode = null;
            } catch (Exception e) {
                log.error("释放锁失败", e);
            }
        }
    }

    @Override
    public void close() {
        unlock();
        client.close();
    }
}

六、消息中间件

6.1 消息队列的核心问题
消息丢失与可靠性保证

// 生产端保证(同步发送 + 回调确认)
@Component
public class ReliableMessageProducer {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    // 同步发送(确保Broker收到)
    public SendResult syncSend(String topic, Object message) {
        SendResult result = rocketMQTemplate.syncSend(topic, message, 3000);
        if (result.getSendStatus() != SendStatus.SEND_OK) {
            // 记录失败消息,异步重试
            saveToRetryQueue(topic, message);
            throw new RuntimeException("消息发送失败: " + result.getSendStatus());
        }
        return result;
    }

    // 异步发送 + 回调
    public void asyncSend(String topic, Object message, MessageCallback callback) {
        rocketMQTemplate.asyncSend(topic, message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                callback.onSuccess(sendResult);
            }

            @Override
            public void onException(Throwable e) {
                log.error("消息发送失败", e);
                // 记录失败消息,重试
                retryMessage(topic, message);
                callback.onFailure(e);
            }
        });
    }
}

// Broker端保证(同步刷盘 + 主从同步)
// 配置:
// flushDiskType=SYNC_FLUSH(同步刷盘)
// brokerRole=SYNC_MASTER(同步双写)

// 消费端保证(手动确认)
@RocketMQMessageListener(topic = "order_topic", consumerGroup = "order_group", 
                         messageModel = MessageModel.CLUSTERING,
                         consumeMode = ConsumeMode.CONCURRENTLY)
public class OrderConsumer implements RocketMQListener<OrderMessage> {

    @Override
    public void onMessage(OrderMessage message) {
        try {
            // 处理业务逻辑
            processOrder(message);

            // 处理成功,返回CONSUME_SUCCESS(自动确认)
        } catch (Exception e) {
            log.error("消费失败", e);
            // 返回RECONSUME_LATER(稍后重试)
            throw new RuntimeException("消费失败,稍后重试");
        }
    }
}

消息幂等性处理

@Component
public class IdempotentConsumer {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String PROCESSED_FLAG_PREFIX = "msg:processed:";
    private static final long EXPIRE_SECONDS = 86400;  // 24小时

    // 基于Redis的幂等性判断
    public boolean isProcessed(String messageId) {
        String key = PROCESSED_FLAG_PREFIX + messageId;
        Boolean success = redisTemplate.opsForValue()
            .setIfAbsent(key, "1", Duration.ofSeconds(EXPIRE_SECONDS));
        return Boolean.FALSE.equals(success);
    }

    // 基于数据库唯一索引
    @Transactional
    public void consumeWithDbIdempotent(MessageRecord message) {
        try {
            // 插入消息消费记录(唯一索引:message_id)
            messageRecordMapper.insert(message);

            // 执行实际业务逻辑
            processBusiness(message);

        } catch (DuplicateKeyException e) {
            // 重复消息,跳过
            log.info("重复消息,messageId={}", message.getMessageId());
        }
    }

    // 基于业务键的幂等性(如订单号、交易流水号)
    public void consumeWithBusinessIdempotent(OrderMessage message) {
        String businessKey = "order:" + message.getOrderId();
        Boolean locked = redisTemplate.opsForValue()
            .setIfAbsent(businessKey, "processing", Duration.ofSeconds(30));

        if (Boolean.FALSE.equals(locked)) {
            log.info("订单正在处理中或已处理完成: {}", message.getOrderId());
            return;
        }

        try {
            // 检查是否已处理
            Order order = orderMapper.selectById(message.getOrderId());
            if (order != null && "PROCESSED".equals(order.getStatus())) {
                return;
            }

            // 处理业务
            processOrder(message);

        } finally {
            redisTemplate.delete(businessKey);
        }
    }
}

6.2 消息顺序保证

// RocketMQ顺序消息(消息队列选择器)
public class OrderlyMessageProducer {

    public void sendOrderlyMessage(String topic, OrderMessage message, String orderId) {
        // 使用orderId作为选择Key,相同orderId的消息进入同一个队列
        rocketMQTemplate.syncSendOrderly(topic, message, orderId);
    }
}

// 消费端(顺序消费)
@RocketMQMessageListener(topic = "order_topic", consumerGroup = "order_group",
                         consumeMode = ConsumeMode.ORDERLY)  // 顺序消费模式
public class OrderlyConsumer implements RocketMQListener<OrderMessage> {

    @Override
    public void onMessage(OrderMessage message) {
        // 顺序消费,无需考虑并发问题
        processOrder(message);
    }
}

来源:
http://uklgy.cn/

相关文章
|
6月前
|
消息中间件 存储 缓存
程序员进阶工程师必备技能之中间件深度使用与运维(一)
教程来源 https://zlpow.cn/ 中间件是分布式系统的“神经系统”,位于操作系统与应用之间,屏蔽底层异构性,提供消息队列、缓存、分库分表、服务治理等标准化能力。它是高并发、高可用架构的核心基石。
程序员进阶工程师必备技能之中间件深度使用与运维(一)
|
6月前
|
消息中间件 负载均衡 算法
程序员必备的十大技能(进阶版)之分布式核心技术(一)
教程来源 http://unbgv.cn/ 本文系统剖析分布式核心技术,涵盖CAP/BASE理论、服务治理、一致性协议、分布式事务、锁、消息中间件、负载均衡、存储及可观测性九大维度,直击微服务演进中的核心挑战与落地实践。
|
6月前
|
消息中间件 弹性计算 Cloud Native
从单机崩溃到全球代购:我用云原生重构了跨境物流系统
代购转运系统曾因订单队列卡死、DB连接爆满饱受大促之苦。去年以“解耦、异步、弹性、可观测”八字方针重构:拆为7个独立服务,订单创建后异步发MQ,按CPU/QPS自动扩缩容,修复连接池泄漏、优化分布式事务(本地消息表+补偿),日志分级治理。平稳扛过多次大促。
303 1
|
6月前
|
存储 缓存 Java
Java在配置中心(Apollo/Nacos)设计中的核心贡献
微服务架构下,配置文件分散在各处,修改一个配置需要重启服务,效率低下且易出错。配置中心实现了配置的统一管理、动态刷新、版本控制、灰度发布。
428 2
|
6月前
|
数据可视化 JavaScript Java
Maven dependency:tree 的 8 个高级用法
本文深入讲解 Maven dependency:tree 命令的 8 个高级用法,涵盖依赖冲突排查、传递依赖分析、版本升级建议等实战场景。通过企业级真实案例,展示如何利用这个强大工具快速定位和解决复杂的依赖问题。提供可视化分析方法、自动化脚本工具和企业级依赖管理规范,让你掌握专业级的依赖分析技能。
Maven dependency:tree 的 8 个高级用法
|
7月前
|
程序员 Shell 持续交付
初级程序员必备的十大技能之开发工具熟练使用(二)
教程来源 https://zlpow.cn/ 命令行是程序员高效开发的“第二语言”:涵盖文件操作、进程管理、网络诊断、管道重定向、Shell脚本及终端增强工具,助你快速定位问题、批量处理任务、自动化部署,全面提升系统操控力与生产力。
|
6月前
|
消息中间件 存储 监控
Java在JavaAgent与字节码增强技术中的应用(APM基石)
JavaAgent是一种特殊的JAR包,可以在JVM启动时(-javaagent)或运行时(AttachAPI)修改字节码。它利用Instrumentation接口,通过ClassFileTransformer在类加载前或重定义时替换字节码。
531 0
|
6月前
|
存储 缓存 负载均衡
程序员必备的十大技能(进阶版)之分布式核心技术(五)
教程来源 http://yvyus.cn/ 本节系统讲解分布式核心能力:涵盖加权随机、最少活跃连接等负载均衡算法;Failover、Forking等容错策略;多级缓存与一致性保障;虚拟桶分片与平滑迁移;OpenTelemetry链路追踪及全链路日志透传,助力构建高可用、可观测的分布式系统。
|
6月前
|
消息中间件 程序员 RocketMQ
程序员必备的十大技能(进阶版)之分布式核心技术(三)
教程来源 http://vbzcj.cn/ 分布式事务三大主流方案:2PC(强一致、同步阻塞)、TCC(业务侵入、高灵活)、RocketMQ事务消息(最终一致、异步解耦),分别适用于金融核心、高并发微服务及积分订单等场景。
|
6月前
|
SQL 缓存 监控
程序员必备的十大技能(进阶版)之高性能数据库实战(五)
教程来源 http://qcycj.cn/ 本节涵盖数据库监控诊断(慢日志配置、实时SQL与表状态分析)、NoSQL/NewSQL选型策略(缓存穿透/击穿/雪崩应对、分库分表与TiDB对比),以及千万级订单系统的实战优化路径,强调“硬件→架构→业务”逐层治理理念。

热门文章

最新文章