基于Redis实现——分布式锁与实现

实现

使用的是jedis来连接Redis。

实现思想

  • 获取锁的时候,使用setnx加锁,并使用expire命令为锁添加一个超时时间,超过该时间则自动释放锁,锁的value值为一个随机生成的UUID,通过此在释放锁的时候进行判断。
  • 获取锁的时候还设置一个获取的超时时间,若超过这个时间则放弃获取锁。
  • 释放锁的时候,通过UUID判断是不是该锁,若是该锁,则执行delete进行锁释放

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

import redis.clients.jedis.Jedis;

import redis.clients.jedis.JedisPool;

import redis.clients.jedis.Transaction;

import redis.clients.jedis.exceptions.JedisException;

import java.util.List;

import java.util.UUID;

/**

 * Created by liuyang on 2017/4/20.

 */

public class DistributedLock {

    private final JedisPool jedisPool;

    public DistributedLock(JedisPool jedisPool) {

        this.jedisPool = jedisPool;

    }

    /**

     * 加锁

     * @param locaName  锁的key

     * @param acquireTimeout  获取超时时间

     * @param timeout   锁的超时时间

     * @return 锁标识

     */

    public String lockWithTimeout(String locaName,

                                  long acquireTimeout, long timeout) {

        Jedis conn = null;

        String retIdentifier = null;

        try {

            // 获取连接

            conn = jedisPool.getResource();

            // 随机生成一个value

            String identifier = UUID.randomUUID().toString();

            // 锁名,即key值

            String lockKey = "lock:" + locaName;

            // 超时时间,上锁后超过此时间则自动释放锁

            int lockExpire = (int)(timeout / 1000);

            // 获取锁的超时时间,超过这个时间则放弃获取锁

            long end = System.currentTimeMillis() + acquireTimeout;

            while (System.currentTimeMillis() < end) {

                if (conn.setnx(lockKey, identifier) == 1) {

                    conn.expire(lockKey, lockExpire);

                    // 返回value值,用于释放锁时间确认

                    retIdentifier = identifier;

                    return retIdentifier;

                }

                // 返回-1代表key没有设置超时时间,为key设置一个超时时间

                if (conn.ttl(lockKey) == -1) {

                    conn.expire(lockKey, lockExpire);

                }

                try {

                    Thread.sleep(10);

                catch (InterruptedException e) {

                    Thread.currentThread().interrupt();

                }

            }

        catch (JedisException e) {

            e.printStackTrace();

        finally {

            if (conn != null) {

                conn.close();

            }

        }

        return retIdentifier;

    }

    /**

     * 释放锁

     * @param lockName 锁的key

     * @param identifier    释放锁的标识

     * @return

     */

    public boolean releaseLock(String lockName, String identifier) {

        Jedis conn = null;

        String lockKey = "lock:" + lockName;

        boolean retFlag = false;

        try {

            conn = jedisPool.getResource();

            while (true) {

                // 监视lock,准备开始事务

                conn.watch(lockKey);

                // 通过前面返回的value值判断是不是该锁,若是该锁,则删除,释放锁

                if (identifier.equals(conn.get(lockKey))) {

                    Transaction transaction = conn.multi();

                    transaction.del(lockKey);

                    List<Object> results = transaction.exec();

                    if (results == null) {

                        continue;

                    }

                    retFlag = true;

                }

                conn.unwatch();

                break;

            }

        catch (JedisException e) {

            e.printStackTrace();

        finally {

            if (conn != null) {

                conn.close();

            }

        }

        return retFlag;

    }

}

  

测试

下面就用一个简单的例子测试刚才实现的分布式锁。
例子中使用50个线程模拟秒杀一个商品,使用--运算符来实现商品减少,从结果有序性就可以看出是否为加锁状态。

模拟秒杀服务,在其中配置了jedis线程池,在初始化的时候传给分布式锁,供其使用。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

import redis.clients.jedis.JedisPool;

import redis.clients.jedis.JedisPoolConfig;

/**

 * Created by liuyang on 2017/4/20.

 */

public class Service {

    private static JedisPool pool = null;

    static {

        JedisPoolConfig config = new JedisPoolConfig();

        // 设置最大连接数

        config.setMaxTotal(200);

        // 设置最大空闲数

        config.setMaxIdle(8);

        // 设置最大等待时间

        config.setMaxWaitMillis(1000 * 100);

        // 在borrow一个jedis实例时,是否需要验证,若为true,则所有jedis实例均是可用的

        config.setTestOnBorrow(true);

        pool = new JedisPool(config, "127.0.0.1", 6379, 3000);

    }

    DistributedLock lock new DistributedLock(pool);

    int n = 500;

    public void seckill() {

        // 返回锁的value值,供释放锁时候进行判断

        String indentifier = lock.lockWithTimeout("resource", 5000, 1000);

        System.out.println(Thread.currentThread().getName() + "获得了锁");

        System.out.println(--n);

        lock.releaseLock("resource", indentifier);

    }

}

  // 模拟线程进行秒杀服务

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

public class ThreadA extends Thread {

    private Service service;

    public ThreadA(Service service) {

        this.service = service;

    }

    @Override

    public void run() {

        service.seckill();

    }

}

public class Test {

    public static void main(String[] args) {

        Service service = new Service();

        for (int i = 0; i < 50; i++) {

            ThreadA threadA = new ThreadA(service);

            threadA.start();

        }

    }

}

  

在分布式环境中,对资源进行上锁有时候是很重要的,比如抢购某一资源,这时候使用分布式锁就可以很好地控制资源。
当然,在具体使用中,还需要考虑很多因素,比如超时时间的选取,获取锁时间的选取对并发量都有很大的影响,上述实现的分布式锁也只是一种简单的实现,主要是一种思想。

下一次我会使用zookeeper实现分布式锁,使用zookeeper的可靠性是要大于使用redis实现的分布式锁的,但是相比而言,redis的性能更好。

http://www.cnblogs.com/liuyang0/p/6744076.html

猜你喜欢

转载自blog.csdn.net/liao1990/article/details/81177115