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

最近有时间又折腾了一下,之前只能将结果用对象序列化的方式放入redis中,现在改为json字符串,并通过反射拿到原来类型 ,
并且在今天有重构了一下代码,自定义注解中的所有属性都已实现


主要修改了之前使用redisUtil使用jdk对象序列化的方式来缓存,现在改为StringRedistemplate 的方式,细节大家就看下面的
代码吧,祝你们生活愉快哦

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

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

@Configuration
public class MyRedisConfig {
	
    /**
    自定义redistemplate
    */
	@Bean
	public 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 // 将某个缓存管理器作为默认的
	@Bean
	public 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 .创建自定义注解
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;  //默认值是以分钟为单位
	
}
2. 创建aspect类 (在这里要多最一句:切面=切入点+通知/增强)

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


package com.yunsuibi.common.aop;

import com.alibaba.fastjson.JSONObject;
import com.yunsuibi.common.annotation.Cacheable;
import org.apache.commons.lang.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.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * ClassName    RedisAop
 * Package	    com.yunsuibi.common.aop
 * Description  aop缓存
 *
 * @author cyf
 * @date 2019/4/28 15:41
 */
@Component
@Aspect
public class CacheableAop {

    @Autowired
    private StringRedisTemplate redisTemplate;

    //切入点:方法上带有@Cacheable注解的方法
    @Pointcut(value = "@annotation(com.yunsuibi.common.annotation.Cacheable)")
    public void pointCut() {
    }

    //这里通知选用环绕通知,由于首先要判断缓存中是否存在,存在则返回,不存在则放过查询数据库,查询完数据库就要放入缓存中,所以其他四种都不合适
    @Around(value = "pointCut()")
    public Object cache(ProceedingJoinPoint joinPoint) throws Throwable {
        Method method = getMethod(joinPoint);
        Cacheable cacheable = method.getAnnotation(Cacheable.class);
        String key = cacheable.key();
        Object[] args = joinPoint.getArgs();
        String prefix = cacheable.name();
        String methodName = method.getName();
        String cacheKey = getCacheableKey(key, prefix, args,methodName);
        Object proceed = null;
        String value = getValueInCacheByKey(cacheKey);
        if (StringUtils.isNotBlank(value)) {
            return getValueActualTypeData(method, value);
        } else {
            proceed = joinPoint.proceed();
            // 查询到的数据库数据保存到redis
            String results = JSONObject.toJSONString(proceed);
            long expireTime = cacheable.expireTime();
            TimeUnit unit = cacheable.unit();
            setValueInCache(cacheKey, results, expireTime, unit);
            return proceed;
        }
    }

    private void setValueInCache(String cacheKey, String results, long expireTime, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(cacheKey, results, expireTime, timeUnit);
    }

    private String getValueInCacheByKey(String cacheKey) {
        return redisTemplate.opsForValue().get(cacheKey);
    }

    private Object getValueActualTypeData(Method method, String value) throws ClassNotFoundException {
        Class returnActualType = getReturnActualType(method);
        if (null != returnActualType) {
            return JSONObject.parseArray(value, returnActualType);
        }
        return null;
    }

    private Method getMethod(ProceedingJoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        return methodSignature.getMethod();
    }

    private Class getReturnActualType(Method method) throws ClassNotFoundException {
        Type genericReturnType = method.getGenericReturnType();
        if (genericReturnType instanceof ParameterizedType) {
            Type[] actualTypes = ((ParameterizedType) genericReturnType).getActualTypeArguments();
            for (Type actualType : actualTypes) {
                return Class.forName(actualType.getTypeName());
            }
        }
        return null;
    }

    /**
     * 获取要缓存的key 默认值为查询条件的第一个参数 可以通过key属性指定key
     *
     * @param key       存储的key
     * @param prefix    存储前缀
     * @param args      方法入参参数
     * @param methodName 方法名称,当方法没有入参时且没有指定key默认使用方法名称作为key
     * @return
     */
    public String getCacheableKey(String key, String prefix, Object[] args,String methodName) {
        String cacheKey = "";
        if (StringUtils.isNotBlank(prefix)) {
            cacheKey = "/" + prefix + "/";
        }
        if (StringUtils.isNotBlank(key)) {
            return cacheKey += key;
        }
        if (null != args && 0 < args.length) {
            return cacheKey += args[0];
        }
        return methodName;//方法名称
    }
}


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

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

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

云随笔:www.yunsuibi.com 欢迎大家来支持
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值