Redis缓存 自定义注解+aspect+反射技术实现

2024-09-08 01:32

本文主要是介绍Redis缓存 自定义注解+aspect+反射技术实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

    最近再给云随笔后台增加redis模块,突然发现spring-boot-starter-data-redis模块很不人性化,实现不了通用的方式,(当然,你也可以自己写个通用的CacheUtil来实现通用的方式),但由于本人非常的爱装逼,就在这里不讲解那种傻瓜式操作了,这里只讲干货,干到你不可置信的干货).

例如:这里我使用了它其中的RedisTemplate ,发现存到redis中后,数据是乱码,看了底层才知道,它里面的序列化机制是jdk,为了修改它其中的序列化机制,就自定义redisTempate.
 

@Configuration
public class MyRedisConfig {/**自定义redistemplate*/@Beanpublic RedisTemplate<Object, SysUser> userRedisTemplate(RedisConnectionFactory redisConnectionFactory)throws UnknownHostException {RedisTemplate<Object, SysUser> template = new RedisTemplate<Object, SysUser>();template.setConnectionFactory(redisConnectionFactory);Jackson2JsonRedisSerializer<SysUser> ser = new Jackson2JsonRedisSerializer<SysUser>(SysUser.class);template.setDefaultSerializer(ser);return template;}// CacheManagerCustomizers可以来定制缓存的一些规则@Primary // 将某个缓存管理器作为默认的@Beanpublic RedisCacheManager userCacheManager(RedisTemplate<Object, SysUser> userRedisTemplate) {RedisCacheManager cacheManager = new RedisCacheManager(userRedisTemplate);// key多了一个前缀// 使用前缀,默认会将CacheName作为key的前缀cacheManager.setUsePrefix(true);return cacheManager;}}

 

此时,又发现了个问题,RedisTemplate的泛型第二个参数竟然不能是object,key,value能放进去却拿不出了,String 转换不了实际类型.

此时我决定用aspectJ+注解+反射的方式来实现通用缓存模块(用的StringRedisTamplate,这样就可以实现通用)

1 .创建aspect类 (在这里要多最一句:切面=切入点+通知/增强)
 

package com.orhonit.yunsuibi.common.aop;import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
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.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.StringUtil;
import com.orhonit.yunsuibi.common.annotation.Cacheable;
import com.orhonit.yunsuibi.common.utils.CacheUtil;/*** 切面=通知+切入点* * @author cyf* @date 2018/11/30 上午10:16:01*/
@Component
@Aspect
public class CacheableAop {}

