当前位置: 首页> 汽车> 车展 > 企业网站设计布局方式_宣传手册设计模板_成都最新数据消息_外贸网站建设公司哪家好

企业网站设计布局方式_宣传手册设计模板_成都最新数据消息_外贸网站建设公司哪家好

时间:2025/7/19 7:51:54来源:https://blog.csdn.net/PleaseBeStrong/article/details/145521160 浏览次数: 0次
企业网站设计布局方式_宣传手册设计模板_成都最新数据消息_外贸网站建设公司哪家好

1. 需求分析

某公司需要将原有的Redis缓存抽离出来,并且还要要实现:

  1. 可配置
  2. 热拔插
  3. 高可用
  4. 高通用

请问你会如何实现?

2. 思路

话不多说直接上思路:

  1. 自定义缓存注解,当容器扫描到该注解自动调用AOP想应的增强方法为原有的业务逻辑赋能
  2. 使用SpringEL表达式占位符扩展

3. 代码实现

3.1 注解创建

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyRedisCatch {// 前缀String keyPrefix();// 匹配的value值String matchValue();
}

3.2 切面类

@Component
@Aspect
public class MyRedisCacheAspect {@Resourceprivate RedisTemplate redisTemplate;//换成自己注解的全类名@Around("@annotation(com.example.redisexercises.annotation.MyRedisCatch)")public Object doCatch(ProceedingJoinPoint joinPoint){Object res = null;try {//获取当前的方法MethodSignature signature = (MethodSignature) joinPoint.getSignature();Method method = signature.getMethod();//获取方法上的注解MyRedisCatch redisCatchAnnotation = method.getAnnotation(MyRedisCatch.class);//获得注解中的参数String keyPrefix = redisCatchAnnotation.keyPrefix();String matchValue = redisCatchAnnotation.matchValue();//SpringEL解析器SpelExpressionParser spelExpressionParser = new SpelExpressionParser();Expression expression = spelExpressionParser.parseExpression(matchValue);EvaluationContext context = new StandardEvaluationContext();//获得方法中形参Object[] args = joinPoint.getArgs();DefaultParameterNameDiscoverer defaultParameterNameDiscoverer = new DefaultParameterNameDiscoverer();String[] parameterNames = defaultParameterNameDiscoverer.getParameterNames(method);for(int i = 0;i< parameterNames.length;i++){context.setVariable(parameterNames[i], args[i].toString());}//拼接最终redis keyString key = keyPrefix + ":" + expression.getValue(context).toString();//查询redisres = redisTemplate.opsForValue().get(key);if(res != null){return res;}//没查询到结果则则主业务类查数据库res = joinPoint.proceed();//最终回填到redis中,下次查询命中if(res != null)redisTemplate.opsForValue().set(key, res, 60, TimeUnit.SECONDS);}catch (Throwable throwable){throwable.printStackTrace();}return res;}
}

3.3 在任意方法上标注注解以实现缓存功能

@ApiOperation("获取商品")
@GetMapping("/get/{id}")
@MyRedisCatch(keyPrefix = "user", matchValue = "id")
public Order get(@PathVariable Integer id){//数据库查找业务逻辑
}
关键字:企业网站设计布局方式_宣传手册设计模板_成都最新数据消息_外贸网站建设公司哪家好

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: