/** * 锁定一个key,***一定要手工释放锁 * * @param key * @return */ public boolean lockKey(String key) { return redisTemplate.opsForValue().setIfAbsent(key, 0); } /** * 锁定一个key,指定锁定时间 * * @param key * @param time * @return */ public boolean lockKey(String key, int locktime) { return redisTemplate.opsForValue().setIfAbsent(key, 0, locktime, TimeUnit.SECONDS); } /** * 自旋加锁 * * @param key * @param trytime * @return */ public boolean lockKeySpin(String key, int trytime, long sleepTime) { for (int i = 0; i < trytime; i++) { boolean flag = redisTemplate.opsForValue().setIfAbsent(key, 0); if (flag) return true; try { Thread.sleep(sleepTime); } catch (InterruptedException e) { continue; } } return false; } /** * 锁定一个key,指定锁定时间,***一定要手工释放锁 * * @param key * @param trytime * @param sleepTime * @param locktime * @return */ public boolean lockKeySpin(String key, int trytime, long sleepTime, int locktime) { for (int i = 0; i < trytime; i++) { boolean flag = redisTemplate.opsForValue().setIfAbsent(key, 0, locktime, TimeUnit.SECONDS); if (flag) return true; try { Thread.sleep(sleepTime); } catch (InterruptedException e) { continue; } } return false; } /** * 释放锁 * * @param key * @return */ public boolean unlockKey(String key) { return redisTemplate.delete(key); }