注解的方式实现redis分布式锁

简介: 创建redisLock注解:import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.

创建redisLock注解:

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.concurrent.TimeUnit;

/**
 * redis锁注解
 * @author MAZHEN
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
public @interface RedisLock {
    String lockPrefix() default "";
    long timeOut() default 60;
    TimeUnit timeUnit() default TimeUnit.SECONDS;
}

拦截器逻辑:

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.aspectj.apache.bcel.classfile.Constant;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.spring.mongo.annotation.RedisLock;

/**
 * redis锁拦截器实现
 * @author MAZHEN
 */
@Aspect
@Component
public class RedisLockInterceptor {

    private static final Integer MAX_RETRY_COUNT = 10;
    private static final String LOCK_PRE_FIX = "lockPreFix";
    private static final String TIME_OUT = "timeOut";

    @Autowired
    private RedisManager redisManager;

    @Pointcut("@annotation(com.spring.mongo.annotation.RedisLock)")
    public void redisLockAspect(){}

    @Around("redisLockAspect()")
    public Map<String, Object> lockAroundAction(ProceedingJoinPoint proceeding){
        //获取redis锁
        Map<String, Object> getLockResult = this.getLock(proceeding,0,System.currentTimeMillis());
    }

    /**
     * 获取锁
     * @param proceeding
     * @return
     */
    private Map<String, Object> getLock(ProceedingJoinPoint proceeding,int count,long currentTime){
        //获取注解中的参数
        Map<String, Object> annotationArgs = this.getAnnotationArgs(proceeding);
        String lockPrefix = (String) annotationArgs.get(LOCK_PRE_FIX);
        long expire = (long) annotationArgs.get(TIME_OUT);
        String key = this.getFirstArg(proceeding);
        if(StringUtils.isEmpty(lockPrefix) || StringUtils.isEmpty(key)){
            return this.argErrResult("锁前缀或业务参数不能为空");
        }
        String lockName = lockPrefix+"_"+key;
        String value = String.valueOf(currentTime);
        if(CommonRedisUtils.setNx(lockName,value) == 1){
            //获取锁成功
            CommonRedisUtils.expire(lockName,expire);
            return this.buildSuccessResult();
        }else {
            //获取锁失败,为防止其它线程正在设置过时时间时误删,添加第一个条件
            if((System.currentTimeMillis()-currentTime>5000)
                    &&(CommonRedisUtils.ttl(lockName)<0
                            ||System.currentTimeMillis()-currentTime>expire)){
                //强制删除锁,并尝试再次获取锁
                CommonRedisUtils.delete(lockName);
                if(count<MAX_RETRY_COUNT){
                    return getLock(proceeding,count++,currentTime);
                }
            }
            return this.buildGetLockErrorResult("请重试!!!");
        }
    }

    /**
     * 获取锁参数
     * @param proceeding
     * @return
     */
    private Map<String, Object> getAnnotationArgs(ProceedingJoinPoint proceeding){
        Class target = proceeding.getTarget().getClass();
        Method[] methods = target.getMethods();
        String methodName = proceeding.getSignature().getName();
        for (Method method : methods) {
            if(method.getName().equals(methodName)){
                Map<String, Object> result = new HashMap<String, Object>();
                RedisLock redisLock = method.getAnnotation(RedisLock.class);
                result.put(LOCK_PRE_FIX,redisLock.lockPrefix());
                result.put(TIME_OUT, redisLock.timeUnit().toSeconds(redisLock.timeOut()));
                return result;
            }
        }
        return null;
    }

    /**
     * 获取第一个String类型的参数为锁的业务参数
     * @param proceeding
     * @return
     */
    public String getFirstArg(ProceedingJoinPoint proceeding){
        Object[] args = proceeding.getArgs();
        if(args != null && args.length>0){
            for (Object object : args) {
                String type = object.getClass().getName();
                if("java.lang.String".equals(type)){
                    return (String)object;
                }
            }
        }
        return null;
    }

    public Map<String, Object> argErrResult(String mes){
        Map<String, Object> result = new HashMap<String, Object>();
        //TODO
        //result.put("code", "9");
        result.put("msg", mes);
        return result;
    }

    public Map<String, Object> buildGetLockErrorResult(String mes){
        Map<String, Object> result = new HashMap<String, Object>();
        //TODO
        //result.put("code", "9");
        result.put("msg", mes);
        return result;
    }

    public Map<String, Object> buildSuccessResult(){
        Map<String, Object> result = new HashMap<String, Object>();
        //TODO
        //result.put("code", "1");
        result.put("msg", "处理成功");
        return result;
    }
}

