分布式锁

方案一:
redis
方案二:
zk

方案一:redis

public class RedisTool {
    private static final String LOCK_SUCCESS = "OK";
    private static final String SET_IF_NOT_EXIST = "NX";
    private static final String SET_WITH_EXPIRE_TIME = "PX";
    private static final Long RELEASE_SUCCESS = 1L;
    private static int ticketCount = 450;
    public static JedisPool pool;
    static String lockKey = getRequestId();

    static {
        if (pool == null) {
            JedisPoolConfig config = new JedisPoolConfig();
            //控制一个pool可分配多少个jedis实例,通过pool.getResource()来获取;
            //如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
            config.setMaxTotal(1000);
            config.setMaxWaitMillis(1000);
            //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。
            config.setMaxIdle(50);
            //表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;单位毫秒
            //小于零:阻塞不确定的时间,  默认-1
            config.setMaxWaitMillis(1000 * 100);
            //在borrow(引入)一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
            config.setTestOnBorrow(true);
            //return 一个jedis实例给pool时,是否检查连接可用性(ping())
            config.setTestOnReturn(true);
            //connectionTimeout 连接超时(默认2000ms)
            //soTimeout 响应超时(默认2000ms)
            pool = new JedisPool(config, "127.0.0.1", 6379, 2000);
        }
    }

    public static Jedis getJedis() {
        return pool.getResource();
    }

    public static String getRequestId() {
        String uuid = UUID.randomUUID().toString().replace("-", "");

        return uuid;
    }

    @Test
    public void test() throws InterruptedException {
        long start = System.currentTimeMillis();
        final CountDownLatch countDownLatch = new CountDownLatch(500);
        Executor executor = Executors.newFixedThreadPool(50);
        for (int i = 0; i < 500; i++) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        distributeLock();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        long costTime = System.currentTimeMillis() - start;
        pool.close();
        System.out.println("it totally took:" + costTime + " ms");
    }

    public void distributeLock() throws InterruptedException {
        Jedis jedis = null;
        String requestId = null;
        int timeoutCount = 0;
        requestId = getRequestId();
        while (true) {
            try {
                jedis = getJedis();
                break;
            } catch (Exception e) {
                if (e instanceof JedisConnectionException || e instanceof SocketTimeoutException) {
                    //记录下获取多少次才获得jedis连接,并发很多的时候可能池里的连接不够而导致获取连接失败,所以这里循环获取
                    timeoutCount++;
                    //System.out.println("user:"+requestId+" getJedis timeoutCount={"+timeoutCount+"}");
                }
            }
        }

        if (tryGetDistributedLock(jedis, lockKey, requestId, 3000)) {
            if (ticketCount > 0) {
                System.out.println(requestId + " have got a ticket:" + ticketCount);
                ticketCount--;
            } else {
                System.out.println(requestId + "the ticket have been sold out.");
            }
            System.out.println(requestId+"释放了锁");
            releaseDistributedLock(jedis, lockKey, requestId);
            jedis.close();
        } else {
            System.out.println("user" + requestId + " have been sold out!Give up getting lock");
        }

    }

    /**
     * 尝试获取分布式锁
     *
     * @param jedis      Redis客户端
     * @param lockKey    锁
     * @param requestId  请求标识
     * @param expireTime 超期时间
     * @return 是否获取成功
     */
    public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) throws InterruptedException {

        int timeoutCount = 0;
        long currentTime = System.currentTimeMillis();
        while (true) {

            try {
                String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
                if (LOCK_SUCCESS.equals(result)) {
                    return true;
                }
                if (ticketCount <= 0) {
                    System.out.println("user" + requestId + " have been sold out!Give up getting lock");
                    return false;
                }
                /*//等待了60S以上,直接不再获取锁
                if(System.currentTimeMillis() > (currentTime+ 60*1000)){
                    System.out.println("user"+ requestId +"等待了60S以上了,放弃!!!");
                    return false;
                }*/
            } catch (Exception e) {
                /*if (e instanceof JedisConnectionException || e instanceof SocketTimeoutException) {
                    timeoutCount++;
                    //System.out.println("user:"+requestId+" jedis.set() timeoutCount={"+timeoutCount+"}");
                    if (timeoutCount > 3)
                    {
                        System.out.println("connect error!");
                        break;
                    }
                }*/
            }
        }
    }

    /**
     * 释放分布式锁
     *
     * @param jedis     Redis客户端
     * @param lockKey   锁
     * @param requestId 请求标识
     * @return 是否释放成功
     */
    public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) {

        //判断requestId相等时为了确定解锁和获取锁的用户是同一个用户
        //lockKey是针对此业务的锁ID 执行成功返回1.
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));

        if (RELEASE_SUCCESS.equals(result)) {

            return true;
        }
        return false;

    }
}

方案二:zk

public class LockByCurator {

    private static Integer a = 0;

    private static String CONNECT_SERVER = "127.0.0.1";
    private static int SESSION_TIMEOUT = 3000;
    private static int CONNECTION_TIMEOUT = 3000;

    private static final String CURATOR_LOCK = "/currentLock";

    private static void doLock(CuratorFramework cf) {
        System.out.println(Thread.currentThread().getName() + "尝试获取锁");

        InterProcessMutex mutex = new InterProcessMutex(cf, CURATOR_LOCK);

        try {
            if (mutex.acquire(5, TimeUnit.SECONDS)) {
                System.out.println(Thread.currentThread().getName() + "获得到了锁");
                a++;
                System.out.println("=====================>"+a);
                /*操作业务*/
                Thread.sleep(5000);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                /*释放*/
                System.out.println(Thread.currentThread().getName() + "释放了锁");
                mutex.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        /*定义信号灯。只能允许10个线程并发操作*/
        final Semaphore semaphore = new Semaphore(11);
        for (int i = 1; i <= 20; i++) {
            Runnable runnable =new Runnable() {
                @Override
                public void run() {

                        try {
                            semaphore.acquire();
                            /*链接zk*/
                            CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(CONNECT_SERVER, SESSION_TIMEOUT, CONNECTION_TIMEOUT, new RetryNTimes(10, 5000));
                            curatorFramework.start();
                            doLock(curatorFramework);
                            semaphore.release();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                }
            };
            executorService.execute(runnable);
        }
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,233评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,013评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,030评论 0 241
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,827评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,221评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,542评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,814评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,513评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,225评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,497评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,998评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,342评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,986评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,812评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,560评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,461评论 2 266

推荐阅读更多精彩内容

  • 分布式锁定义 分布式锁在分布式环境下,锁定全局唯一公共资源,表现为: 请求串行化 互斥性 第一步是上锁的资源目标,...
    ___n阅读 1,673评论 0 0
  • 一、概念 在单机环境中,Java提供了很多API来解决并发问题,如java.util.concurrent包下(简...
    秋慕云阅读 609评论 0 2
  • Redis实现分布式锁 一、Redis单节点实现 (一) 获取锁 使用 Redis 客户端获取锁,向Redis发出...
    heyong阅读 1,711评论 0 1
  • 瘦尽芳菲露已寒,夜凉独倚小阑干。 杏花未落离人去,鸿雁归时只影单。 频寄锦书催返棹,更愁杂事阻雕鞍。 中秋一近相思...
    田梦_阅读 543评论 28 20
  • 这是入职拓普一周内画的思维导图,记得当时画这幅自我介绍的时候很认真 这是今天用思维导图绘制得自我介绍 通过两幅思维...
    会飞的画家阅读 1,080评论 2 3