自定义分布式锁注解

本文介绍了如何在SpringBoot中使用切面编程(AOP)和SpringAOP注解@Aspect实现分布式锁,包括基本概念、Redis分布式锁原理,以及如何自定义注解来控制加锁和解锁操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习基础:

定义加锁接口

public interface DistributedLock extends Lock {
   

    /**
     * 尝试获取分布式锁
     *
     * @param lockKey       锁
     * @param requestId     请求标识
     * @param expireSeconds 锁有效时间
     * @param overTime      超时时间
     * @param timeUnit      时间单位
     * @return 是否获取成功
     * @throws InterruptedException 中断异常
     */
    boolean tryLock(String lockKey, String requestId, int expireSeconds, int overTime, TimeUnit timeUnit) throws InterruptedException;


    /**
     * 尝试获取分布式分段锁
     * @param lockKey
     * @param segments 分段标识
     * @param requestId
     * @param expireSeconds
     * @param overTime
     * @param timeUnit
     * @return 返回成功加锁的段
     * @throws InterruptedException
     */
    String tryLock(String lockKey, List<String> segments , String requestId, int expireSeconds, int overTime, TimeUnit timeUnit) throws InterruptedException ;


        /**
         * 释放分布式锁
         *
         * @param lockKey   锁
         * @param requestId 请求标识
         */
    boolean unlock(String lockKey, String requestId);
}

实现加锁的方法

加锁本质是为了实现互斥,只让一个访问资源。redis分布式锁是根据lockKey这个key去查是否有对应的value,如果值不存在,说明并没有人访问资源,则加锁成功。如果值存在,说明已经有人在访问资源,则加锁失败。

@Component
public class RedisDistributedLock implements DistributedLock {
   

    /**
     * 成功
     */
    private final static Long SUCCESS = 1L;
    /**等待200ms*/
    private final static Long WAIT_TIME = 200L;


    /**分段锁间的时间间隔*/
    private final static Long SEGMENT_WAIT_TIME = 5L;


    private final static Long WAIT_TIME_1 = 50L;


    /**
     * 缓存
     */
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void lock() {
   
        throw new UnsupportedOperationException();
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
   
        throw new InterruptedException();
    }

    @Override
    public boolean tryLock() {
   
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean tryLock(String lockKey, String requestId, int expireSeconds, int overTime, TimeUnit timeUnit) throws InterruptedException {
   
        long lastTime = System.nanoTime();
        // 获取锁的超时时间
        long timeout = timeUnit.toNanos(overTime);
        for (; ; ) {
   
            boolean isGet = tryGe
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值