`
hbxflihua
  • 浏览: 669818 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

基于spring的缓存注解实现

阅读更多

时间原因,这里只贴代码,见谅。

package com.rd.ifaes.common.annotation;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.asm.*;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 切面编程工具类
 * @author lh
 * @version 3.0
 * @since 2016-8-26
 */
public class AopUtils {

	
	private static final Logger LOGGER = LoggerFactory.getLogger(AopUtils.class);
	private static final String DESC_DOUBLE = "D";
	private static final String DESC_SHORT = "J";
	
	private AopUtils() {	}
	
	/**
	 * <p>获取方法的参数名</p>
	 *
	 * @param m
	 * @return
	 */
	public static String[] getMethodParamNames(final Method m) {
		final String[] paramNames = new String[m.getParameterTypes().length];
		final String n = m.getDeclaringClass().getName();
		final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
		String className = m.getDeclaringClass().getSimpleName();
		ClassReader cr = null;
		InputStream resourceAsStream = null;
		try {
			resourceAsStream = Class.forName(n).getResourceAsStream(className + ".class");
			cr = new ClassReader(resourceAsStream);
		} catch (IOException | ClassNotFoundException e) {
			LOGGER.warn(e.getMessage(), e);
		} finally {
			if (resourceAsStream != null) {
				try {
					resourceAsStream.close();
				} catch (IOException e) {
					LOGGER.warn(e.getMessage(), e);
				}
			}
		}

		if (cr != null) {
			cr.accept(new ClassVisitor(Opcodes.ASM4, cw) {
				@Override
				public MethodVisitor visitMethod(final int access,
						final String name, final String desc,
						final String signature, final String[] exceptions) {
					final Type[] args = Type.getArgumentTypes(desc);
					// 方法名相同并且参数个数相同
					if (!name.equals(m.getName())
							|| !sameType(args, m.getParameterTypes())) {
						return super.visitMethod(access, name, desc, signature,
								exceptions);
					}
					MethodVisitor v = cv.visitMethod(access, name, desc, signature,
							exceptions);
					return new MethodVisitor(Opcodes.ASM4, v) {
						
						int fixCount = 0;//步长修正计数器
						
						@Override
						public void visitLocalVariable(String name, String desc,
								String signature, Label start, Label end, int index) {
							int i = index - 1;
							// 如果是静态方法,则第一就是参数
							// 如果不是静态方法,则第一个是"this",然后才是方法的参数
							if (Modifier.isStatic(m.getModifiers())) {
								i = index;
							}
							if (i > fixCount) {
								i -= fixCount;
							}
							if(desc.equals(DESC_SHORT) || desc.equals(DESC_DOUBLE)){
								fixCount++;
							}
							if (i >= 0 && i < paramNames.length) {
								paramNames[i] = name;
							}
							super.visitLocalVariable(name, desc, signature, start,
									end, index);
						}
						
					};
				}
			}, 0);			
		}
		return paramNames;
	}

	/**
	 * <p>比较参数类型是否一致</p>
	 *
	 * @param types   asm的类型({@link Type})
	 * @param clazzes java 类型({@link Class})
	 * @return
	 */
	private static boolean sameType(Type[] types, Class<?>[] clazzes) {
		// 个数不同
		if (types.length != clazzes.length) {
			return false;
		}

		for (int i = 0; i < types.length; i++) {
			if (!Type.getType(clazzes[i]).equals(types[i])) {
				return false;
			}
		}
		return true;
	}
	
	/**
	 * 取得切面调用的方法
	 * @param pjp
	 * @return
	 */
	public static Method getMethod(ProceedingJoinPoint pjp){
		Signature sig = pjp.getSignature();
        if (!(sig instanceof MethodSignature)) {
            throw new IllegalArgumentException("该注解只能用于方法");
        }
        MethodSignature msig = (MethodSignature) sig;
        Object target = pjp.getTarget();
        Method currentMethod = null;
		try {
			currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
		} catch (NoSuchMethodException | SecurityException e) {
			LOGGER.warn(e.getMessage(), e);
		}       
        return currentMethod;
	}
	
	public static List<String> getMatcher(String regex, String source) {  
        List<String> list = new ArrayList<>();
        Pattern pattern = Pattern.compile(regex);  
        Matcher matcher = pattern.matcher(source);  
        while (matcher.find()) {  
            list.add(matcher.group());
        }  
        return list;  
    }
	
	/**
	 * 取得注解参数
		(?=exp)	匹配exp前面的位置
		(?<=exp)	匹配exp后面的位置
		(?!exp)	匹配后面跟的不是exp的位置
		(?<!exp)	匹配前面不是exp的位置
	 * @param managers
	 * @return
	 */
	public static List<String> getAnnoParams(String source){
		String regex = "(?<=\\{)(.+?)(?=\\})";
        return getMatcher(regex, source);
    }
	

}

 

 

package com.rd.ifaes.common.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import com.rd.ifaes.common.dict.ExpireTime;
/**
 * 添加缓存
 * @author lh
 *
 */
@Retention(RetentionPolicy.RUNTIME)  
@Target({ElementType.METHOD}) 
public @interface Cacheable {

	/**
	 * 缓存key
	 * @return
	 */
	public String key() default ""; 
	
	/**
	 * 缓存时效,默认无限期
	 * @return
	 */
	public ExpireTime expire() default ExpireTime.NONE; 

}

 

package com.rd.ifaes.common.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import com.rd.ifaes.common.dict.ExpireTime;
/**
 * 缓存清除
 * @author lh
 * @version 3.0
 * @since 2016-8-28
 *
 */
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface CacheEvict {

	/**
	 * 缓存key
	 * @return
	 */
	String key() default "";
	
	/**
	 * 缓存key数组
	 * @return
	 */
	String[] keys() default{};
	/**
	 * 操作之间的缓存时间(秒)
	 * @author  FangJun
	 * @date 2016年9月9日
	 * @return 默认0,不做限制
	 */
	ExpireTime interval() default ExpireTime.NONE;
	
}

 

package com.rd.ifaes.common.annotation;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.rd.ifaes.common.dict.ExpireTime;
import com.rd.ifaes.common.util.ReflectionUtils;
import com.rd.ifaes.common.util.StringUtils;
import com.rd.ifaes.core.core.constant.CacheConstant;
import com.rd.ifaes.core.core.constant.Constant;
import com.rd.ifaes.core.core.util.CacheUtils;
/**
 * 缓存操作切面
 * @author lh
 *
 */
@Aspect
@Component
public class CacheAspect {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(CacheAspect.class);
	
	@SuppressWarnings("rawtypes")
	@Autowired
	private RedisTemplate redisTemplate;
	
	/**
	 * 添加缓存
	 * @param pjp
	 * @param cache
	 * @return
	 * @throws Throwable
	 */
	@Around("@annotation(cache)")
	public Object cacheable(final ProceedingJoinPoint pjp, Cacheable cache)throws Throwable {

		String key = getCacheKey(pjp, cache.key());

		//使用redisTemplate操作缓存
		@SuppressWarnings("unchecked")
		ValueOperations<String, Object> valueOper = redisTemplate.opsForValue();
		Object value =  valueOper.get(key); // 从缓存获取数据
		if (value != null) {
			return value; // 如果有数据,则直接返回
		}
		
		value = pjp.proceed();
		if(LOGGER.isInfoEnabled()){
			LOGGER.info("cachePut, key={}", key);			
		}
		// 缓存,到后端查询数据
		if (cache.expire().getTime() <= 0) { // 如果没有设置过期时间,则无限期缓存
			valueOper.set(key, value);
		} else { // 否则设置缓存时间
			valueOper.set(key, value, cache.expire().getTime(), TimeUnit.SECONDS);
		}
		return value;
	}
	
	
	@Around("@annotation(evict)")
	public Object cacheEvict(final ProceedingJoinPoint pjp, CacheEvict evict)throws Throwable {
		Object value;
		// 执行方法
		value = pjp.proceed();
		
		//单个key操作
		if (StringUtils.isNotBlank(evict.key())) {
			String keyname = evict.key();
			evictByKeyname(pjp, keyname,evict.interval());
		}
		//批量key操作
		if (evict.keys() != null && evict.keys().length > 0) {
			for (String keyname : evict.keys()) {
				evictByKeyname(pjp, keyname,evict.interval());
			}
		}
		return value;
	}

	@SuppressWarnings("unchecked")
	private void evictByKeyname(final ProceedingJoinPoint pjp, final String keyname, ExpireTime interval) {
		final String key = getCacheKey(pjp, keyname);
		//操作间隔判断
		if (!ExpireTime.NONE.equals(interval)) {
			final String intervalKey = CacheConstant.KEY_PREFIX_CACHE_EVICT + key;
			if (CacheUtils.incr(intervalKey, Constant.DOUBLE_ONE) > Constant.DOUBLE_ONE) {
				return;
			}
			CacheUtils.expire(intervalKey, interval);
		}
		
		if(LOGGER.isInfoEnabled()){
			LOGGER.info("cacheEvict, key={}", key);			
		}
		
		//使用redisTemplate操作缓存
		if (keyname.equals(key)) {// 支持批量删除
			Set<String> keys = redisTemplate.keys(key.concat("*"));
			if (!CollectionUtils.isEmpty(keys)) {
				redisTemplate.delete(keys);
			}
		} else {
			redisTemplate.delete(key);
		}
	}

	/**
	 * 获取缓存的key值
	 * 
	 * @param pjp
	 * @param key
	 * @return
	 */
	private String getCacheKey(final ProceedingJoinPoint pjp, final String key) {

		StringBuilder buf = new StringBuilder();
		final Object[] args = pjp.getArgs();
		
		if(StringUtils.isNotBlank(key)){
			buf.append(key);
			List<String> annoParamNames = AopUtils.getAnnoParams(key);
			String[] methodParamNames = AopUtils.getMethodParamNames(AopUtils.getMethod(pjp));
			if(!CollectionUtils.isEmpty(annoParamNames)){
				for (String ap : annoParamNames) {
					buf = replaceParam(buf, args, methodParamNames, ap);
				}				
			}
			
		}else{
			buf.append(pjp.getSignature().getDeclaringTypeName()).append(":").append(pjp.getSignature().getName());
			for (Object arg : args) {
				buf.append(":").append(arg.toString());
			}
		}	

		return buf.toString();
	}

	/**
	 * 替换占位参数
	 * @param buf
	 * @param args
	 * @param methodParamNames
	 * @param ap
	 * @return
	 */
	private StringBuilder replaceParam(StringBuilder buf, final Object[] args, String[] methodParamNames, String ap) {
		StringBuilder builder = new StringBuilder(buf);
		String paramValue = "";
		for (int i = 0; i < methodParamNames.length; i++) {
			if(ap.startsWith(methodParamNames[i])){
				final Object arg = args[i];
				if (ap.contains(".")) {
					paramValue = String.valueOf(ReflectionUtils.invokeGetter(arg, ap.substring(ap.indexOf('.') + 1)));
				} else {
					paramValue = String.valueOf(arg);
				}
				break;
			}
		}
		int start = builder.indexOf("{" + ap);
		int end = start + ap.length() + 2;
		builder =builder.replace(start, end, paramValue);
		return builder;
	}
}

   spring相关配置如下:

 	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<property name="maxIdle" value="${redis.pool.maxIdle}" /> <!-- 最大能够保持idel状态的对象数  -->
		<property name="maxTotal" value="${redis.pool.maxTotal}" /> <!-- 最大分配的对象数 -->
		<property name="testOnBorrow" value="${redis.pool.testOnBorrow}" /> <!-- 当调用borrow Object方法时,是否进行有效性检查 -->
	</bean>
	 
 	<!-- sprin_data_redis 单机配置 -->
 	<bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" >
         <property name="hostName" value="${redis.host}" />
         <property name="port" value="${redis.port}" />
         <property name="timeout" value="${redis.timeout}" />
         <property name="password" value="${redis.password}" />
         <property name="poolConfig" ref="jedisPoolConfig" />
 	</bean>
 	<!-- key序列化 -->
	<bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" />
	 
	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
	 p:connectionFactory-ref="jedisConnFactory" p:keySerializer-ref="stringRedisSerializer" />
 	
	<!-- spring自己的缓存管理器 -->  
    <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">  
        <property name="caches">  
            <set>  
            	<bean class="com.rd.ifaes.common.jedis.RdRedisCache" p:redis-template-ref="redisTemplate" p:name="sysCache"/> 
            </set>  
        </property>  
    </bean>  
	
	<!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在spring主配置文件中才会生效 -->
	<cache:annotation-driven cache-manager="cacheManager" proxy-target-class="true" key-generator="rdKeyGenerator"/>
	<!-- 自定义主键生成策略 -->
	<bean id="rdKeyGenerator" class="com.rd.ifaes.common.jedis.RdKeyGenerator"/>

 

分享到:
评论

相关推荐

    spring简单的缓存

    Spring提供了一种基于事件的更新策略,或者可以使用缓存 provider 提供的监听机制来实现。 7. **分布式缓存**: 在多节点环境中,通常需要使用分布式缓存,如Redis,来保证缓存的一致性和高可用性。Spring Data ...

    Spring基于注解的缓存配置--web应用实例

    在本实例中,我们将深入探讨如何在Spring框架中利用注解来实现缓存配置,特别是在Web应用程序中的实际应用。Spring Cache是一个强大的功能,它允许我们高效地管理应用程序中的数据,减少不必要的数据库查询,提高...

    Spring 与Ehcache实现基于方法的缓存

    2. **配置Spring的缓存注解支持** 在Spring的配置文件中,启用缓存注解支持,并指定使用的缓存管理器。例如,使用`&lt;cache:annotation-driven&gt;`标签: ```xml &lt;beans xmlns="http://www.springframework.org/...

    基于Spring的Web缓存

    在实现Spring缓存时,你需要确保引入了相应的库,如`spring-boot-starter-cache`或`spring-context-support`,它们包含了Spring缓存支持所需的类和接口。同时,如果你打算使用特定的缓存实现,如EhCache或Redis,还...

    springboot1.x基于spring注解实现J2Cache两级缓存集成

    在本文中,我们将深入探讨如何在Spring Boot 1.x版本中使用Spring注解来实现J2Cache的两级缓存机制,其中包括一级缓存Ehcache和二级缓存Redis。通过这种方式,我们可以显著提高应用程序的性能,减少对数据库的依赖,...

    自定义注解实现缓存机制

    在Spring Boot应用中,自定义注解来实现缓存机制是一种常见的优化手段,尤其是在处理大量重复数据查询时,可以显著提升应用性能。本教程将详细解释如何利用Spring Boot结合Redis来实现这一功能。 首先,我们需要...

    Spring 缓存

    Spring 缓存机制的实现主要有两种方法:使用 Spring 与 Ehcache 结合,使用注解的方式对指定的方法进行缓存;封装 Guava 缓存,使用 Guava 包中的缓存机制。 方法一:使用 Spring 与 Ehcache 结合 使用 Spring 与 ...

    spring整合redis做缓存用注解实现的完整例子

    在本文中,我们将深入探讨如何使用Spring框架与Redis集成,以实现高效的缓存管理,并通过注解的方式简化这一过程。Redis是一种高性能的键值数据存储系统,常被用于缓存、消息队列等多种场景,而Spring框架则为Java...

    Spring基于注解的缓存配置--EHCache AND OSCache

    1. **Spring缓存抽象** Spring 3.1引入了一种统一的缓存抽象,它允许开发者在不关心具体缓存实现的情况下,轻松地在应用程序中引入缓存功能。这种抽象包括了注解、接口和配置元素,使得缓存的使用变得简单。 2. **...

    spring缓存实例

    首先,Spring缓存抽象是通过`@Cacheable`、`@CacheEvict`、`@Caching`和`@CacheConfig`等注解实现的,它们允许开发者在不修改业务代码的情况下,轻松地添加缓存功能。`@Cacheable`用于标记那些可以被缓存的方法,当...

    spring-data-redis基于注解的实现方式

    "spring-data-redis基于注解的实现方式"是这个话题的核心,它探讨了如何利用Spring Data Redis的注解功能来简化数据缓存的实现。下面将详细阐述这一主题,包括相关的技术和实践方法。 首先,我们需要理解Spring ...

    Spring基于注解整合Redis完整实例

    本实例完美的实现了Spring基于注解整合Redis,只需在相应方法上加上注解便可实现操作redis缓存的功能,具体实现方法与运行测试方法请参见博文:http://blog.csdn.net/l1028386804/article/details/52141372

    spring缓存机制-入门实例

    1. **Spring缓存注解**: - `@Cacheable`:标记在方法上,表示该方法的返回结果应被缓存。每次调用时,Spring会检查缓存中是否有该方法的结果,如果有,则直接返回,无需再次执行方法;如果没有,则执行方法并将...

    基于spring boot上的注解缓存,自带轻量级缓存管理页面.zip

    本项目主题是"基于Spring Boot上的注解缓存,自带轻量级缓存管理页面",这涉及到Spring Boot如何集成和管理缓存,以及如何通过注解来实现这一功能。在快应用开发中,缓存优化是提升系统性能、减少数据库负载的关键...

    spring缓存机制-自定义缓存(五, 六)

    Spring缓存抽象是基于Java的注解驱动的,它提供了声明式缓存管理。核心组件包括`@Cacheable`、`@CacheEvict`、`@CachePut`等注解,这些注解可以直接应用在方法上,指示Spring在适当的时候进行缓存操作。 1. `@...

    详解Spring缓存注解@Cacheable,@CachePut , @CacheEvict使用

    Spring 缓存注解 @Cacheable、@CachePut、@CacheEvict 使用详解 Spring 框架提供了三个缓存注解:@Cacheable、@CachePut 和 @CacheEvict,这三个注解可以帮助开发者简化缓存的使用,提高应用程序的性能。在本文中,...

    基于spring注解的SSH2框架集成

    在这个基于Spring注解的SSH2框架集成中,我们将深入探讨如何将这三个组件有效地整合,并利用Spring的注解驱动特性提升开发效率。 首先,Struts2是一个强大的MVC(Model-View-Controller)框架,它在Struts1的基础上...

    spring缓存机制-根据condition加入缓存(三)

    `@Cacheable`是Spring缓存中最常用的注解,用于标记一个方法,表示该方法的返回结果应该被缓存。它的基本用法如下: ```java @Cacheable(value = "myCache", key = "#id") public MyObject findById(String id) { ...

    (SSM框架)memcached整合Spring基于Cache注解.

    在SSM框架中引入Memcached并基于Spring的Cache注解进行整合,可以实现高效、分布式的数据缓存,提升系统性能。下面将详细阐述这一过程中的关键知识点。 1. **Memcached介绍**: Memcached是一款高性能、分布式的...

    spring注解方式实现aop

    在Spring中,AOP主要分为两种实现方式:基于XML配置和基于注解。本示例主要探讨注解方式。 1. **定义切面(Aspect)** 切面是关注点的模块化,它包含通知(Advice)和切入点(Pointcut)。在Spring中,我们可以...

Global site tag (gtag.js) - Google Analytics