Redis做分布式锁

/**
* 基于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;
}

 

posted @ 2020-08-11 15:18  爵士灬  阅读(100)  评论(0编辑  收藏  举报