在處理業務代碼時,總會遇到多線程對同一資源競爭,此時對已經搶到資源的線程作Lock。redis
這裏暫時先不考慮 是不是公平鎖,是否能夠重入的狀況。多線程
給出實現代碼,key爲加鎖的維度。併發
@Service public class LockManagementService { private static Logger logger = LoggerFactory.getLogger(LockManagementService.class); @Autowired private RedisService redisService; /** * 加分佈式鎖 */ public void getLock(String type,String value){ String key = type+value; Long result = redisService.setnx(key, "00"); logger.info("{},開始建立分佈式鎖...",key); while(result==0L){ Long ttl =redisService.getTtl(key); logger.info("{},併發等待中...,剩餘過時時間:{} s",key,ttl); try { Thread.sleep(500L); } catch (InterruptedException e) { logger.error("分佈式鎖線程等待出現異常:"+ e.getMessage(),e); }; result = redisService.setnx(key, "00"); } logger.info("{},成功建立分佈式鎖...",key); redisService.setKeyExpire(key, 300);//單位秒 } /** * 釋放分佈式鎖 */ public void unLock(String type,String value){ String key = type+value; redisService.del(key); logger.info("{},成功釋放分佈式鎖...",key); } }