您现在的位置是:网站首页> 编程资料编程资料
基于 Spring Aop 环绕通知实现 Redis 缓存双删功能(示例代码)_Redis_
2023-05-27
472人已围观
简介 基于 Spring Aop 环绕通知实现 Redis 缓存双删功能(示例代码)_Redis_
基于 spring aop 常规应用场景多是用于日志记录以及实现 redis 分布式锁,在 github 中也有项目是把它拿来当作缓存的异常捕捉。从而避免影响实际业务的开发;在某天,笔者有个业务开发是给某个服务模块增加 redis 缓存。增加缓存就会涉及 redis 删除。所以笔者就在思考是不是可以用环绕通知的方式来进行实现
代码实现
结构示意图:
自定义注解 RedisDelByDbUpdate
@Repeatable 表示允许在同一个地方上使用相同的注解,没有该注解时贴相同注解会报错
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented @Repeatable(RedisDelByDbUpdateList.class) public @interface RedisDelByDbUpdate { /** * 具体操作得缓存前缀 */ String redisPrefix() default ""; /** * 具体的缓存名称,为空则删除 redisPrefix 下的所有缓存 */ String fieldName() default ""; }
自定义注解 RedisDelByUpdateList
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface RedisDelByDbUpdateList { RedisDelByDbUpdate[] value(); }
具体实现 redis 双删逻辑
@Aspect @Component @Slf4j public class RedisDelAspect_bak { //环绕增强 @Autowired private RedisUtil redis; @Pointcut("@annotation(com.cili.baseserver.aop.annotation.RedisDelByDbUpdate) " + "|| @annotation(com.cili.baseserver.aop.annotation.RedisDelByDbUpdateList)") public void pointCut() { } // 线程池定长设置:最佳线程数目 = ((线程等待时间+线程CPU时间)/线程CPU时间 )* CPU数目 ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(26); /** * 环绕增强 * * @param point * @return * @throws Throwable */ @Around("pointCut()") public Object around(ProceedingJoinPoint point) throws Throwable { MethodSignature signature = (MethodSignature) point.getSignature(); Method method = signature.getMethod(); RedisDelByDbUpdate redisDelByDbUpdate = method.getAnnotation(RedisDelByDbUpdate.class); if (redisDelByDbUpdate != null) { return singleRedisDel(redisDelByDbUpdate, point); } RedisDelByDbUpdateList updateList = method.getAnnotation(RedisDelByDbUpdateList.class); return arraysRedisDel(updateList, point); } private Object singleRedisDel(RedisDelByDbUpdate redisDelByDbUpdate, ProceedingJoinPoint point) throws Throwable { return handle(redisDelByDbUpdate, point, new IObjectCallback
注解使用示例
public class Test { @Override @RedisDelByDbUpdate(redisPrefix = RedisConstant.BANNER, fieldName = "ids") @RedisDelByDbUpdate(redisPrefix = RedisConstant.BANNER_LIST) public void batchDeleted(Listids) throws BizException { if (CollectionUtils.isEmpty(ids)) { log.info("banner ID 不能为空"); throw new BizException(BaseResponseCode.PARAM_IS_NOT_NULL); } try { bannerMapper.batchDeleted(ids); } catch (Exception e) { log.error("==>批量删除Banner错误:{}<==", e); throw new BizException(BaseResponseCode.SYSTEM_BUSY); } } }
到此这篇关于基于 Spring Aop 环绕通知实现 Redis 缓存双删的文章就介绍到这了,更多相关Spring Aop Redis 缓存双删内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
您可能感兴趣的文章: