setnx(key,value) 如果key不存在,设置为当前key的值为value;如果key存在,直接返回。 expire()来设置超时时间
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Lockable{
// redis缓存key
String key();
// redis缓存key中的数据
String value() default "";
// 过期时间(秒),默认为一分钟
long expire() default 60;
}
@Lockable(key = "DistributedLock:dealExpireRecords")
public void dealExpireRecords() {
}
@Component
@Slf4j
@Aspect
public class LockAspect {
@Autowired
private RedisTemplate redisTemplate;
@Around("@annotation(com.records.aop.Lockable)")
public Object distributeLock(ProceedingJoinPoint pjp) {
Object resultObject = null;
//确认此注解是用在方法上
Signature signature = pjp.getSignature();
if (!(signature instanceof MethodSignature)) {
log.error("Lockable is method annotation!");
return resultObject;
}
MethodSignature methodSignature = (MethodSignature) signature;
Method targetMethod = methodSignature.getMethod();
//获取注解信息
Lockable lockable = targetMethod.getAnnotation(Lockable.class);
String key = lockable.key();
String value = lockable.value();
long expire = lockable.expire();
// 分布式锁,如果没有此key,设置此值并返回true;如果有此key,则返回false
boolean result = redisTemplate.boundValueOps(key).setIfAbsent(value);
if (!result) {
//其他程序已经获取分布式锁
return resultObject;
}
//设置过期时间,默认一分钟
redisTemplate.boundValueOps(key).expire(expire, TimeUnit.SECONDS);
try {
resultObject = pjp.proceed(); //调用对应方法执行
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return resultObject;
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有