使用方式:只需要在需要使用redis锁的方法上添加@RedisLock注解,并输入redis锁的前缀字段,过时时间和时间单位有默认值,而方法上的第一个String类型的参数为锁的key的第二段。

目录
相关文章
|
11月前
|
存储 负载均衡 NoSQL
【赵渝强老师】Redis Cluster分布式集群
Redis Cluster是Redis的分布式存储解决方案,通过哈希槽(slot)实现数据分片,支持水平扩展,具备高可用性和负载均衡能力,适用于大规模数据场景。
763 2
|
11月前
|
存储 缓存 NoSQL
【📕分布式锁通关指南 12】源码剖析redisson如何利用Redis数据结构实现Semaphore和CountDownLatch
本文解析 Redisson 如何通过 Redis 实现分布式信号量(RSemaphore)与倒数闩(RCountDownLatch),利用 Lua 脚本与原子操作保障分布式环境下的同步控制,帮助开发者更好地理解其原理与应用。
823 6
|
12月前
|
存储 缓存 NoSQL
Redis核心数据结构与分布式锁实现详解
Redis 是高性能键值数据库,支持多种数据结构,如字符串、列表、集合、哈希、有序集合等,广泛用于缓存、消息队列和实时数据处理。本文详解其核心数据结构及分布式锁实现,帮助开发者提升系统性能与并发控制能力。
|
10月前
|
NoSQL Java 调度
分布式锁与分布式锁使用 Redis 和 Spring Boot 进行调度锁(不带 ShedLock)
分布式锁是分布式系统中用于同步多节点访问共享资源的机制,防止并发操作带来的冲突。本文介绍了基于Spring Boot和Redis实现分布式锁的技术方案,涵盖锁的获取与释放、Redis配置、服务调度及多实例运行等内容,通过Docker Compose搭建环境,验证了锁的有效性与互斥特性。
873 0
分布式锁与分布式锁使用 Redis 和 Spring Boot 进行调度锁(不带 ShedLock)
|
10月前
|
缓存 NoSQL 关系型数据库
Redis缓存和分布式锁
Redis 是一种高性能的键值存储系统,广泛用于缓存、消息队列和内存数据库。其典型应用包括缓解关系型数据库压力,通过缓存热点数据提高查询效率,支持高并发访问。此外,Redis 还可用于实现分布式锁,解决分布式系统中的资源竞争问题。文章还探讨了缓存的更新策略、缓存穿透与雪崩的解决方案,以及 Redlock 算法等关键技术。
|
缓存 NoSQL 关系型数据库
美团面试:MySQL有1000w数据,redis只存20w的数据,如何做 缓存 设计?
美团面试:MySQL有1000w数据,redis只存20w的数据,如何做 缓存 设计?
美团面试:MySQL有1000w数据,redis只存20w的数据,如何做 缓存 设计?
|
缓存 NoSQL Java
Redis+Caffeine构建高性能二级缓存
大家好,我是摘星。今天为大家带来的是Redis+Caffeine构建高性能二级缓存,废话不多说直接开始~
1741 0
|
9月前
|
缓存 负载均衡 监控
135_负载均衡:Redis缓存 - 提高缓存命中率的配置与最佳实践
在现代大型语言模型(LLM)部署架构中,缓存系统扮演着至关重要的角色。随着LLM应用规模的不断扩大和用户需求的持续增长,如何构建高效、可靠的缓存架构成为系统性能优化的核心挑战。Redis作为业界领先的内存数据库,因其高性能、丰富的数据结构和灵活的配置选项,已成为LLM部署中首选的缓存解决方案。
898 25
|
10月前
|
存储 缓存 NoSQL
Redis专题-实战篇二-商户查询缓存
本文介绍了缓存的基本概念、应用场景及实现方式,涵盖Redis缓存设计、缓存更新策略、缓存穿透问题及其解决方案。重点讲解了缓存空对象与布隆过滤器的使用,并通过代码示例演示了商铺查询的缓存优化实践。
396 1
Redis专题-实战篇二-商户查询缓存
|
9月前
|
缓存 运维 监控
Redis 7.0 高性能缓存架构设计与优化
🌟蒋星熠Jaxonic,技术宇宙中的星际旅人。深耕Redis 7.0高性能缓存架构,探索函数化编程、多层缓存、集群优化与分片消息系统,用代码在二进制星河中谱写极客诗篇。
1781 3