redis分布式锁

redis实现微服务锁

Redis

1
2
3
4
5
6
7
8
9
10
11
12
13
@Autowired
private StringRedisTemplate rs;

// 不推荐使用,推荐使用Redisson方式
public void redisFenBuShiLock() {
ValueOperations<String, String> ops = rs.opsForValue();
String uuid = UUID.randomUUID().toString();
// 上锁 20秒过期
ops.setIfAbsent("lock", uuid, 20, TimeUnit.SECONDS);
// 删除锁,保证原子性
String scrapt = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
Long i = rs.execute(new DefaultRedisScript<>(scrapt, Long.class), Arrays.asList("lock"), uuid);
}

Redisson

pom依赖

1
2
3
4
5
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.12.0</version>
</dependency>

SpringBoot配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 集群模式
@Bean
public RedissonClient redisson() throws IOException {
Config config = new Config();
//可以用"rediss://"来启用SSL连接
config.useClusterServers()
.addNodeAddress("redis://127.0.0.1:6379","redis://127.0.0.1:6380");
return Redisson.create(config);
}

// 单节点模式
@Bean
public RedissonClient redisson() throws IOException {
Config config = new Config();
//可以用"rediss://"来启用SSL连接
config.useSingleServer()
.setAddress("redis://127.0.0.1:6379");
return Redisson.create(config);
}

测试

可重入锁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Autowired
public RedissonClient redisson

public void test(){
RLock lock = redisson.getLock("lock-name");
// 加锁 会自动续期
lock.lock();
// 指定锁时间 10s过期时间 不会自动续期
// lock.lock(10,TimeUnit.SECONDS);
try{
// 执行业务逻辑
}catch(Exception e){

}finally{
// 解锁
lock.unlock();
}
}

读写锁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Autowired
public RedissonClient redisson

public void test(){
RReadWriteLock lock = redisson.getReadWriteLock("ReadWriteLock");
// 写锁
RLock writeLock = lock.writeLock();

// 读锁
RLock readLock = lock.readLock();
// 指定锁时间 10s过期时间 不会自动续期
// lock.lock(10,TimeUnit.SECONDS);
try{
writeLock.lock();
// 执行业务逻辑
}catch(Exception e){

}finally{
// 解锁
writeLock.unlock();
readLock.unlock();
}
}

相关文章

SpringCloud

服务注册与发现

服务调用

SpringCloud-OpenFeign问题

SpringCloud-GateWay工具类

DockerCompose常用软件配置

SpringQuartz动态定时任务

Redis集群搭建

服务链路追踪

K8S