java使用redis 加鎖
配置類:
public class RedisLockUtil { private static RedisCache redisCache = null; /** * 給 key 加鎖,如果加鎖成功,則返回true,加鎖失敗返回false * @return */ public static boolean lock(String key,Integer timeout, TimeUnit timeUnit){ if (redisCache == null){ redisCache = SpringUtil.getBean(RedisCache.class); } return redisCache.setIfAbsent("LVS_LOCK:"+key,0,timeout, timeUnit); } public static boolean unLock(String key){ if (redisCache == null){ redisCache = SpringUtil.getBean(RedisCache.class); } return redisCache.deleteObject("LVS_LOCK:"+key); } }
示例:
public void createWoBoxByWo(CuxWipJobSchedule schedule) { String lockKey = "CreateWoBox:" + schedule.getJobName(); // 創(chuàng)建生成工單SN if (!RedisLockUtil.lock(lockKey, 1, TimeUnit.HOURS)) { // 存在鎖 log.info("檢查工單SN存在鎖:" + schedule.getJobName()); return; } log.info("進入到檢查工單"); try { // 執(zhí)行檢查工單外箱已經(jīng)外箱SN方法 } catch (Exception e) { log.error("", e); } finally { RedisLockUtil.unLock(lockKey); } }

浙公網(wǎng)安備 33010602011771號