本文爲博主原創文章,轉載請附帶博客地址:https://www.cnblogs.com/xbjhs/p/11041221.htmlhtml
這個分佈式鎖知足:java
1.redis線程池
package com.test; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import java.util.Arrays; import java.util.UUID; /** * Description:redis鎖實現類 <br/> * * @author: * @date 2019-06-17 11:43 * @Param: * @Return: */ public class TestPool { public static void main(String[] args) { Jedis jedis = null; try { RedisLock redisLock = new RedisLock("123421342134"); //獲取鎖 jedis = redisLock.getRedisLock(); //釋放鎖 redisLock.unlock(jedis); } catch (Exception e) { System.out.println("獲取redis鎖失敗"); } finally { if (null != jedis) { JedisPoolUtil.release(jedis); } } } }
2.獲取redis鎖,解鎖的測試類
package com.test; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import java.util.Arrays; import java.util.UUID; /** * Description:redis鎖實現類 <br/> * * @author: * @date 2019-06-17 11:43 * @Param: * @Return: */ public class TestPool { public static void main(String[] args) { Jedis jedis = null; try { RedisLock redisLock = new RedisLock("123421342134"); //獲取鎖 jedis = redisLock.getRedisLock(); //釋放鎖 redisLock.unlock(jedis); } catch (Exception e) { System.out.println("獲取redis鎖失敗"); } finally { if (null != jedis) { JedisPoolUtil.release(jedis); } } } }
package com.test; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import java.util.Arrays; import java.util.UUID; /** * Description:redis鎖 <br/> * * @author: * @date 2019-06-17 17:07 * @Param: * @Return: */ public class RedisLock { public static final String SET_SUCCESS = "OK"; private String key; private String val; public RedisLock(String key) { this.key = key; this.val = UUID.randomUUID().toString(); } public Jedis getRedisLock() { JedisPool jedisPool = JedisPoolUtil.getJedisPoolInstance(); JedisPool jedisPool2 = JedisPoolUtil.getJedisPoolInstance(); System.out.println(jedisPool == jedisPool2); Jedis jedis = null; jedis = jedisPool.getResource(); /** *第三個參數是NX,意思是SET IF NOT EXIST,即當key不存在時,進行set操做;若key已經存在,則不作任何操做; *第四個參數是PX,意思是咱們要給這個key加一個過時的設置,具體時間由第五個參數決定。 *第五個爲time,與第四個參數相呼應,表明key的過時時間。設置時間較大,方便截圖 */ String response = jedis.set(key, val, "NX", "PX", 20000); if (!SET_SUCCESS.equals(response)) { //拋出自定義異常 } return jedis; } public void unlock(Jedis jedis) { jedis.eval("if redis.call('get',KEYS[1]) == ARGV[1] then \n return redis.call('del',KEYS[1]) \n else return 0 \n end", Arrays.asList(key), Arrays.asList(val)); System.out.println("釋放鎖成功"); } }
3.pom依賴
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.2</version>
</dependency>
4.截圖
redis