自己写了个简单的redis分布式锁【我】

自己写了个简单的redis分布式锁

package redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class RedisLock2 {

    JedisPool jedisPool = new JedisPool("127.0.0.1", 6379);
    private String key;
    private String value;
    private Long timeout = 5L;
    private Long startTime;
    
    public RedisLock2(JedisPool jedis,String key) {
        super();
        this.jedisPool = jedisPool;
        this.key = key;
        value = System.currentTimeMillis()+"";
    }
    
    public RedisLock2(JedisPool jedis,String key,Long timeout) {
        super();
        this.jedisPool = jedis;
        this.key = key;
        this.timeout = timeout;
        value = System.currentTimeMillis()+"";
    }

    public boolean lock() {
        Jedis jedis = jedisPool.getResource();
        boolean ok = jedis.set(key,value, "nx", "ex", timeout)!=null;
        jedis.close();
        if (!ok) {
            //加锁失败
            return false;
        }
        //加锁成功
        startTime = System.currentTimeMillis();
        return true;
    }
    
    public String unlock() {
        String msg = "";
        long timeConsume = System.currentTimeMillis()-startTime;
        if (timeConsume>timeout*1000) {
            System.out.println("出现超时解锁-----------key:"+key+",耗时毫秒:"+timeConsume);
//            return false;
            msg = "出现超时解锁--key:"+key+",耗时毫秒:"+timeConsume;
            return msg;
        }
        //这里是为了避免超时后,释放掉其他线程的同名锁
        //但是有个问题,就是下面的代码不是原子操作,可能会有并发问题,这里忽略
        Jedis jedis = jedisPool.getResource();
        String s = jedis.get(key);
        if (value.equals(s)) {
            //释放锁
            jedis.del(key);
            jedis.close();
//            return true;
            msg = "解锁成功";
            return msg;
        }
        jedis.close();
        System.out.println("出现其他异常解锁失败---------key:"+key);
//        return false;
        msg = "出现其他异常解锁失败--key:"+key;
        return msg;
    }
    
    
    public static void main1(String[] args) throws InterruptedException {
        JedisPool jedisPool = new JedisPool("127.0.0.1", 6379);
        // 从连接池中获取一个jedis对象
        RedisLock2 redisLock = new RedisLock2(jedisPool,"lock1",1L);
        boolean lock = redisLock.lock();
        if(lock) {
            System.out.println("获取到锁了");
            Thread.sleep(2000);
        }
        System.out.println(redisLock.unlock());
    }
    
    
    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool("127.0.0.1", 6379);
        Jedis jedis2 = jedisPool.getResource();
        
//        DistributedLock lock = new DistributedLock(jedisPool);
        
        for (int i = 0; i < 3; i++) {
//            final int k = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int j = 0; j < 10; j++) {
                        int k = j;
                        // 连接本地的 Redis 服务
//                        Jedis jedis = new Jedis("localhost");
                        // 创建连接池对象
                        String code = null;
                        try {
                            //加分布式锁
//                            code = lock.lock("mylock");
                            RedisLock2 myLock = new RedisLock2(jedisPool,"lock1",10L);
                            while (true) {
                                //不断获取锁
                                boolean lock = myLock.lock();
                                if (lock) {
                                    //如果获取到则执行
                                    // 从连接池中获取一个jedis对象
                                    Jedis jedis = jedisPool.getResource();
                                    if (!jedis.exists("a" + k)) {
                                        jedis.set("a" + k, Thread.currentThread().getName());
                                        jedis.expire("a" + k, 60);
                                        System.out.println(System.currentTimeMillis() + "--" + Thread.currentThread().getName()
                                                + "--key:" + ("a" + k) + "不存在,设置值为: " + Thread.currentThread().getName());
                                        try {
                                            // Thread.sleep((long) (Math.random()*1000));
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    } else {
                                        System.out.println(Thread.currentThread().getName() + "--key:" + ("a" + k) + "存在,值为: "
                                                + jedis.get("a" + k));
                                    }
                                    jedis.close();
                                    //执行完解锁
                                    myLock.unlock();
                                    break;//跳出循环
                                }
                                
                            }
                            
                        } finally {
                            //释放分布式锁
//                            lock.unLock("mylock",code);
                        }
                    }
                }
            }).start();
        }
    }
    
    
}

猜你喜欢

转载自www.cnblogs.com/libin6505/p/11284401.html
今日推荐