@return true 获取成功, false 获取失败
- */
- public boolean getLock(Lock lock, long timeout, long tryInterval, long lockExpireTime) {
- try {
- if (StringUtils.isEmpty(lock.getName()) || StringUtils.isEmpty(lock.getValue())) {
- return false;
- }
- long startTime = System.currentTimeMillis();
- {
- if (!template.hasKey(lock.getName())) {
- ValueOperations<String, String> ops = template.opsForValue();
- ops.set(lock.getName(), lock.getValue(), lockExpireTime, TimeUnit.MILLISECONDS);
- return true;
- } else {
- // 存在锁
- logger.debug("lock is exist!!!");
- }
- if (System.currentTimeMillis() - startTime> timeout) {
- // 尝试超过了设定值之后直接跳出循环
- return false;
- }
- Thread.sleep(tryInterval);
- }
- while (template.hasKey(lock.getName())) ;
- } catch (InterruptedException e) {
- logger.error(e.getMessage());
- return false;
- }
- return false;
- }
来源: http://www.bubuko.com/infodetail-2921149.html