注解式缓存配置方法

@Slf4j
@Aspect
@Component
public class PushCacheInterceptor {

    @Autowired
    private BdrpProxy bdrpProxy;

    @Around("@annotation(com.xxxx.PushCacheable)")
    public Object handle(ProceedingJoinPoint jp) {
        Object result = null;
        MethodSignature signature = (MethodSignature) jp.getSignature();
        Method method = signature.getMethod();
        PushCacheable annotation = method.getAnnotation(PushCacheable.class);
        if (annotation != null) {
            GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
            String cacheKey = getCacheKey(jp, method);
            log.info("get from redis cache key is {}", cacheKey);
            long beginTime = System.currentTimeMillis();
            String rets = null;
            try {
                rets = bdrpProxy.get(RedisClusterTypeEnum.STORAGE.getType(), cacheKey);
            } catch (Throwable throwable) {
                log.error("get bdrp is exception , cache key is {}", cacheKey);
            }
            long endTime = System.currentTimeMillis();
            if (StringUtils.isNotBlank(rets)) {
                log.info("hit cache , cache key is {}, cost: {}", cacheKey, (endTime - beginTime));
                try {
                    result = jsonRedisSerializer.deserialize(rets.getBytes());
                } catch (Exception e) {
                    log.warn("[cache] hit cache, but jsonRedisSerializer.deserialize fail");
                    result = null;
                }
            }

            if (result != null) {
                return result;
            } else {
                log.info("miss cache , load from db ,cache key is {}, cost: {}", cacheKey, (endTime - beginTime));
                try {
                    result = jp.proceed();
                } catch (Throwable throwable) {
                    log.error("{} invoke 1st fail,arguments is {}", jp.getTarget().getClass().getSimpleName() + "." +
                            method.getName(), Arrays.toString(jp.getArgs()));
                }
                if (result != null && StrUtil.isNotBlank(result.toString())) {
                    int expire = annotation.expire();
                    beginTime = System.currentTimeMillis();
                    byte[] redisValue = jsonRedisSerializer.serialize(result);
                    try {
                        if (redisValue != null) {
                            bdrpProxy.setEx(RedisClusterTypeEnum.STORAGE.getType(), cacheKey,
                                    SafeEncoder.encode(redisValue), expire);
                        }
                    } catch (Throwable throwable) {
                        log.error("set bdrp is exception , cache key is {},", cacheKey, throwable);
                    }
                    endTime = System.currentTimeMillis();
                    log.info("set data to redis {}, cost: {}", result, (endTime - beginTime));
                }
            }
        } else {
            try {
                result = jp.proceed();
            } catch (Throwable throwable) {
                log.error("{} invoke 2nd fail,arguments is {}", jp.getTarget().getClass().getSimpleName() + "." +
                        method.getName(), Arrays.toString(jp.getArgs()));
            }
        }
        return result;
    }

    /**
     * 获取缓存场景Redis Key
     */
    String getCacheKey(ProceedingJoinPoint jp, Method method) {
        return RedisConstants.CACHE_KEY_PREFIX + jp.getTarget().getClass().getSimpleName() + ":" + method.getName()
                + ":" + Joiner.on(":").join(jp.getArgs());
    }

1、上方是声明缓存注解拦截

2、定义对应的注解:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface BcpPushCacheable {
    /**
     * 超时时间 默认600s
     */
    int expire() default 600;
}

3、在需要缓存的方法上直接添加上注解即可

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
J2Cache 支持使用注解的方实现声明缓存。在 Spring Boot 中,你可以使用 `@Cacheable`、`@CachePut`、`@CacheEvict` 等注解来声明缓存。 `@Cacheable`:表示该方法是需要被缓存的,如果缓存中有对应的值,则直接返回缓存中的值,否则执行方法并将返回值放入缓存。 `@CachePut`:表示该方法是需要被缓存的,每次都会执行方法并将返回值放入缓存。 `@CacheEvict`:表示该方法执行后会将缓存中对应的值删除。 下面是一个简单的示例: ```java @Service public class UserService { @Autowired private CacheChannel cacheChannel; @Cacheable(name = "userCache", key = "#userId") public User getUserById(int userId) { // 模拟从数据库中获取用户信息 User user = new User(); user.setId(userId); user.setName("test"); return user; } @CachePut(name = "userCache", key = "#user.id") public User updateUser(User user) { // 更新用户信息 return user; } @CacheEvict(name = "userCache", key = "#userId") public void deleteUserById(int userId) { // 删除用户信息 } } ``` 在上面的示例中,我们使用了 `@Cacheable`、`@CachePut`、`@CacheEvict` 注解来声明缓存。其中,`name` 属性指定了缓存名称,`key` 属性指定了缓存的 key,`#` 符号表示使用 SpEL 表达,这样可以动态地指定缓存的 key。 在实际应用中,你可以根据自己的需求来配置缓存的名称、有效时间等等。同时,你也可以根据自己的缓存策略来选择缓存的类型,比如使用本地缓存或者使用分布缓存

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值