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

相关文章

Python实现终端清屏的几种方式详解

《Python实现终端清屏的几种方式详解》在使用Python进行终端交互式编程时,我们经常需要清空当前终端屏幕的内容,本文为大家整理了几种常见的实现方法,有需要的小伙伴可以参考下... 目录方法一:使用 `os` 模块调用系统命令方法二:使用 `subprocess` 模块执行命令方法三:打印多个换行符模拟

SpringBoot+EasyPOI轻松实现Excel和Word导出PDF

《SpringBoot+EasyPOI轻松实现Excel和Word导出PDF》在企业级开发中,将Excel和Word文档导出为PDF是常见需求,本文将结合​​EasyPOI和​​Aspose系列工具实... 目录一、环境准备与依赖配置1.1 方案选型1.2 依赖配置(商业库方案)二、Excel 导出 PDF

Python实现MQTT通信的示例代码

《Python实现MQTT通信的示例代码》本文主要介绍了Python实现MQTT通信的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 安装paho-mqtt库‌2. 搭建MQTT代理服务器(Broker)‌‌3. pytho

spring中的@MapperScan注解属性解析

《spring中的@MapperScan注解属性解析》@MapperScan是Spring集成MyBatis时自动扫描Mapper接口的注解,简化配置并支持多数据源,通过属性控制扫描路径和过滤条件,利... 目录一、核心功能与作用二、注解属性解析三、底层实现原理四、使用场景与最佳实践五、注意事项与常见问题六

使用zip4j实现Java中的ZIP文件加密压缩的操作方法

《使用zip4j实现Java中的ZIP文件加密压缩的操作方法》本文介绍如何通过Maven集成zip4j1.3.2库创建带密码保护的ZIP文件,涵盖依赖配置、代码示例及加密原理,确保数据安全性,感兴趣的... 目录1. zip4j库介绍和版本1.1 zip4j库概述1.2 zip4j的版本演变1.3 zip4

python生成随机唯一id的几种实现方法

《python生成随机唯一id的几种实现方法》在Python中生成随机唯一ID有多种方法,根据不同的需求场景可以选择最适合的方案,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习... 目录方法 1:使用 UUID 模块(推荐)方法 2:使用 Secrets 模块(安全敏感场景)方法

Redis中Stream详解及应用小结

《Redis中Stream详解及应用小结》RedisStreams是Redis5.0引入的新功能,提供了一种类似于传统消息队列的机制,但具有更高的灵活性和可扩展性,本文给大家介绍Redis中Strea... 目录1. Redis Stream 概述2. Redis Stream 的基本操作2.1. XADD

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

《SpringBoot结合WxJava实现文章上传微信公众号草稿箱与群发》本文将详细介绍如何使用SpringBoot框架结合WxJava开发工具包,实现文章上传到微信公众号草稿箱以及群发功能,... 目录一、项目环境准备1.1 开发环境1.2 微信公众号准备二、Spring Boot 项目搭建2.1 创建

IntelliJ IDEA2025创建SpringBoot项目的实现步骤

《IntelliJIDEA2025创建SpringBoot项目的实现步骤》本文主要介绍了IntelliJIDEA2025创建SpringBoot项目的实现步骤,文中通过示例代码介绍的非常详细,对大家... 目录一、创建 Spring Boot 项目1. 新建项目2. 基础配置3. 选择依赖4. 生成项目5.