注解代码:

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; /**
* Created by qhong on 2018/9/5 11:12
**/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface CreditRedisCache {
String prefix() default "huishi-server:credit";
}

利用拦截器处理注解中的方法,有就调用缓存,没有就新增

import com.alibaba.fastjson.JSON;
import com.shitou.huishi.annotation.CreditRedisCache;
import com.shitou.huishi.utils.RedisUtil;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; /**
* Created by qhong on 2018/9/5 11:13
**/
@Aspect
@Component
@Slf4j
public class RedisCacheAspect { @Autowired
RedisUtil redisUtil; /**
* 分隔符 生成key 格式为 类全类名|方法名|参数所属类全类名
**/
private static final String DELIMITER = "-"; private static final Long expireTime=60*60*24*30L; /**
* Service层切点 使用到了我们定义的 RedisCache 作为切点表达式。
* 而且我们可以看出此表达式基于 annotation。
* 并且用于内建属性为查询的方法之上
*/
@Pointcut("@annotation(com.shitou.huishi.annotation.CreditRedisCache)")
public void redisCacheAspect() {
} /**
* Around 手动控制调用核心业务逻辑,以及调用前和调用后的处理,
* <p>
* 注意:当核心业务抛异常后,立即退出,转向AfterAdvice 执行完AfterAdvice,再转到ThrowingAdvice
*
* @param pjp the pjp
* @return object
* @throws Throwable the throwable
*/
@Around(value = "redisCacheAspect()")
public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
// 得到类名、方法名和参数
String clazzName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs(); // 根据类名、方法名和参数生成Key
log.info("key参数: " + clazzName + "." + methodName);
String key = getKey(clazzName, methodName, args);
if (log.isInfoEnabled()) {
log.info("生成key: " + key);
} // 得到被代理的方法
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod(); //redis 前缀
String prefix = method.getAnnotation(CreditRedisCache.class).prefix(); // 检查Redis中是否有缓存
Object value = redisUtil.get(prefix, key); // 得到被代理方法的返回值类型
Class returnType = ((MethodSignature) joinPoint.getSignature()).getReturnType(); // result是方法的最终返回结果
Object result = null;
try {
if (null == value) {
log.info("缓存未命中");
// 调用数据库查询方法
result = joinPoint.proceed(args);
// 结果放入缓存
redisUtil.set(prefix, key, result,expireTime);
} else {
// 缓存命中
log.info("缓存命中, value = " + JSON.toJSONString(value));
result = value;
}
} catch (Throwable e) {
log.error("程序异常",e.getMessage());
throw e;
}
return result;
} /**
* * 根据类名、方法名和参数生成Key
* * @param clazzName
* * @param methodName
* * @param args
* * @return key格式:全类名|方法名|参数类型
*
*/
private String getKey(String clazzName, String methodName, Object[] args) {
StringBuilder key = new StringBuilder(clazzName);
key.append(DELIMITER);
key.append(methodName);
key.append(DELIMITER);
key.append(Arrays.stream(args).map(x->x.toString()).collect(Collectors.joining(DELIMITER)));
return key.toString();
} }

使用:

	@CreditRedisCache
public DataResponse queryICInfo(String name,String card)

直接在方法上使用即可,如果要自定义前缀,可以添加prefix,不然使用默认值。

这种很类似Spring-Cache,但是自己的代码比较灵活 ,可以针对不同的模块设定前缀,缓存时间等。

参考:

https://www.jianshu.com/p/95ddef3168f8

https://www.cnblogs.com/hongdada/p/9263699.html

