Java开发框架spring实现自定义缓存标签

 更新时间:2015年12月14日 16:35:35   作者:txxs  
这篇文章主要介绍了Java开发框架spring实现自定义缓存标签的详细代码,感兴趣的小伙伴们可以参考一下
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud

(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

自从spring3.1之后,spring引入了抽象缓存,可以通过在方法上添加@Cacheable等标签对方法返回的数据进行缓存。但是它到底是怎么实现的呢,我们通过一个例子来看一下。首先我们定义一个@MyCacheable

package caching.springaop; 
 
import java.lang.annotation.Retention; 
import java.lang.annotation.RetentionPolicy; 
import java.lang.annotation.Target; 
import java.lang.annotation.ElementType; 
 
/** 
 * 使用@MyCacheable注解方法 
 */ 
@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.METHOD) 
public @interface MyCacheable{ 
 
} 

然后定义处理MyCacheable的切面

package caching.springaop; 
 
import java.util.HashMap; 
import java.util.Map; 
 
import org.apache.log4j.Logger; 
import org.aspectj.lang.ProceedingJoinPoint; 
import org.aspectj.lang.annotation.Around; 
import org.aspectj.lang.annotation.Aspect; 
import org.aspectj.lang.annotation.Pointcut; 
 
/** 
 * 处理MyCacheable方法的切面 
 */ 
@Aspect 
public class CacheAspect { 
 
  private Logger logger = Logger.getLogger(CacheAspect.class); 
  private Map<String, Object> cache; 
 
  public CacheAspect() { 
    cache = new HashMap<String, Object>(); 
  } 
 
  /** 
   * 所有标注了@Cacheable标签的方法切入点 
   */ 
  @Pointcut("execution(@MyCacheable * *.*(..))") 
  @SuppressWarnings("unused") 
  private void cache() { 
  } 
 
  @Around("cache()") 
  public Object aroundCachedMethods(ProceedingJoinPoint thisJoinPoint) 
      throws Throwable { 
    logger.debug("Execution of Cacheable method catched"); 
    //产生缓存数据的key值,像是这个样子caching.aspectj.Calculator.sum(Integer=1;Integer=2;) 
    StringBuilder keyBuff = new StringBuilder(); 
    //增加类的名字 
    keyBuff.append(thisJoinPoint.getTarget().getClass().getName()); 
    //加上方法的名字 
    keyBuff.append(".").append(thisJoinPoint.getSignature().getName()); 
    keyBuff.append("("); 
    //循环出cacheable方法的参数 
    for (final Object arg : thisJoinPoint.getArgs()) { 
      //增加参数的类型和值 
      keyBuff.append(arg.getClass().getSimpleName() + "=" + arg + ";"); 
    } 
    keyBuff.append(")"); 
    String key = keyBuff.toString(); 
    logger.debug("Key = " + key); 
    Object result = cache.get(key); 
    if (result == null) { 
      logger.debug("Result not yet cached. Must be calculated..."); 
      result = thisJoinPoint.proceed(); 
      logger.info("Storing calculated value '" + result + "' to cache"); 
      cache.put(key, result); 
    } else { 
      logger.debug("Result '" + result + "' was found in cache"); 
     
    return result; 
  } 
 
} 

上述代码展示了如何处理MyCacheable自定义的标签,以及默认情况下产生key值的规则。最后生成的key值大概是这个样子:caching.aspectj.Calculator.sum(Integer=1;Integer=2;)
下边这段代码在方法上添加了MyCacheable标签

package caching.springaop; 
 
import org.apache.log4j.Logger; 
public class Calculator { 
  private Logger logger = Logger.getLogger(Calculator.class); 
  @MyCacheable 
  public int sum(int a, int b) { 
    logger.info("Calculating " + a + " + " + b); 
    try { 
      //假设这是代价非常高的计算 
      Thread.sleep(3000); 
    } catch (InterruptedException e) { 
      logger.error("Something went wrong...", e); 
    } 
    return a + b; 
  } 
} 

在方法上加了MyCacheable标签,当key值相同的情况下会直接在缓存中获取数据,如果没有相同的key值,则会重新计算,因为这里只是一个加和操作,耗时非常的短暂。我们在这里让其睡眠3秒钟。
我们在spring-config.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns:aop="http://www.springframework.org/schema/aop" 
  xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> 
  <aop:aspectj-autoproxy /> 
  <bean class="caching.springaop.CacheAspect" /> 
  <bean id="calc" class="caching.springaop.Calculator" /> 
</beans> 

测试类:

package caching.springaop; 
 
import org.apache.log4j.Logger; 
import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.ClassPathXmlApplicationContext; 
 
/** 
 * 使用SpringAOP缓存的简单例子 
 * @author txxs 
 */ 
public class App { 
 
