栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Redisson分布式锁(使用注解方式)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Redisson分布式锁(使用注解方式)

引入pom依赖
        
            org.redisson
            redisson-spring-boot-starter
            3.13.1
        
配置RedissonClient
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.redisson.config.TransportMode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class RedissonConfig {

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.password}")
    private String password;

    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        // 这里使用最简单的单机模式
        SingleServerConfig singleServerConfig = config.useSingleServer();
        singleServerConfig.setAddress("redis://" + host + ":" + port);
        singleServerConfig.setPassword(password);
        return Redisson.create(config);
    }
}
自定义RedissonLock注解
import java.lang.annotation.*;
import java.util.concurrent.TimeUnit;


@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface RedissonLock {

    
    String value();

    
    String key() default "";

    
    long time() default -1;

    
    TimeUnit timeUnit() default TimeUnit.SECONDS;
}
定义Aspect
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;



@Component
@Aspect
public class RedissonLockAspect {

    @Autowired
    private RedissonClient redissonClient;
    
    // redis key全局前缀
    @Value("${spring.redis.prefix}")
    private String redisPrefix;

    
    private final SpelExpressionParser spelExpressionParser = new SpelExpressionParser();
    
    private final DefaultParameterNameDiscoverer defaultParameterNameDiscoverer = new DefaultParameterNameDiscoverer();

    @Pointcut("@annotation(com.xxx.annotation.RedissonLock)")
    public void LockAspect() {}

    @Around("LockAspect()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object object;
        RLock lock = null;
        try {
            // 获取注解实体信息
            RedissonLock lockEntity =
                (((MethodSignature)proceedingJoinPoint.getSignature()).getMethod()).getAnnotation(RedissonLock.class);
            String key = lockEntity.key();
            String cacheName = lockEntity.value();
            long time = lockEntity.time();
            TimeUnit timeUnit = lockEntity.timeUnit();
            // 根据名字获取锁实例
            lock = redissonClient.getLock(getKey(cacheName, key, proceedingJoinPoint));
            // 这里加锁失败会阻塞等待;也可以使用tryLock,不阻塞,加锁失败返回flase,自行处理后续逻辑(比如抛异常)
            lock.lock(time, timeUnit);
            object = proceedingJoinPoint.proceed();
        } finally {
            if (Objects.nonNull(lock) && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
        return object;
    }

    @AfterThrowing(value = "LockAspect()", throwing = "ex")
    public void afterThrowing(Throwable ex) {
        throw new RuntimeException(ex);
    }

    
    public String getKey(String cacheName, String spel, ProceedingJoinPoint proceedingJoinPoint) {
        MethodSignature methodSignature = (MethodSignature)proceedingJoinPoint.getSignature();
        String[] paramNames = defaultParameterNameDiscoverer.getParameterNames(methodSignature.getMethod());
        if (!"".equals(spel) && null != paramNames && paramNames.length > 0) {
            EvaluationContext context = new StandardEvaluationContext();
            Object[] args = proceedingJoinPoint.getArgs();
            for (int i = 0; i < args.length; i++) {
                context.setVariable(paramNames[i], args[i]);
            }
            Object value = spelExpressionParser.parseExpression(spel).getValue(context);
            if (null != value) {
                return redisPrefix + ":" + cacheName + ":" + value;
            }
        }
        return redisPrefix + ":" + cacheName;
    }
}
使用
    // 也可以指定加锁时间 time设值
    @RedissonLock(value = "test:lock", key = "#id")
    public void testLock(Long id) {
        // ...
    }
查看redis中的锁

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/936499.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号