SpringBoot 注解调用Redis缓存的更多相关文章

  1. 小白的springboot之路(八)、继承Redis以及@Cacheable注解实现Redis缓存

    0.前言 在项目中,缓存作为一种高效的提升性能的手段,几乎必不可少,Redis作为其中的佼佼者被广泛应用: 一.spring boot集成Redis 1.添加依赖 <dependency> ...

  2. 在springboot中使用redis缓存,将缓存序列化为json格式的数据

    背景 在springboot中使用redis缓存结合spring缓存注解,当缓存成功后使用gui界面查看redis中的数据 原因 springboot缓存默认的序列化是jdk提供的 Serializa ...

  3. 完整SpringBoot Cache整合redis缓存(二)

    缓存注解概念 名称 解释 Cache 缓存接口,定义缓存操作.实现有:RedisCache.EhCacheCache.ConcurrentMapCache等 CacheManager 缓存管理器,管理 ...

  4. springboot 2 集成 redis 缓存 序列化

    springboot 缓存 为了实现是在数据中查询数据还是在缓存中查询数据,在application.yml 中将mybatis 对应的mapper 包日志设置为debug . spring: dat ...

  5. C# mvc 前端调用 redis 缓存的信息

    新手 这几天网上学习下redis ,自己总结下过程,怕之后忘记了,基本会用最简单的,有的还是不懂,先记下来,自己摸索的. 没有安装redis的先安装,教程:http://www.cnblogs.com ...

  6. springboot项目:Redis缓存使用

    保存Redis 第一步:启动类中加入注解 @EnableCaching package com.payease; import org.springframework.boot.SpringAppli ...

  7. 搞懂分布式技术14:Spring Boot使用注解集成Redis缓存

    本文内容参考网络,侵删 本系列文章将整理到我在GitHub上的<Java面试指南>仓库,更多精彩内容请到我的仓库里查看 https://github.com/h2pl/Java-Tutor ...

  8. SpringBoot缓存管理(二) 整合Redis缓存实现

    SpringBoot支持的缓存组件 在SpringBoot中,数据的缓存管理存储依赖于Spring框架中cache相关的org.springframework.cache.Cache和org.spri ...

  9. ssm+redis 如何更简洁的利用自定义注解+AOP实现redis缓存

    基于 ssm + maven + redis 使用自定义注解 利用aop基于AspectJ方式 实现redis缓存 如何能更简洁的利用aop实现redis缓存,话不多说,上demo 需求: 数据查询时 ...

随机推荐

  1. 关于js语句的分号

    我在使用js的时候可能发现一个现象:js语句结尾有时候有分号,有时候没有,没有的时候js代码也是能正确执行的. 到底要不要写分号?QAQ 转自博客园@winter-cn JavaScript自动加分号 ...

  2. SQLGetEnvAttr

    SQLGetEnvAttr 函数定义: 用于得到当前环境的各项设置属性 SQLRETURN SQLGetEnvAttr( SQLHENV     EnvironmentHandle, SQLINTEG ...

  3. valueError: This solver needs samples of at least 2 classes in the data, but the data contains only one class: 0

    问题描述:执行下面的代码,报错valueError: This solver needs samples of at least 2 classes in the data, but the data ...

  4. hdu4870 高斯消元

    题意 一个人打比赛 ,rating 有p的概率 为加50分 有1-p的概率为 x-100分 最大值为 1000 最小值为0 有两个号 每次拿较小的号来提交 , 计算最后到达 1000分得期望场数是多少 ...

  5. volatile 线程内存模型

  6. 【swiper轮播插件】解决swiper轮播插件触控屏问题

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  7. (cvpr2019 ) Technology details of Deep Learning for Multiple-Image Super-Resolution

    Mutiple-Image SSR 关键的技术imformation fusion 1. 将单一场景的多图像经过Resnet, 其中每张图片的维度变为了输入的两倍.同时,这些输入的单一场景的多图像进行 ...

  8. 以太坊智能合约介绍,Solidity介绍

    以太坊智能合约介绍,Solidity介绍 一个简单的智能合约 先从一个非常基础的例子开始,不用担心你现在还一点都不了解,我们将逐步了解到更多的细节. Storage contract SimpleSt ...

  9. [转载]SQL中EXISTS的用法

    比如在Northwind数据库中有一个查询为SELECT c.CustomerId,CompanyName FROM Customers cWHERE EXISTS(SELECT OrderID FR ...

  10. Django后端项目----restful framework 认证源码流程

    一.请求到来之后,都要先执行dispatch方法,dispatch方法方法根据请求方式的不同触发get/post/put/delete等方法 注意,APIView中的dispatch方法有很多的功能 ...