当前位置: 首页 > news >正文

redisson分布式锁--实际应用!!!

我的做法:通过切面配合注解的方式使用。

注意:切面不能应用于静态方法,私有方法,注解要被代理对象调用。

1.注解

@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface RedisLock {String name() default "";String key() default "";int waitTime() default 5;int expireTime() default -1;TimeUnit timeUnit() default TimeUnit.SECONDS;String notes() default "";String[] tags() default {""};
}

 2.切面

@Aspect
@Component
public class RedisLockAspect {private static final Logger LOGGER = LoggerFactory.getLogger(RedisLockAspect.class);private static final String REDISSON_LOCK_PREFIX = "redisson_lock:";@Lazy@Resourceprivate RedissonClient redissonClient;/*** 定义切点*/@Pointcut("@annotation(mairuirobot.iwarehousecontrol.framework.functions.iwc.redis.annotation.RedisLock)")public void redisLockPointcut() {}/*** 环绕通知*/@Around("redisLockPointcut()")public Object around(ProceedingJoinPoint joinPoint) throws Throwable {String comment;// 获取方法上的注解 RedisLockMethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();Method method = methodSignature.getMethod();RedisLock redisLock = method.getAnnotation(RedisLock.class);String name = redisLock.name();String spel = redisLock.key();String key = getRedisKey(joinPoint, name, spel);RLock rLock = redissonClient.getLock(key);boolean lock = false;Object result = null;try {// long waitTime-获取锁的等待时长;long leaseTime-持有锁的时间,-1代表默认启动看门狗机制;TimeUnit unit-时间单位lock = rLock.tryLock(redisLock.waitTime(), redisLock.expireTime(), redisLock.timeUnit());if (!lock) {comment = String.format("Redis key[%s] lock failed, it's a repeated message", key);LOGGER.error(comment);Class<?> clazz = ((MethodSignature) joinPoint.getSignature()).getReturnType();if (GeneralResponse.class == clazz) {return GeneralResponse.failure();}if (boolean.class == clazz || Boolean.class == clazz) {return false;}return GeneralResponse.failure();}result = joinPoint.proceed();} finally {if (lock) {try {rLock.unlock();} catch (IllegalMonitorStateException e) {comment = String.format("Redis key[%s] unlock failed: errMsg = ", key);LOGGER.error(comment, e);}} else {comment = String.format("Current thread did not acquire the redis key[%s] lock, skipping unlock", key);LOGGER.error(comment);}}return result;}private String getRedisKey(ProceedingJoinPoint joinPoint, String lockName, String spel) {Object[] arguments = joinPoint.getArgs();String key = REDISSON_LOCK_PREFIX + lockName + ":" + SpelUtil.parse(spel, arguments);return key;}
}

3.解析方法(需要根据你实际情况进行修改)

public class SpelUtil {public static String parse(String spel, Object[] args) {if (spel == null || spel.isEmpty()) return "";Map<Object, Object> resMap = new HashMap<>();String[] split = spel.split("\\.");Arrays.stream(args).forEach(arg -> {JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(arg));jsonObject.forEach((key, value) -> {if (value instanceof JSONObject) {((JSONObject) value).forEach((k, v) -> {resMap.put(k, v);});} else {resMap.put(key, value);}});});try {String key = split[split.length - 1];Object value = resMap.get(key);return (value != null) ? value.toString() : "";} catch (Exception e) {throw new RuntimeException("redisson参数解析失败: " + spel, e);}}
}

4.注册bean 

@Configuration
public class MyRedisRegistration {@Value("${redisson.address:}")private String redissonAddress;@Value("${redisson.password:}")private String redissonPassword;@Beanpublic RedissonClient redissonClient() {Config config = new Config();config.useSingleServer().setAddress(redissonAddress).setPassword(redissonPassword);return Redisson.create(config);}
}

 场景:申请电梯资源的时候,会有很多请求进来,导致电梯资源被争夺,这时就需要锁定电梯资源,防止同一个设备被抢占。

相关文章:

  • 决策树简介
  • redis -- redis介绍,性能(与mysql性能对比),使用场景,CAP介绍
  • gravity`(控制 View 内部内容的对齐方式)
  • Hikyuu C++与Python层交互机制
  • Vue 3中的setup【与Vue 2的区别】
  • 深度学习--深度学习概念、框架以及构造
  • GIT工具学习【1】:新安装git预操作
  • candence17.4原理图编号
  • 你了解哪些Java限流算法?
  • 深入解析操作系统的文件系统:从存储介质到数据管理的核心引擎
  • 猿辅导集团推首个教育AI范式小猿AI 聚焦家校应用场景发布3款新品
  • VGA显示
  • 【euclid】10.2 2D变换模块(transform2d.rs)Arbitrary trait
  • 蓝桥杯嵌入式十六届赛前复习总结与准备
  • linux运维篇-Ubuntu(debian)系操作系统创建源仓库
  • 基本元器件—电阻器(2025.4.14)
  • 实现表单验证
  • YOLOv2 快速入门与核心概念:更快、更准的目标检测利器
  • tap交换机配置步骤
  • 详解最大公约数做法
  • 中国政府援缅第七批抗震救灾物资运抵交付
  • 因在罗博特科并购项目中执业违规,东方证券、国浩所均遭警示
  • 思南读书会500期了,这是上海最具温度的阅读文化样本
  • 绝境逆转晋级世界杯四强,王楚钦再爆金句:能抽死我就给你了
  • 守护体面的保洁员,何时能获得体面?|离题
  • 公安部道研中心:虚假宣传自动驾驶致严重后果,责任人或处2年以下刑期