 2 .创建自定义注解

package com.orhonit.yunsuibi.common.annotation;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.concurrent.TimeUnit;/*** 自定义注解,对于查询使用缓存的方法加入该注解* * @author Chenth*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
public @interface Cacheable {String name() default ""; String key() default ""; //要存储的key,默认是查询条件的第一个参数int expireTime() default 30;//默认30分钟TimeUnit unit() default TimeUnit.MINUTES;  //默认值是以分钟为单位}

 

3.开始写aspect中的切入点和通知

package com.orhonit.yunsuibi.common.aop;import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
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.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.StringUtil;
import com.orhonit.yunsuibi.common.annotation.Cacheable;
import com.orhonit.yunsuibi.common.utils.CacheUtil;/*** 切面=通知+切入点* * @author cyf* @date 2018/11/30 上午10:16:01*/
@Component
@Aspect
public class CacheableAop {//切入点:方法上带有@Cacheable注解的方法@Pointcut(value = "@annotation(com.orhonit.yunsuibi.common.annotation.Cacheable)")public void pointCut() {}//这里通知选用环绕通知,由于首先要判断缓存中是否存在,存在则返回,不存在则放过查询数据库,查询完数据库就要放入缓存中,所以其他四种都不合适@Around(value = "pointCut()")public Object cache(ProceedingJoinPoint joinPoint) throws Throwable {return null;}}

 

4.写一个RedisUitl,用于给aspect用

 

package com.orhonit.yunsuibi.common.utils;import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.DefaultStringRedisConnection;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;import com.alibaba.fastjson.JSON;
import com.orhonit.yunsuibi.common.annotation.Cacheable;import cn.hutool.core.io.IoUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;/*** * ClassName    RedisUtil* Package	    com.orhonit.yunsuibi.common.utils* Description  缓存工具类,采用序列化对象的方式,之前是fastjson ,发现也是转换不了实际类型-,-** @author 		cyf* @date		2018/11/20 下午11:04:32*/
@Component
public class RedisUtil {JedisPool jedisPool = new JedisPool();/*** 获取缓存中的数据* * @param key* @return* @throws UnsupportedEncodingException*/public Object getCacheByKey(String key) {// 查询Jedis jedis = jedisPool.getResource();byte[] result = jedis.get(key.getBytes());// 如果查询没有为空if (null == result) {return null;}// 查询到了,反序列化return SerializeUtil.unSerialize(result);}/***  删除缓存中的数据* @param key*/public void delCacheByKey(String key) {Jedis jedis = jedisPool.getResource();jedis.del(key);}/*** 将数据保存到缓存中的数据* @param key* @return*/public boolean setCache(String key, Object obj, int expireTime, TimeUnit unit) {// 序列化byte[] bytes = SerializeUtil.serialize(obj);// 存入redisJedis jedis = jedisPool.getResource();String success = jedis.set(key.getBytes(), bytes);if ("OK".equals(success)) {System.out.println("数据成功保存到redis...");}return true;}}

 

4.此时此刻,万事俱备,只欠东风了 ,开始写主要逻辑

package com.orhonit.yunsuibi.common.aop;import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
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.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.orhonit.yunsuibi.common.annotation.Cacheable;
import com.orhonit.yunsuibi.common.parser.DefaultResultParser;
import com.orhonit.yunsuibi.common.utils.CacheKeyUtil;
import com.orhonit.yunsuibi.common.utils.RedisUtil;import lombok.extern.slf4j.Slf4j;/*** 切面=通知+切入点* * @author cyf* @date 2018/11/30 上午10:16:01*/
@Component
@Aspect
@Slf4j
public class CacheableAop {@Autowiredprivate CacheKeyUtil keyUtil;@Autowiredprivate RedisUtil redisUtil ;private ConcurrentHashMap<String, DefaultResultParser> parserMap = new ConcurrentHashMap<String, DefaultResultParser>();@Pointcut(value = "@annotation(com.orhonit.yunsuibi.common.annotation.Cacheable)")public void getCache() {}@Around(value = "getCache()")public Object cache(ProceedingJoinPoint joinPoint) throws Throwable {log.debug("@Cacheable 注解:拦截开始");//获取方法签名MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();//通过反射得到方法Method method = methodSignature.getMethod();//获取注解Cacheable cacheable = method.getAnnotation(Cacheable.class);// 首先查询缓存,key默认使用第一个查询参数String cacheKey = keyUtil.getCacheableKey(joinPoint);Object proceed = null;Object result=null;if (StringUtils.isNotBlank(cacheKey)) {// 查询缓存Class returnType = method.getReturnType();Object value = redisUtil.getCacheByKey(cacheKey);if (null != value) {return result = value;}proceed = joinPoint.proceed();// 查询到的数据库数据保存到redislog.debug("@Cacheable 注解:redis数据保存成功");redisUtil.setCache(cacheKey, proceed, cacheable.expireTime(), cacheable.unit());}return proceed;}}

此时此刻,我就要恭喜你了,你将又成为一个大牛! 只需要在你要缓存的方法上加上@Cacheable就可以实现自定义注解实现通用缓存 -.-

/*** 通过账号查找用户信息* @param usercode * @return*/@Cacheable()public SysUser selectUserByUserCode(String usercode) {return userMapper.selectUserByUserCode(usercode);}

好了 ,到此为止,本节内容讲解完毕.讲的不好还请谅解,等云随笔后台管理完事后,云随笔前后台,以及代码开源共享!

云随笔:www.yunsuibi.com 欢迎大家来支持

不好意思 ,补充一个 ,发现少了一个序列化工具和获取缓存key的工具类

package com.orhonit.yunsuibi.common.utils;import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;/*** * ClassName    SerializeUtil* Package	    com.orhonit.yunsuibi.common.utils* Description  序列化反序列化工具** @author 		cyf* @date		2018/11/21 上午11:19:09*/
public class SerializeUtil {/*** * 序列化*/public static byte[] serialize(Object obj) {ObjectOutputStream oos = null;ByteArrayOutputStream baos = null;try {// 序列化baos = new ByteArrayOutputStream();oos = new ObjectOutputStream(baos);oos.writeObject(obj);byte[] byteArray = baos.toByteArray();return byteArray;} catch (IOException e) {e.printStackTrace();}return null;}/*** * 反序列化* * @param bytes* @return*/public static Object unSerialize(byte[] bytes) {ByteArrayInputStream bais = null;try {// 反序列化为对象bais = new ByteArrayInputStream(bytes);ObjectInputStream ois = new ObjectInputStream(bais);return ois.readObject();} catch (Exception e) {e.printStackTrace();}return null;}
}
package com.orhonit.yunsuibi.common.utils;import java.lang.reflect.Method;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import com.orhonit.yunsuibi.common.annotation.Cacheable;
import com.orhonit.yunsuibi.common.annotation.CacheableDel;
/*** * ClassName    CacheKeyUtil* Package	    com.orhonit.yunsuibi.common.utils* Description  获取缓存keyUtil** @author 		cyf* @date		2018/12/21 上午11:22:32*/
@Component
public class CacheKeyUtil {/*** 获取要缓存的key 默认值为查询条件的第一个参数 可以通过key属性指定key* * @param joinPoint* @return*/public String getCacheableKey(ProceedingJoinPoint joinPoint) {MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();Method method = methodSignature.getMethod();Cacheable cacheable = method.getAnnotation(Cacheable.class);String key = cacheable.key();String catalog = cacheable.catalog();String cacheKey="";if(StringUtils.isNotBlank(catalog)) {cacheKey+=catalog+":";}if (StringUtils.isNotBlank(key)) {return cacheKey+=key;}Object[] args = joinPoint.getArgs();return cacheKey+=args[0];}/*** 获取要删除的key 默认值为查询条件的第一个参数 可以通过key属性指定key* * @param joinPoint* @return*/public String getCacheDelKey(ProceedingJoinPoint joinPoint) {MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();Method method = methodSignature.getMethod();CacheableDel cacheable = method.getAnnotation(CacheableDel.class);String key = cacheable.key();if (StringUtils.isNotBlank(key)) {return key;}Object[] args = joinPoint.getArgs();return (String) args[0];}
}

 

 

 

这篇关于Redis缓存 自定义注解+aspect+反射技术实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1146728

相关文章

使用Java实现通用树形结构构建工具类

《使用Java实现通用树形结构构建工具类》这篇文章主要为大家详细介绍了如何使用Java实现通用树形结构构建工具类,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录完整代码一、设计思想与核心功能二、核心实现原理1. 数据结构准备阶段2. 循环依赖检测算法3. 树形结构构建4. 搜索子

MySQL多列IN查询的实现

《MySQL多列IN查询的实现》多列IN查询是一种强大的筛选工具,它允许通过多字段组合快速过滤数据,本文主要介绍了MySQL多列IN查询的实现,具有一定的参考价值,感兴趣的可以了解一下... 目录一、基础语法:多列 IN 的两种写法1. 直接值列表2. 子查询二、对比传统 OR 的写法三、性能分析与优化1.

在C#中调用Python代码的两种实现方式

《在C#中调用Python代码的两种实现方式》:本文主要介绍在C#中调用Python代码的两种实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录C#调用python代码的方式1. 使用 Python.NET2. 使用外部进程调用 Python 脚本总结C#调

Python实现自动化接收与处理手机验证码

《Python实现自动化接收与处理手机验证码》在移动互联网时代,短信验证码已成为身份验证、账号注册等环节的重要安全手段,本文将介绍如何利用Python实现验证码的自动接收,识别与转发,需要的可以参考下... 目录引言一、准备工作1.1 硬件与软件需求1.2 环境配置二、核心功能实现2.1 短信监听与获取2.

Redis 中的热点键和数据倾斜示例详解

《Redis中的热点键和数据倾斜示例详解》热点键是指在Redis中被频繁访问的特定键,这些键由于其高访问频率,可能导致Redis服务器的性能问题,尤其是在高并发场景下,本文给大家介绍Redis中的热... 目录Redis 中的热点键和数据倾斜热点键(Hot Key)定义特点应对策略示例数据倾斜(Data S

使用Python实现获取网页指定内容

《使用Python实现获取网页指定内容》在当今互联网时代,网页数据抓取是一项非常重要的技能,本文将带你从零开始学习如何使用Python获取网页中的指定内容,希望对大家有所帮助... 目录引言1. 网页抓取的基本概念2. python中的网页抓取库3. 安装必要的库4. 发送HTTP请求并获取网页内容5. 解

SpringBoot如何通过Map实现策略模式

《SpringBoot如何通过Map实现策略模式》策略模式是一种行为设计模式,它允许在运行时选择算法的行为,在Spring框架中,我们可以利用@Resource注解和Map集合来优雅地实现策略模式,这... 目录前言底层机制解析Spring的集合类型自动装配@Resource注解的行为实现原理使用直接使用M

如何自定义Nginx JSON日志格式配置

《如何自定义NginxJSON日志格式配置》Nginx作为最流行的Web服务器之一,其灵活的日志配置能力允许我们根据需求定制日志格式,本文将详细介绍如何配置Nginx以JSON格式记录访问日志,这种... 目录前言为什么选择jsON格式日志?配置步骤详解1. 安装Nginx服务2. 自定义JSON日志格式各

Python实现Microsoft Office自动化的几种方式及对比详解

《Python实现MicrosoftOffice自动化的几种方式及对比详解》办公自动化是指利用现代化设备和技术,代替办公人员的部分手动或重复性业务活动,优质而高效地处理办公事务,实现对信息的高效利用... 目录一、基于COM接口的自动化(pywin32)二、独立文件操作库1. Word处理(python-d

Java时间轮调度算法的代码实现

《Java时间轮调度算法的代码实现》时间轮是一种高效的定时调度算法,主要用于管理延时任务或周期性任务,它通过一个环形数组(时间轮)和指针来实现,将大量定时任务分摊到固定的时间槽中,极大地降低了时间复杂... 目录1、简述2、时间轮的原理3. 时间轮的实现步骤3.1 定义时间槽3.2 定义时间轮3.3 使用时