贵州遵义企业公司网站建设,给别人做网站做什么科目,长沙微信小程序公司,wordpress 页面美化1.原始写法
我们平常使用redisson的分布式锁是不是基本都用下面的这个模板#xff0c;既然是模板#xff0c;那为何不把他抽出来呢#xff1f;
// 尝试加锁#xff0c;最多等待100秒#xff0c;上锁以后10秒自动解锁
boolean res lock.tryLock(100, 10, TimeUnit.SECON…1.原始写法
我们平常使用redisson的分布式锁是不是基本都用下面的这个模板既然是模板那为何不把他抽出来呢
// 尝试加锁最多等待100秒上锁以后10秒自动解锁
boolean res lock.tryLock(100, 10, TimeUnit.SECONDS);
if (res) {try {...业务代码} finally {lock.unlock();}
}2.抽出分布式锁工具类
我们可以抽出一个 LockService 方法把锁的模板写在方法里调用的时候只需要指定 key把锁内的代码块用 supplier 函数传进来。
Service
Slf4j
public class LockService {Autowiredprivate RedissonClient redissonClient;public T T executeWithLock(String key, int waitTime, TimeUnit unit, SupplierThrowT supplier) throws Throwable {RLock lock redissonClient.getLock(key);boolean lockSuccess lock.tryLock(waitTime, unit);if (!lockSuccess) {throw new BusinessException(CommonErrorEnum.LOCK_LIMIT);}try {return supplier.get();//执行锁内的代码逻辑} finally {lock.unlock();}}
}
使用起来就方便了
lockService.executeWithLock(key, 10, TimeUnit.SECONDS, ()-{//执行业务逻辑。。。。。return null;
});
如果我们不需要排队等锁甚至还能重载方法减少两个参数。
lockService.executeWithLock(key, ()-{//执行业务逻辑。。。。。return null;
});
还能不能更简便呢当然
3.注解实现分布式锁
其实锁工具类已经是核心功能代码了用注解只是为了使用方便。就像很多底层sdk都是有接口调用的方法来实现核心功能然后再加个注解让使用更加简便。来想一想场景我们的分布式锁很多时候都是加在最外层也就是controller上或者是service某个方法上。我们通常加锁需要的key都是由入参组装的。那是不是可以用el表达式来组装key呢
3.1 创建注解RedissonLock
/*** 分布式锁注解*/
Retention(RetentionPolicy.RUNTIME)//运行时生效
Target(ElementType.METHOD)//作用在方法上
public interface RedissonLock {/*** key的前缀,默认取方法全限定名除非我们在不同方法上对同一个资源做分布式锁就自己指定** return key的前缀*/String prefixKey() default ;/*** springEl 表达式** return 表达式*/String key();/*** 等待锁的时间默认-1不等待直接失败,redisson默认也是-1** return 单位秒*/int waitTime() default -1;/*** 等待锁的时间单位默认毫秒** return 单位*/TimeUnit unit() default TimeUnit.MILLISECONDS;}
约定大于配置的思想我们的大多数参数都是可以默认的。很多时候我们的锁都是针对方法的要锁同一处地方调用同一个方法就好了这样前缀可以直接默认根据类方法名来实现同样针对特例我们也提供了自己指定前缀的入口。
3.2 实现切面RedissonLockAspect
切面其实很简单构建key前缀el表达式然后把参数都传进去调用我们核心功能的工具类LockService。
Slf4j
Aspect
Component
Order(0)//确保比事务注解先执行分布式锁在事务外
public class RedissonLockAspect {Autowiredprivate LockService lockService;Around(annotation(com.abin.mallchat.common.common.annotation.RedissonLock))public Object around(ProceedingJoinPoint joinPoint) throws Throwable {Method method ((MethodSignature) joinPoint.getSignature()).getMethod();RedissonLock redissonLock method.getAnnotation(RedissonLock.class);String prefix StrUtil.isBlank(redissonLock.prefixKey()) ? SpElUtils.getMethodKey(method) : redissonLock.prefixKey();//默认方法限定名注解排名可能多个String key SpElUtils.parseSpEl(method, joinPoint.getArgs(), redissonLock.key());return lockService.executeWithLockThrows(prefix : key, redissonLock.waitTime(), redissonLock.unit(), joinPoint::proceed);}
}
上述解析EL表达式需要定义以下解析类
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;import java.lang.reflect.Method;
import java.util.Optional;/*** Description: spring el表达式解析*/
public class SpElUtils {private static final ExpressionParser parser new SpelExpressionParser();private static final DefaultParameterNameDiscoverer parameterNameDiscoverer new DefaultParameterNameDiscoverer();public static String parseSpEl(Method method, Object[] args, String spEl) {//解析参数名String[] params Optional.ofNullable(parameterNameDiscoverer.getParameterNames(method)).orElse(new String[]{});EvaluationContext context new StandardEvaluationContext();//el解析需要的上下文对象for (int i 0; i params.length; i) {context.setVariable(params[i], args[i]);//所有参数都作为原材料扔进去}Expression expression parser.parseExpression(spEl);return expression.getValue(context, String.class);}public static String getMethodKey(Method method) {return method.getDeclaringClass() # method.getName();}
}
3.3 使用
以mallchat项目为例使用起来就非常方便了发奖的时候我们需要对uid加锁直接一个注解搞定。如果需要等待再加个等待时间就行。这里需要注意分布式锁要在事务外层。所以我们锁的切面优先级要高一些。
Service
public class UserBackpackServiceImpl implements IUserBackpackService {Autowiredprivate UserBackpackDao userBackpackDao;Autowiredprivate ItemCache itemCache;Autowiredprivate ApplicationEventPublisher applicationEventPublisher;AutowiredLazyprivate UserBackpackServiceImpl userBackpackService;Overridepublic void acquireItem(Long uid, Long itemId, IdempotentEnum idempotentEnum, String businessId) {//组装幂等号String idempotent getIdempotent(itemId, idempotentEnum, businessId);userBackpackService.doAcquireItem(uid, itemId, idempotent);}RedissonLock(key #idempotent, waitTime 5000)//相同幂等如果同时发奖需要排队等上一个执行完取出之前数据返回public void doAcquireItem(Long uid, Long itemId, String idempotent) {UserBackpack userBackpack userBackpackDao.getByIdp(idempotent);//幂等检查if (Objects.nonNull(userBackpack)) {return;}//业务检查ItemConfig itemConfig itemCache.getById(itemId);if (ItemTypeEnum.BADGE.getType().equals(itemConfig.getType())) {//徽章类型做唯一性检查Integer countByValidItemId userBackpackDao.getCountByValidItemId(uid, itemId);if (countByValidItemId 0) {//已经有徽章了不发return;}}//发物品UserBackpack insert UserBackpack.builder().uid(uid).itemId(itemId).status(YesOrNoEnum.NO.getStatus()).idempotent(idempotent).build();userBackpackDao.save(insert);//用户收到物品的事件applicationEventPublisher.publishEvent(new ItemReceiveEvent(this, insert));}private String getIdempotent(Long itemId, IdempotentEnum idempotentEnum, String businessId) {return String.format(%d_%d_%s, itemId, idempotentEnum.getType(), businessId);}
}