redis 缓存注解+切面实现

注解 
package com.olivia.sdk.ann;

import java.lang.annotation.*;
import java.util.concurrent.TimeUnit;

/***
 *
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RedissonCacheAnn {

  //组名称(user:info)
  String group() default "";

  //SpelExpression表达式的key,已#开头,单个字段#userId,对象中的字段#dto.userId
  String key();

  //超时时间单位(默认秒)
  TimeUnit unit() default TimeUnit.SECONDS;

  //超时时间-默认1个小时
  long ttl() default 3600L;

}
实现类
package com.olivia.sdk.aspect;


import com.olivia.sdk.ann.RedissonCacheAnn;
import com.olivia.sdk.utils.SpelUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Slf4j
@Aspect
@Component
public class RedisCacheSetAspect {
  @Resource
  RedisTemplate<String, Object> redisTemplate;

  @Pointcut("@annotation(com.olivia.sdk.ann.RedissonCacheAnn)")
  public void aspect() {
  }

  @Around("aspect()")
  public Object around(ProceedingJoinPoint point) throws Throwable {
    String methodName = point.getSignature().getName();
    Class<?> classTarget = point.getTarget().getClass();
    Class<?>[] par = ((MethodSignature) point.getSignature()).getParameterTypes();
    Method objMethod = classTarget.getMethod(methodName, par);
    //判断返回值,如果是void则直接返回处理结果
    if (objMethod.getReturnType().equals(Void.TYPE)) {
      log.warn("@CacheSet method={}  use CachePut but has no return value.", methodName);
      return point.proceed(point.getArgs());
    }
    String key = null;
    RedissonCacheAnn cacheAnn = objMethod.getAnnotation(RedissonCacheAnn.class);
    Object result = null;
    String tmKey = cacheAnn.key();
    if (StringUtils.isNotBlank(tmKey) && tmKey.startsWith("#")) {
      tmKey = SpelUtils.parseKey(cacheAnn.key(), objMethod, point.getArgs());
    }
    key = "cache:" + cacheAnn.group() + ":" + tmKey;
    if (log.isDebugEnabled()) log.debug("RedissonCacheAnn {}  key {}", methodName, key);

    try {
      Object cacheValue = redisTemplate.opsForValue().get(key);
      if (cacheValue != null) {
        if (log.isDebugEnabled()) {
          if (log.isDebugEnabled()) log.debug("RedissonCacheAnn {}  value: {}", methodName, cacheValue);
        }
        //存在缓存数据,返回数据
        return cacheValue;
      }
    } catch (Exception e) {
      log.error("RedissonCacheAnn {} get error: {}", methodName, e.getMessage());
    }
    //缓存中无数据时初始化缓存值
    result = point.proceed();
    try {
      redisTemplate.opsForValue().set(key, result, cacheAnn.ttl(), cacheAnn.unit());
    } catch (Exception e) {
      log.error("RedissonCacheAnn {}  set error: {}", methodName, e.getMessage());
    }
    return result;
  }


}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值