首页 > 其他 > 详细

Redis做分布式锁

时间:2020-08-11 16:06:55      阅读:52      评论:0      收藏:0      [点我收藏+]

/**
* 基于Redis的 setnx特性
* **/

import redis.clients.jedis.Jedis;

public class RedisLock {

//加入redis锁
public static boolean tryLock(String methods){
Jedis jedis = new Jedis("127.0.0.1", 6379);
while (true){
try {
Long flag = jedis.setnx(methods, "ok");
if(flag>0){
return true;
}
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//解锁redis锁
public static void UnLock(String methods){
Jedis jedis = new Jedis("127.0.0.1", 6379);
jedis.del(methods);
}
}

 


/**
* 竞拍加价 加入了redis锁
* **/
@RequestMapping(value = "/updateCurrPrice")
@ResponseBody
public double updateCurrPrice(double addmoney,Integer commid){
if(RedisLock.tryLock("updateCurrPrice")){
Integer addcurrpeice = commodityService.addcurrpeice(addmoney, commid);
RedisLock.UnLock("updateCurrPrice");
return addmoney;
}
return 0;
}

 

Redis做分布式锁

原文:https://www.cnblogs.com/sunnycc/p/13475790.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!