性格左右命运,气度影响格局。——余世雅博士
代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| public static int EXPIRE_SECONDS = 5 * 60; @Resource private RedissonClient redissonClient;
@Override @Transactional(rollbackFor = Throwable.class, isolation = Isolation.READ_UNCOMMITTED, propagation = Propagation.REQUIRED) public <T> T lockByName(String lockName, Supplier<T> supplier) { RLock lock = redissonClient.getLock(lockName); try { if (lock.tryLock(EXPIRE_SECONDS, TimeUnit.SECONDS)) { return supplier.get(); } } catch (Exception e) { log.error("Something Wrong with:", e); } finally { lock.unlock(); } return null; }
|
如何使用就不再赘述了,和我之前写的redis
防止缓存穿透击穿雪崩的那篇博客差不多的
不过以防万一还是写一个吧哈哈
1 2 3 4
| redisManager.lockByName("achao"), () -> { return ""; });
|
在多线程场景下锁生效
如果我们需要集群下的RedLock
则可以如下实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
@Override @Transactional(rollbackFor = Throwable.class, isolation = Isolation.READ_UNCOMMITTED, propagation = Propagation.REQUIRED) public <T> T lockByName(String lockName, Supplier<T> supplier) { RLock lock = redissonClientFirst.getLock(lockName); RLock second = redissonClientSecond.getLock(lockName); RLock third = redissonClientThird.getLock(lockName); RedissonRedLock redissonRedLock = new RedissonRedLock(lock,second,third); try { if (redissonRedLock.tryLock(EXPIRE_SECONDS, TimeUnit.SECONDS)) { return supplier.get(); } } catch (Exception e) { log.error("Something Wrong with:", e); } finally { redissonRedLock.unlock(); } return null; }
|