SpringBoot+Redis+Lua 实现自定义分布式锁

1 分布式锁具备的条件

(1) 独占性:在分布式系统环境下,一个方法在同一时间只能被一个机器的一个线程执行。
(2) 高可用:不能因某一个节点挂了而出现获取锁和释放锁失败的情况。
(3) 防死锁:要有超时机制或撤销操作兜底释放锁。
(4)不乱抢:自己只能解自己上的锁,不能解其它线程上的锁。
(5) 可重入:同一个节点的同一个线程如果获得锁之后可以再次获取锁。

2 代码实现

@Service
@Slf4j
public class RedisService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String LOCK = "lock";

    private static final Integer LOCK_TIMEOUT = 10;

    private static ThreadLocal<String> local = new ThreadLocal<>();

    public boolean lock() {
        String uuid = getUUID();
        local.set(uuid);
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(LOCK, uuid, LOCK_TIMEOUT, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(flag);
    }

    public void unlock() {
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else  return 0 end";
        //脚本返回的是Long
        redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Collections.singletonList("lock"), local.get());
        local.remove();
    }

    private String getUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}

3 UT

测试: 10个线程,每个线程给num增加10000,判断最终结果是否为100W。

import com.rosh.RoshSpringApplication;
import com.rosh.service.RedisService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.CountDownLatch;

/**
 * @Description:
 * @Author: rosh
 * @Date: 2021/11/17 23:16
 */
@RunWith(SpringRunner.class)
//主application方法
@SpringBootTest(classes = RoshSpringApplication.class)
public class RedisLockTest {


    private Integer count = 0;

    private static final Integer COUNT_NUM = 10000;

    private static final Integer THREAD_COUNTS = 10;

    private static final CountDownLatch countDownLatch = new CountDownLatch(THREAD_COUNTS);

    @Autowired
    private RedisService redisService;

    @Test
    public void contextLoads() {
        for (int i = 1; i <= THREAD_COUNTS; i++) {
            new Thread(this::addCount, "thread" + i).start();
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void addCount() {
        try {
            if (redisService.lock()) {
                for (int i = 1; i <= COUNT_NUM; i++) {
                    count++;
                }
                countDownLatch.countDown();
                System.out.println(Thread.currentThread().getName() + " -> " + count);
            } else {
                Thread.sleep(500);
                addCount();
            }
        } catch (Exception e) {
            throw new RuntimeException("分布式锁抛出异常,异常原因:{}", e.getCause());
        } finally {
            redisService.unlock();
        }
    }

}

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
可以使用 Redisson 实现分布式锁,具体实现如下: 1. 引入 Redisson 依赖: ```xml <dependency> <groupId>org.redisson</groupId> <artifactId>redisson-spring-boot-starter</artifactId> <version>3.16.1</version> </dependency> ``` 2. 定义自定义注解 `DistributedLock`: ```java @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface DistributedLock { String value() default ""; long leaseTime() default 30L; TimeUnit timeUnit() default TimeUnit.SECONDS; } ``` 3. 在需要加锁的方法上加上 `@DistributedLock` 注解: ```java @Service public class UserService { @DistributedLock("user:#{#userId}") public User getUserById(String userId) { // ... } } ``` 4. 实现 `DistributedLockAspect` 切面: ```java @Aspect @Component public class DistributedLockAspect { private final RedissonClient redissonClient; public DistributedLockAspect(RedissonClient redissonClient) { this.redissonClient = redissonClient; } @Around("@annotation(distributedLock)") public Object around(ProceedingJoinPoint joinPoint, DistributedLock distributedLock) throws Throwable { String lockKey = distributedLock.value(); if (StringUtils.isEmpty(lockKey)) { lockKey = joinPoint.getSignature().toLongString(); } RLock lock = redissonClient.getLock(lockKey); boolean locked = lock.tryLock(distributedLock.leaseTime(), distributedLock.timeUnit()); if (!locked) { throw new RuntimeException("获取分布式锁失败"); } try { return joinPoint.proceed(); } finally { lock.unlock(); } } } ``` 5. 在 `application.yml` 中配置 Redisson: ```yaml spring: redis: host: localhost port: 6379 password: database: 0 redisson: single-server-config: address: redis://${spring.redis.host}:${spring.redis.port} ``` 这样就实现了一个基于 Redis分布式锁

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

响彻天堂丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值