zoukankan      html  css  js  c++  java
  • 分布式锁-基于redis的分布式锁实现

    在微服务中缓存重建的时候一般会考虑使用分布式锁来避免缓存重建工作在不同的服务中重复执行

    以下是使用Spring Cloud工程,基于Redis实现的分布式锁, 使用时需要引入 spring-boot-data-redis 依赖

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.stereotype.Component;
    
    import java.util.concurrent.TimeUnit;
    
    @Component
    public class RedisLockSample {
    
        @Autowired
        private RedisTemplate redisTemplate;
    
        public synchronized String reconstructionCache() {
            boolean findValue = false;
            try{
                for (int i = 0; i < 3; i++) {
                    // 使用nx特性获取锁
                    boolean lock = redisTemplate.boundValueOps("lock").setIfAbsent("test");
                    if (lock) {
                        // 多重检查避免无效更新
                        if (redisTemplate.hasKey("data:cache")) {
                            findValue = true;
                            break;
                        }
    
                        redisTemplate.opsForValue().set("data:cache", "业务数据部分");
                        findValue = true;
                        break;
                    }
                    // 无法获取到锁 进入等待
                    try {
                        TimeUnit.MILLISECONDS.sleep(200L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // 检查值是否被其他服务设置,如果被设置了则提前退出锁获取流程
                    if (redisTemplate.hasKey("data:cache")) { 
                        findValue = true;
                        break;
                    }
                }
                return findValue ? (String) redisTemplate.opsForValue().get("data:cache") : null;
            }finally {
                // 释放锁
                redisTemplate.delete("lock");
            }
        }
    
    }
  • 相关阅读:
    python数据采集与多线程效率分析
    Memcache使用基础
    《大规模 web服务开发》笔记
    画了一张PHPCMSV9的运行流程思维导图
    MySQL的正则表达式
    linux patch 格式与说明(收录)
    Memcached笔记之分布式算法
    bzoj 2120 带修改莫队
    bzoj 2073 暴力
    bzoj 1814 Ural 1519 Formula 1 插头DP
  • 原文地址:https://www.cnblogs.com/banywl/p/15376694.html
Copyright © 2011-2022 走看看