本文主要是介绍基于Redission实现分布式锁,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
pom文件
<dependency><groupId>org.redisson</groupId><artifactId>redisson-spring-boot-starter</artifactId><version>3.15.0</version></dependency>
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;import java.util.concurrent.TimeUnit;/*** 分布式锁实现基于Redisson*/
@Slf4j
@Component
public class RedissonLockClient {@Autowiredprivate RedissonClient redissonClient;@Autowiredprivate RedisTemplate<String, Object> redisTemplate;/*** 获取锁*/public RLock getLock(String lockKey) {return redissonClient.getLock(lockKey);}/*** 加锁操作** @return boolean*/public boolean tryLock(String lockName, long expireSeconds) {return tryLock(lockName, 0, expireSeconds);}/*** 加锁操作** @return boolean*/public boolean tryLock(String lockName, long waitTime, long expireSeconds) {RLock rLock = getLock(lockName);boolean getLock = false;try {getLock = rLock.tryLock(waitTime, expireSeconds, TimeUnit.SECONDS);if (getLock) {log.info("获取锁成功,lockName={}", lockName);} else {log.info("获取锁失败,lockName={}", lockName);}} catch (InterruptedException e) {log.error("获取式锁异常,lockName=" + lockName, e);getLock = false;}return getLock;}public boolean fairLock(String lockKey, TimeUnit unit, int leaseTime) {RLock fairLock = redissonClient.getFairLock(lockKey);try {boolean existKey = existKey(lockKey);// 已经存在了,就直接返回if (existKey) {return false;}return fairLock.tryLock(3, leaseTime, unit);} catch (InterruptedException e) {e.printStackTrace();}return false;}public boolean existKey(String key) {return redisTemplate.hasKey(key);}/*** 锁lockKey** @param lockKey* @return*/public RLock lock(String lockKey) {RLock lock = getLock(lockKey);lock.lock();return lock;}/*** 锁lockKey** @param lockKey* @param leaseTime* @return*/public RLock lock(String lockKey, long leaseTime) {RLock lock = getLock(lockKey);lock.lock(leaseTime, TimeUnit.SECONDS);return lock;}/*** 解锁** @param lockName 锁名称*/public void unlock(String lockName) {try {redissonClient.getLock(lockName).unlock();} catch (Exception e) {log.error("解锁异常,lockName=" + lockName, e);}}}
配置类
@Configuration
public class RedissonConfig {@Value("${spring.redis.host}")private String host;@Value("${spring.redis.port}")private String port;@Beanpublic RedissonClient getRedisson(){Config config = new Config();//单机模式 依次设置redis地址和密码config.useSingleServer().setAddress("redis://" + host + ":" + port);return Redisson.create(config);}
}
这篇关于基于Redission实现分布式锁的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!