Redis做锁小案例
使用redis做锁
import redis.clients.jedis.Jedis;
/**
* MyRedisLock
*/
public class MyRedisLock {
/**
* 得到锁
*
* @param model 方法名
* @return
*/
public static boolean getLock(String model) {
Jedis jedis = new Jedis("127.0.0.1", 6379);
while (true) {
long setnx = jedis.setnx(model, "1");
if (setnx == 1) {
return true;
}
}
}
/**
* 释放锁
*
* @param model
*/
public static void realsLock(String model) {
Jedis jedis = new Jedis("127.0.0.1", 6379);
jedis.del(model);
}
}
连接到redis,由于多个setnx指令并发,能够返回1的只有1个,其他都是0。并且redis天生单进程单线程
从而可以做锁;
使用锁:
public class Shop {
private int num = 1;
public void buyOne() {
if (RedisLock.getLock("buyOne")) {
if (num > 0) {
System.out.println(Thread.currentThread().getName() + "购买成功");
num--;
} else {
System.out.println(Thread.currentThread().getName() + "库存不足");
}
RedisLock.realsLock("buyOne");
}
}
}
测试结果:
public class Mian {
public static void main(String[] args) {
Shop shop = new Shop();
Thread t1 = new Thread(() -> {
shop.buyOne();
}, "客户端1");
Thread t2 = new Thread(() -> {
shop.buyOne();
}, "客户端2");
t1.start();
t2.start();
}
}
多次运行结果都是: