java使用redis缓存可以使用jedis框架,jedis操作简单,没有什么复杂的东西需要学习,网上资料很多,随便看看就会了.

将spring与redis缓存集成,其实也是使用jedis框架,只不过spring对它进行了一层封装,并将这层封装库命名为spring-data-redis.

下面将要使用spring-data-redis与jedis的jar包,并通过spring的aop功能,将redis缓存无缝无侵入的整合进来.

1.先下载好依赖包

[html] view
plain
 copy

  1. <dependency>
  2. <groupId>org.springframework</groupId>
  3. <artifactId>spring-core</artifactId>
  4. <version>4.1.1.RELEASE</version>
  5. </dependency>
  6. <!-- 还有spring的其它包,这里不一一贴出-->
[html] view
plain
 copy

  1. <dependency>
  2. <groupId>org.springframework.data</groupId>
  3. <artifactId>spring-data-redis</artifactId>
  4. <version>1.4.1.RELEASE</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>redis.clients</groupId>
  8. <artifactId>jedis</artifactId>
  9. <version>2.6.0</version>
  10. </dependency>

2.再配置spring文件

[html] view
plain
 copy

  1. <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
  2. <property name="minIdle" value="${redis.minIdle}" />
  3. <property name="maxIdle" value="${redis.maxIdle}" />
  4. <property name="maxTotal" value="${redis.maxActive}" />
  5. <property name="maxWaitMillis" value="${redis.maxWait}" />
  6. <property name="testOnBorrow" value="${redis.testOnBorrow}" />
  7. </bean>
  8. <bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
  9. <property name="hostName" value="${redis.host}" />
  10. <property name="port" value="${redis.port}" />
  11. <property name="password" value="${redis.password}" />
  12. <property name="usePool" value="true" />
  13. <property name="poolConfig" ref="poolConfig" />
  14. </bean>
  15. <!-- redis template definition -->
  16. <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
  17. <property name="connectionFactory" ref="jedisConnFactory" />
  18. <property name="keySerializer">
  19. <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
  20. </property>
  21. <property name="valueSerializer">
  22. <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
  23. </property>
  24. <property name="hashKeySerializer">
  25. <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
  26. </property>
  27. <property name="hashValueSerializer">
  28. <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
  29. </property>
  30. </bean>

3.开始编写aop代码

3.1 声明两个注解类,用于定义哪些方法将使用缓存

[java] view
plain
 copy

  1. @Retention(RetentionPolicy.RUNTIME)
  2. @Target({ElementType.METHOD})
  3. public @interface Cacheable {
  4. public enum KeyMode{
  5. DEFAULT,    //只有加了@CacheKey的参数,才加入key后缀中
  6. BASIC,      //只有基本类型参数,才加入key后缀中,如:String,Integer,Long,Short,Boolean
  7. ALL;        //所有参数都加入key后缀
  8. }
  9. public String key() default "";     //缓存key
  10. public KeyMode keyMode() default KeyMode.DEFAULT;       //key的后缀模式
  11. public int expire() default 0;      //缓存多少秒,默认无限期
  12. }
[java] view
plain
 copy

  1. @Retention(RetentionPolicy.RUNTIME)
  2. @Target({ElementType.PARAMETER})
  3. public @interface CacheKey {}

3.2 创建一个Aop拦截器的处理类,用于拦截加了@Cacheable的方法

[java] view
plain
 copy

  1. @Aspect
  2. @Component
  3. public class CacheableAop {
  4. @Autowired private RedisTemplate redisTemplate;
  5. @Around("@annotation(cache)")
  6. public Object cached(final ProceedingJoinPoint pjp,Cacheable cache) throws Throwable {
  7. String key=getCacheKey(pjp, cache);
  8. ValueOperations<String, Object> valueOper=redisTemplate.opsForValue();
  9. Object value=valueOper.get(key);    //从缓存获取数据
  10. if(value!=null) return value;       //如果有数据,则直接返回
  11. value = pjp.proceed();      //跳过缓存,到后端查询数据
  12. if(cache.expire()<=0) {      //如果没有设置过期时间,则无限期缓存
  13. valueOper.set(key, value);
  14. } else {                    //否则设置缓存时间
  15. valueOper.set(key, value,cache.expire(),TimeUnit.SECONDS);
  16. }
  17. return value;
  18. }
  19. /**
  20. * 获取缓存的key值
  21. * @param pjp
  22. * @param cache
  23. * @return
  24. */
  25. private String getCacheKey(ProceedingJoinPoint pjp,Cacheable cache) {
  26. StringBuilder buf=new StringBuilder();
  27. buf.append(pjp.getSignature().getDeclaringTypeName()).append(".").append(pjp.getSignature().getName());
  28. if(cache.key().length()>0) {
  29. buf.append(".").append(cache.key());
  30. }
  31. Object[] args=pjp.getArgs();
  32. if(cache.keyMode()==KeyMode.DEFAULT) {
  33. Annotation[][] pas=((MethodSignature)pjp.getSignature()).getMethod().getParameterAnnotations();
  34. for(int i=0;i<pas.length;i++) {
  35. for(Annotation an:pas[i]) {
  36. if(an instanceof CacheKey) {
  37. buf.append(".").append(args[i].toString());
  38. break;
  39. }
  40. }
  41. }
  42. } else if(cache.keyMode()==KeyMode.BASIC) {
  43. for(Object arg:args) {
  44. if(arg instanceof String) {
  45. buf.append(".").append(arg);
  46. } else if(arg instanceof Integer || arg instanceof Long || arg instanceof Short) {
  47. buf.append(".").append(arg.toString());
  48. } else if(arg instanceof Boolean) {
  49. buf.append(".").append(arg.toString());
  50. }
  51. }
  52. } else if(cache.keyMode()==KeyMode.ALL) {
  53. for(Object arg:args) {
  54. buf.append(".").append(arg.toString());
  55. }
  56. }
  57. return buf.toString();
  58. }
  59. }

4.使用缓存示例

[java] view
plain
 copy

  1. @Service
  2. @Transactional
  3. public class DemoServiceImpl implements DemoService {
  4. @Autowired private DemoDao demoDao;
  5. public List<Demo> findAll() {
  6. return demoDao.findAll();
  7. }
  8. /*
  9. 对get()方法配置使用缓存,缓存有效期为3600秒,缓存的key格式为:{package_name}.DemoServiceImpl.get
  10. 同时为参数配置了@CacheKey后,表示此参数的值将做为key的后缀,此例的key,最终是:{package_name}.DemoServiceImpl.get.{id}
  11. 可以为多个参数配置@CacheKey,拦截器会调用参数的toString()做为key的后缀
  12. 若配置多个@CacheKey参数,那么最终的key格式为:{package_name}.{class_name}.{method}.{arg1}.{arg2}.{...}
  13. */
  14. @Cacheable(expire=3600)
  15. public Demo get(@CacheKey String id) {
  16. return demoDao.get(id);
  17. }
  18. public Demo getByName(String name) {
  19. return demoDao.getByName(name);
  20. }
  21. }
  • 若为名称相同的方法配置缓存,可以在@Cacheable中加入key属性,追加额外的key后缀
  • @Cacheable还有一个KeyMode属性,用于配置哪些参数可以追加到key后缀中,

    默认取值 DEFAULT:表示只有加了@CacheKey的参数才能追加到key后缀

    BASIC:自动将基本类型追加到key后缀,而无需再配置@CacheKey

    ALL:自动将所有参数追加到lkey后缀,而无需再配置@CacheKey

这只是一个初步整合方案,测试可行,还未在生产中使用,实际效果待验正.

最新文章

  1. 自己用js实现全屏滚动
  2. 00 LabVIEW中类的动态类型处理
  3. word-wrap: break-word; break-word: break-all;区别
  4. CSS3入门之文本与字体
  5. 163源报错Hash Sum mismatch 解决方法
  6. VirtualBox不能为虚拟电脑 Ubuntu 打开一个新任务
  7. QPushButton 与 QListWidget 的按键响应
  8. [有错误]堆排序的实现 java
  9. Azure VM Public IP设置
  10. 什么是WEBserver? 经常使用的WEBserver有哪些?
  11. Python:游戏:300行代码实现俄罗斯方块
  12. MyBatis 作用域(Scope)和生命周期
  13. linux中结构体对齐【转】
  14. MySql 存储过程 光标只循环一次
  15. transaction注解分析
  16. 再读c++primer plus 003
  17. 51nod 1021 石子归并
  18. OO第一次总结作业
  19. CentOS6安装各种大数据软件 第八章:Hive安装和配置
  20. SpringBoot下的值注入

热门文章

  1. jQuery Mobile基础
  2. CreateEvent,OpenEvent成功后 是否需要::CloseHandle(xxx); 避免句柄泄漏
  3. BZOJ 1559: [JSOI2009]密码( AC自动机 + 状压dp )
  4. MySql学习之varchar类型
  5. codinglife主题小修改和有意思的博客挂件
  6. 在实体对象中访问导航属性里的属性值出现异常“There is already an open DataReader associated with this Command which must be closed first”
  7. react-native 入门资源合集
  8. ie6兼容性,还需要测试么?迷茫。。。
  9. 深入解读JavaScript面向对象编程实践
  10. SqlCacheDependency的使用