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

相关文章

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

【专题】2024飞行汽车技术全景报告合集PDF分享(附原数据表)

原文链接: https://tecdat.cn/?p=37628 6月16日,小鹏汇天旅航者X2在北京大兴国际机场临空经济区完成首飞,这也是小鹏汇天的产品在京津冀地区进行的首次飞行。小鹏汇天方面还表示,公司准备量产,并计划今年四季度开启预售小鹏汇天分体式飞行汽车,探索分体式飞行汽车城际通勤。阅读原文,获取专题报告合集全文,解锁文末271份飞行汽车相关行业研究报告。 据悉,业内人士对飞行汽车行业

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]

缓存雪崩问题

缓存雪崩是缓存中大量key失效后当高并发到来时导致大量请求到数据库,瞬间耗尽数据库资源,导致数据库无法使用。 解决方案: 1、使用锁进行控制 2、对同一类型信息的key设置不同的过期时间 3、缓存预热 1. 什么是缓存雪崩 缓存雪崩是指在短时间内,大量缓存数据同时失效,导致所有请求直接涌向数据库,瞬间增加数据库的负载压力,可能导致数据库性能下降甚至崩溃。这种情况往往发生在缓存中大量 k