  private static Logger logger = Logger.getLogger(App.class); 
 
  public static void main(String[] args) { 
    logger.debug("Starting..."); 
    ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml"); 
    Calculator calc = (Calculator) ctx.getBean("calc"); 
    //计算出来的结果将会被存储在cache 
    logger.info("1 + 2 = " + calc.sum(1, 2)); 
    //从缓存中获取结果 
    logger.info("1 + 2 = " + calc.sum(1, 2)); 
    logger.debug("Finished!"); 
  } 
 
} 

我们看一下运行的结果:

从结果来看第一次直接计算结果,第二次从缓存中获取。

以上就是spring实现自定义缓存标签的全部内容,希望对大家的学习有所帮助

相关文章

  • Java中回调函数?(callback)?及其实际应用场景

    Java中回调函数?(callback)?及其实际应用场景

    在Java中回调函数(Callback)是一种常见的设计模式,用于实现异步操作或事件处理,这篇文章主要给大家介绍了关于Java中回调函数?(callback)?及其实际应用场景的相关资料,需要的朋友可以参考下
    2024-02-02
  • 详解Spring Boot 项目部署到heroku爬坑

    详解Spring Boot 项目部署到heroku爬坑

    这篇文章主要介绍了详解Spring Boot 项目部署到heroku爬坑,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-08-08
  • Java中的 FilterInputStream简介_动力节点Java学院整理

    Java中的 FilterInputStream简介_动力节点Java学院整理

    FilterInputStream 的作用是用来“封装其它的输入流,并为它们提供额外的功能”。接下来通过本文给大家分享Java中的 FilterInputStream简介,感兴趣的朋友一起学习吧
    2017-05-05
  • JavaEE开发之SpringMVC中的自定义消息转换器与文件上传

    JavaEE开发之SpringMVC中的自定义消息转换器与文件上传

    本篇文章主要介绍了SpringMVC的相关知识。同时也会介绍到js、css这些静态文件的加载配置,以及服务器推送的两种实现方式并且给出了两者的区别。下面跟着小编一起来看下吧
    2017-04-04
  • Java 实战项目之在线点餐系统的实现流程

    Java 实战项目之在线点餐系统的实现流程

    读万卷书不如行万里路,只学书上的理论是远远不够的,只有在实战中才能获得能力的提升,本篇文章手把手带你用java+SSM+jsp+mysql+maven实现一个在线点餐系统,大家可以在过程中查缺补漏,提升水平
    2021-11-11
  • java Future 接口使用方法详解

    java Future 接口使用方法详解

    这篇文章主要介绍了java Future 接口使用方法详解,Future接口是Java线程Future模式的实现,可以来进行异步计算的相关资料,需要的朋友可以参考下
    2017-03-03
  • Hadoop之NameNode Federation图文详解

    Hadoop之NameNode Federation图文详解

    今天小编就为大家分享一篇关于Hadoop之NameNode Federation图文详解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-01-01
  • 简单了解Spring Boot及idea整合jsp过程解析

    简单了解Spring Boot及idea整合jsp过程解析

    这篇文章主要介绍了简单了解Spring Boot及idea整合jsp过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • Spring boot如何通过@Scheduled实现定时任务及多线程配置

    Spring boot如何通过@Scheduled实现定时任务及多线程配置

    这篇文章主要介绍了Spring boot如何通过@Scheduled实现定时任务及多线程配置,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-12-12
  • Spring4.0 MVC请求json数据报406错误的解决方法

    Spring4.0 MVC请求json数据报406错误的解决方法

    这篇文章主要为大家详细介绍了Spring4.0 MVC请求json数据报406错误的解决方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-01-01

最新评论


http://www.vxiaotou.com