使用Redis的 SETNX 命令可以实现分布式锁

SETNX key value

返回值

返回整数,具体为 
- 1,当 key 的值被设置 
- 0,当 key 的值没被设置

分布式锁使用

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig; /**
* @Author: feng
* @Date: 2019/5/25 21:54
* @Description:
*/
public class RedisManager { private static JedisPool jedisPool; static {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(18);
jedisPoolConfig.setMaxIdle(5);
jedisPool = new JedisPool(jedisPoolConfig,"127.0.0.1",6379,5000);
} public static Jedis getJedis() throws Exception {
if (null != jedisPool){
return jedisPool.getResource();
}
throw new Exception("Jedispool was not init");
}
}

  

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction; import java.util.List; /**
* @Author: feng
* @Date: 2019/5/25 22:04
* @Description:
*/
public class RedisLock { public String getLock(String key, int timeout) {
Jedis jedis = null;
try {
jedis = RedisManager.getJedis();
// String value = UUID.randomUUID().toString();
//以当前线程id作为value
String value = String.valueOf(Thread.currentThread().getId());
long end = System.currentTimeMillis() + timeout;
while (System.currentTimeMillis() < end) {
if (jedis.setnx(key, value) == 1) {
jedis.expire(key, timeout);
return value;
}
if (jedis.ttl(key) == -1) {
jedis.expire(key, timeout);
}
Thread.sleep(500);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
jedis.close();
}
return null;
} public boolean releaseLock(String key, String value) {
Jedis jedis = null;
try {
jedis = RedisManager.getJedis();
while (true) {
jedis.watch(key);
System.out.println(jedis.get(key));
if (value.equals(jedis.get(key))) {
Transaction transaction = jedis.multi();
transaction.del(key);
List<Object> list = transaction.exec();
if (list == null) {
continue;
}
}
jedis.unwatch();
return true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
jedis.close();
}
return false;
} public static void main(String[] args) {
RedisLock redisLock = new RedisLock();
String thredId = redisLock.getLock("test", 1000);
System.out.println("返回值value:" + thredId);
boolean b = redisLock.releaseLock("test", String.valueOf(Thread.currentThread().getId()));
System.out.println(b);
} }

  

redis 加锁与释放锁(分布式锁1)的更多相关文章

  1. 基于redis集群实现的分布式锁,可用于秒杀,定时器。

    在分布式系统中,经常会出现需要竞争同一资源的情况,使用redis可以实现分布式锁. 前提:redis集群已经整合项目,并且可以直接注入JedisCluster使用: @Autowired privat ...

  2. 基于redis集群实现的分布式锁,可用于秒杀商品的库存数量管理,有測试代码(何志雄)

    转载请标明出处. 在分布式系统中,常常会出现须要竞争同一资源的情况,本代码基于redis3.0.1+jedis2.7.1实现了分布式锁. redis集群的搭建,请见我的另外一篇文章:<>& ...

  3. Redis中是如何实现分布式锁的?

    分布式锁常见的三种实现方式: 数据库乐观锁: 基于Redis的分布式锁: 基于ZooKeeper的分布式锁. 本地面试考点是,你对Redis使用熟悉吗?Redis中是如何实现分布式锁的. 要点 Red ...

  4. 【spring boot】【redis】spring boot基于redis的LUA脚本 实现分布式锁

    spring boot基于redis的LUA脚本 实现分布式锁[都是基于redis单点下] 一.spring boot 1.5.X 基于redis 的 lua脚本实现分布式锁 1.pom.xml &l ...

  5. python使用redis实现协同控制的分布式锁

    python使用redis实现协同控制的分布式锁 上午的时候,有个腾讯的朋友问我,关于用zookeeper分布式锁的设计,他的需求其实很简单,就是节点之间的协同合作. 我以前用redis写过一个网络锁 ...

  6. Redis的“假事务”与分布式锁

    关注公众号:CoderBuff,回复"redis"获取<Redis5.x入门教程>完整版PDF. <Redis5.x入门教程>目录 第一章 · 准备工作 第 ...

  7. 使用数据库、Redis、ZK分别实现分布式锁!

    分布式锁三种实现方式: 基于数据库实现分布式锁: 基于缓存(Redis等)实现分布式锁: 基于Zookeeper实现分布式锁: 基于数据库实现分布式锁 悲观锁 利用select - where - f ...

  8. 终极锁实战:单JVM锁+分布式锁

    目录 1.前言 2.单JVM锁 3.分布式锁 4.总结 =========正文分割线================= 1.前言 锁就像一把钥匙,需要加锁的代码就像一个房间.出现互斥操作的场景:多人同 ...

  9. redis 加锁与释放锁(分布式锁)

    使用Redis的 SETNX 命令可以实现分布式锁 SETNX key value 返回值 返回整数,具体为 - 1,当 key 的值被设置 - 0,当 key 的值没被设置

随机推荐

  1. js控件实现修改预览的功能

    http://nytimes.github.io/ice/demo/ https://johnresig.com/projects/javascript-diff-algorithm/

  2. Python Deque 模块使用详解,python中yield的用法详解

    Deque模块是Python标准库collections中的一项. 它提供了两端都可以操作的序列, 这意味着, 你可以在序列前后都执行添加或删除. https://blog.csdn.net/qq_3 ...

  3. 04 npm 命令大全

    一.npm简介   npm(Node Package Manager)是随同node.js 一起安装的包管理工具,为了解决nodejs代码部署上的很多问题,常用以下场景: 允许用户从npm服务器下载别 ...

  4. 【Linux开发】linux中关于dma_alloc_coherent的用法

    大家都知道,DMA的操作是需要物理地址的,但是在linux内核中使用的都是虚拟地址,如果我们想要用DMA对一段内存进行操作,我们如何得到这一段内存的物理地址和虚拟地址的映射呢?dma_alloc_co ...

  5. SpringBoot配置文件值植入

    <!‐‐导入配置文件处理器,配置文件进行绑定就会有提示‐‐> <dependency> <groupId>org.springframework.boot</ ...

  6. PTA(Advanced Level)1011.World Cup Betting

    With the 2010 FIFA World Cup running, football fans the world over were becoming increasingly excite ...

  7. 什么是数据传输服务DTS

    数据传输服务(Data Transmission Service) DTS支持关系型数据库.NoSQL.大数据(OLAP)等数据源间的数据传输. 它是一种集数据迁移.数据订阅及数据实时同步于一体的数据 ...

  8. myeclipse使用db-brower连接到sqlserver2012踩坑经历

    myeclipse使用db-brower连接到sqlserver踩坑经历 首先得建立个角色 右键->创建登录名 权限开大点 连接设置 Driver template选择我选这个,格式按照我的写 ...

  9. Fiddler--模拟弱网

    1.首先要勾选Rules--Performance--Simulate Modem Speeds 2.点击Customer Rules 3.然后找到 修改这个值就好. 备注:修改完保存后,要重新勾选第 ...

  10. GitHub从小白到熟悉<二>

    创建 仓库