public static void main(String[] args) {
RedissonClient redisson = null;
try{
Config config = new Config();
config.useSingleServer().setAddress("127.0.0.1:6379");
redisson = Redisson.create(config);
Thread t = new Thread(()->{
try{
RedissonClient redisson1 = Redisson.create(config);
RLock rLock = redisson1.getLock("myLock");
System.out.println("Thead1开始");
rLock.lock();
System.out.println("Thead1获得锁");
Thread.sleep(10000);
System.out.println("Thread1 do something");
System.out.println("Thead1准备释放锁");
rLock.unlock();
System.out.println("Thead1结束");
redisson1.shutdown();
}
catch (Exception ex){}
});
t.start();
Thread t2 = new Thread(()->{
RedissonClient redisson1 = Redisson.create(config);
RLock rLock = redisson1.getLock("myLock");
System.out.println("Thead2开始");
rLock.lock();
System.out.println("Thead2获得锁");
System.out.println("Thread2 do something");
System.out.println("Thead2准备释放锁");
rLock.unlock();
System.out.println("Thead2结束");
redisson1.shutdown();
});
t2.start();
}
catch (Exception ex){
System.out.println(ex.getMessage());
}
finally {
redisson.shutdown();
}
}
运行结果:
image.png
简单的两句,就实现了分布式锁,那是相当方便的一个工具。
rLock.lock();
rLock.unlock();
加锁的锁key(这里是myLock)默认生存时间是30秒,如果超过了30秒,锁会自动删除,也就是线程崩掉了,锁也会到时间释放的。
而如果操作时长超过了30秒,锁也不会自动消失,运行中会有个后台线程,帮你一直延长这个锁的时间。
深入的用法,可以参考这里:
https://blog.csdn.net/l1028386804/article/details/73523810
网友评论