|
java使用redis缓存可以使用jedis框架,jedis操作简单,没有什么复杂的东西需要学习,网上资料很多,随便看看就会了.
将spring与redis缓存集成,其实也是使用jedis框架,只不过spring对它进行了一层封装,并将这层封装库命名为spring-data-redis.
下面将要使用spring-data-redis与jedis的jar包,并通过spring的aop功能,将redis缓存无缝无侵入的整合进来.
1.先下载好依赖包
[html] view plaincopy 
-
- org.springframework
- spring-core
- 4.1.1.RELEASE
-
-
[html] view plaincopy 
-
- org.springframework.data
- spring-data-redis
- 1.4.1.RELEASE
-
-
- redis.clients
- jedis
- 2.6.0
-
2.再配置spring文件
[html] view plaincopy 
3.开始编写aop代码
3.1 声明两个注解类,用于定义哪些方法将使用缓存
[java] view plaincopy 
- @Retention(RetentionPolicy.RUNTIME)
- @Target({ElementType.METHOD})
- public @interface Cacheable {
- public enum KeyMode{
- DEFAULT, //只有加了@CacheKey的参数,才加入key后缀中
- BASIC, //只有基本类型参数,才加入key后缀中,如:String,Integer,Long,Short,Boolean
- ALL; //所有参数都加入key后缀
- }
- public String key() default ""; //缓存key
- public KeyMode keyMode() default KeyMode.DEFAULT; //key的后缀模式
- public int expire() default 0; //缓存多少秒,默认无限期
- }
[java] view plaincopy 
- @Retention(RetentionPolicy.RUNTIME)
- @Target({ElementType.PARAMETER})
- public @interface CacheKey {}
3.2 创建一个Aop拦截器的处理类,用于拦截加了@Cacheable的方法
[java] view plaincopy 
- @Aspect
- @Component
- public class CacheableAop {
- @Autowired private RedisTemplate redisTemplate;
- @Around("@annotation(cache)")
- public Object cached(final ProceedingJoinPoint pjp,Cacheable cache) throws Throwable {
- String key=getCacheKey(pjp, cache);
- ValueOperations valueOper=redisTemplate.opsForValue();
- Object value=valueOper.get(key); //从缓存获取数据
- if(value!=null) return value; //如果有数据,则直接返回
- value = pjp.proceed(); //跳过缓存,到后端查询数据
- if(cache.expire()0) {
- buf.append(".").append(cache.key());
- }
- Object[] args=pjp.getArgs();
- if(cache.keyMode()==KeyMode.DEFAULT) {
- Annotation[][] pas=((MethodSignature)pjp.getSignature()).getMethod().getParameterAnnotations();
- for(int i=0;i
|
|
|