spring boot 整合redis对查询数据做缓存( 利用spring的AOP技术)
来源:互联网 发布:java多态笔记 编辑:程序博客网 时间:2024/06/05 10:03
本篇主要介绍spring boot 整合redis做数据缓存,利用的是spring aop切面编程技术,利用注解标识切面。
这里不再介绍spring boot操作数据库,有兴趣的话,我最后会给出源码链接
一,引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> <version>1.3.2.RELEASE</version> </dependency>
二,配置redis连接
配置文件我里这用的是yml格式的,tab缩进,如果是properties格式的,请自己改造
redis 安装请参考 Redis安装
windows管理工具可以用RedisDesktopManager,测试的时候,可以直接删除缓存。
spring: redis: database: 0 ## Redis服务器地址 host: 192.168.50.128 ## Redis服务器连接端口 port: 6379 ## Redis服务器连接密码(默认为空) password: ## 连接超时时间(毫秒) timeout: 0 ## 连接池最大连接数(使用负值表示没有限制) pool: max-active: 8 ## 连接池最大阻塞等待时间(使用负值表示没有限制) max-wait: -1 ## 连接池中的最大空闲连接 max-idle: 8 ## 连接池中的最小空闲连接 min-idle: 0
三,注解
注解 QueryCache 用来标识查询数据库的方法,参数nameSpace用来区分应用的,后面会用来添加到缓存的key中。比如,登陆应用缓存的数据key值全部都是sso开头。
package com.example.common.annotation;import com.example.common.CacheNameSpace;import java.lang.annotation.*;/** * Created by mazhenhua on 2017/5/3. */@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD})@Documentedpublic @interface QueryCache { CacheNameSpace nameSpace();}
注解 QueryCacheKey 是方法级别的注解,用来标注要查询数据的主键,会和上面的nameSpace组合做缓存的key值
package com.example.common.annotation;import java.lang.annotation.*;/** * Created by mazhenhua on 2017/5/3. */@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.PARAMETER})@Documentedpublic @interface QueryCacheKey {}
枚举 CacheNameSpace 用来保存nameSpace的
package com.example.common;/** * Created by mazhenhua on 2017/5/3. */public enum CacheNameSpace { SSO_USER}
下面就是组合起来的用法,userMapper.findById(id)是用来查询数据库的方法
@QueryCache(nameSpace = CacheNameSpace.SSO_USER) public UserInfo findUserById(@QueryCacheKey Long id) { UserInfo userInfo = userMapper.findById(id); return userInfo; }
四,Aop切面
下面是重点,代码中的注释已经很多了,应该能看的懂,如有问题,可以留言。
package com.example.common.aspect;import com.example.common.CacheNameSpace;import com.example.common.annotation.QueryCache;import com.example.common.annotation.QueryCacheKey;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.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.core.MethodParameter;import org.springframework.core.annotation.SynthesizingMethodParameter;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.ValueOperations;import org.springframework.stereotype.Service;import javax.annotation.Resource;import java.lang.annotation.Annotation;import java.lang.reflect.Method;import java.util.concurrent.TimeUnit;/** * Created by mazhenhua on 2017/5/3. */@Aspect@Servicepublic class DBCacheAspect { private static final Logger LOGGER = LoggerFactory.getLogger(DBCacheAspect.class); @Resource private RedisTemplate redisTemplate; /** * 定义拦截规则:拦截所有@QueryCache注解的方法。 */ /*@Pointcut("execution(* com.example.service.impl..*(..)) , @annotation(com.example.common.annotation.QueryCache)") public void queryCachePointcut(){}*/ @Pointcut("@annotation(com.example.common.annotation.QueryCache)") public void queryCachePointcut(){} /** * 拦截器具体实现 * @param pjp * @return * @throws Throwable */ @Around("queryCachePointcut()") public Object Interceptor(ProceedingJoinPoint pjp) throws Throwable { long beginTime = System.currentTimeMillis(); LOGGER.info("AOP 缓存切面处理 >>>> start "); MethodSignature signature = (MethodSignature) pjp.getSignature(); Method method = signature.getMethod(); //获取被拦截的方法 CacheNameSpace cacheType = method.getAnnotation(QueryCache.class).nameSpace(); String key = null; int i = 0; // 循环所有的参数 for (Object value : pjp.getArgs()) { MethodParameter methodParam = new SynthesizingMethodParameter(method, i); Annotation[] paramAnns = methodParam.getParameterAnnotations(); // 循环参数上所有的注解 for (Annotation paramAnn : paramAnns) { if ( paramAnn instanceof QueryCacheKey) { // QueryCacheKey requestParam = (QueryCacheKey) paramAnn; key = cacheType.name() + "_" + value; // 取到QueryCacheKey的标识参数的值 } } i++; } // 获取不到key值,抛异常 if (StringUtils.isBlank(key)) throw new Exception("缓存key值不存在"); LOGGER.info("获取到缓存key值 >>>> " + key); ValueOperations<String, Object> operations = redisTemplate.opsForValue(); boolean hasKey = redisTemplate.hasKey(key); if (hasKey) { // 缓存中获取到数据,直接返回。 Object object = operations.get(key); LOGGER.info("从缓存中获取到数据 >>>> " + object.toString()); LOGGER.info("AOP 缓存切面处理 >>>> end 耗时:" + (System.currentTimeMillis() - beginTime)); return object; } // 缓存中没有数据,调用原始方法查询数据库 Object object = pjp.proceed(); operations.set(key, object, 30, TimeUnit.MINUTES); // 设置超时时间30分钟 LOGGER.info("DB取到数据并存入缓存 >>>> " + object.toString()); LOGGER.info("AOP 缓存切面处理 >>>> end 耗时:" + (System.currentTimeMillis() - beginTime)); return object; }}
五,测试
@Test public void testFindById(){ UserInfo userInfo = userService.findUserById(210001L); }
六,执行结果
两张图对比一下很明显,从redis缓存中取数据耗时要少的多。
GitHub :https://github.com/mazh1992/sso/tree/master/ucenter
1 0
- spring boot 整合redis对查询数据做缓存( 利用spring的AOP技术)
- spring boot 整合redis对查询数据做缓存( 利用spring的AOP技术)
- 利用Spring的aop整合redis缓存
- spring-boot | 整合Redis缓存数据
- Spring Boot使用redis做数据缓存
- Spring Boot使用redis做数据缓存
- Spring Boot使用redis做数据缓存
- Spring Boot使用redis做数据缓存
- Spring Boot集成redis做数据缓存
- Spring Boot使用redis做数据缓存
- Spring Boot使用redis做数据缓存
- spring boot使用redis做数据缓存
- Spring Boot使用redis做数据缓存
- Spring AOP 整合Redis 缓存
- spring aop 做redis缓存
- redis整合spring实现对数据的缓存
- spring-boot整合redis作为缓存(2)——spring-boot的缓存
- Spring Boot对Redis的整合
- 深入理解vuex
- Java动态代理机制
- I Hate It(hdu 1754)线段树
- Azure SQLServer 添加Azure Active Directory管理员
- 聊聊三方支付对接那点事儿
- spring boot 整合redis对查询数据做缓存( 利用spring的AOP技术)
- MongoDB学习记录04-MongoDB聚合操作
- 数论常用内容——素数
- Problem F: 多少个最大值?
- 关于背景层与内部层继承的解决方案
- 用cmd命令行,adb连手机,查看手机歌曲,中文歌曲乱码解决办法
- C++中ifstream/ofstream/fstream浅谈
- String转换为其他数据类型
- 源码分析系列