javaspringbootredis20行代码实现分布式锁

编程

话不多说,直接上源码

import com.xiangmi.repair.service.DistributedLockService;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.concurrent.TimeUnit;

/**

* @author asdtiang

* @desc Redis 锁工具类

*/

@Service

public class RedisDistributedLockImpl implements DistributedLockService {

private static final Logger logger = LoggerFactory.getLogger(RedisDistributedLockImpl.class);

@Resource

private RedisTemplate<String, Object> redisTemplate;

private static String LOCK_VALUE = "LOCK_VALUE";

/**

* @param key redis key, 唯一键

* @return true 获得锁成功,false,获得锁失败

* @desc 加锁 true已锁 false未锁

*/

public boolean getLock(String key, long time, TimeUnit unit) {

if (redisTemplate.opsForValue().setIfAbsent(key, LOCK_VALUE, time, unit)) { // 对应setnx命令

return true;

}

return false;

}

/**

* @param key redis key, 唯一键

* @return

* @desc 释放锁

*/

public void releaseLock(String key) {

try {

redisTemplate.opsForValue().getOperations().delete(key);// 删除key

} catch (Exception e) {

logger.error("解锁出现异常了,{}", e);

}

}

}

看到网上的代码,说了一大堆,没到重点。主要就是利用redis的原子操作,实现获取锁,设置值的超时时间,防止死锁。

 

接口类

import java.util.concurrent.TimeUnit;

/**

* @author asdtiang

*/

public interface DistributedLockService {

boolean getLock(String key, long time, TimeUnit unit);

void releaseLock(String key);

}

使用示例

    @Autowired

private DistributedLockService distributedLockService;

@PostConstruct

public void init() {

if(distributedLockService.getLock("lockKey", 5, TimeUnit.MINUTES)){

try {

//业务逻辑

}catch (Exception e){

e.printStackTrace();

}finally {

distributedLockService.releaseLock(RepairConstant.DATA_INIT_DISTRIBUTED_LOCK_KEY);

}

}

}

 

以上是 javaspringbootredis20行代码实现分布式锁 的全部内容, 来源链接: utcz.com/z/512741.html

回到顶部