配置类:
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(); // 创建生成工单SN if (!RedisLockUtil.lock(lockKey, 1, TimeUnit.HOURS)) { // 存在锁 log.info("检查工单SN存在锁:" + schedule.getJobName()); return; } log.info("进入到检查工单"); try { // 执行检查工单外箱已经外箱SN方法 } catch (Exception e) { log.error("", e); } finally { RedisLockUtil.unLock(lockKey); } }
标签:加锁,java,redis,redisCache,key,工单,return,public From: https://www.cnblogs.com/jessi200/p/17984359