Spring 4 Ehcache Configuration Example with @Cacheable Annotation

http://www.concretepage.com/spring-4/spring-4-ehcache-configuration-example-with-cacheable-annotation

Spring 4 Ehcache Configuration Example with @Cacheable Annotation

By Arvind Rai, March 16, 2015

In this page, we will learn Spring 4 Ehcache configuration example with @Cacheable annotation. Ehcache manages cache for boosting performance. Spring provides @Cacheable annotation that uses cache name defined in Ehcache xml file. Spring provides EhCacheManagerFactoryBean and EhCacheCacheManager classes to configure and instantiate Ehcache. The configuration class must be annotated with @EnableCaching annotation which enables annotation driven cache management. Here we will provide a complete example for Spring Ehcache Configuration.

build.gradle

Find the Gradle file to resolve JAR dependency for Spring and Ehcache. 
build.gradle

apply plugin: ‘java‘
apply plugin: ‘eclipse‘
archivesBaseName = ‘concretepage‘
version = ‘1‘
repositories {
        mavenCentral()
}
dependencies {
	compile ‘org.springframework.boot:spring-boot-starter:1.2.2.RELEASE‘
	compile ‘org.springframework:spring-context-support:4.1.5.RELEASE‘
	compile ‘net.sf.ehcache:ehcache-core:2.6.10‘
}

Project Structure in Eclipse

Find the project structure in eclipse that will help to learn fast.

Configuration Class for EhCacheManagerFactoryBean and EhCacheCacheManager

The configuration class will be annotated with @EnableCaching annotation and we need to create bean for EhCacheManagerFactoryBean and EhCacheCacheManager class.

@EnableCaching: It enables annotation driven cache management in spring and is same as using<cache:annotation-driven />
EhCacheManagerFactoryBean: Assign ehcache XML file by calling EhCacheManagerFactoryBean.setConfigLocation(). By passing true to setShared() method, we enable our cache to be shared as singleton at the ClassLoader level. By default it is set to false. 
EhCacheCacheManager: This is a CacheManager backed by an EhCache. We can instantiate it by passing argument of EhCacheManagerFactoryBean.getObject().

Find the Configuration file. 
AppConfig.java

package com.concretepage;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
@Configurable
@EnableCaching
public class AppConfig {
	@Bean
	public Employee getEmployee(){
	        return  new Employee();
	}
	@Bean
	public CacheManager getEhCacheManager(){
	        return  new EhCacheCacheManager(getEhCacheFactory().getObject());
	}
	@Bean
	public EhCacheManagerFactoryBean getEhCacheFactory(){
		EhCacheManagerFactoryBean factoryBean = new EhCacheManagerFactoryBean();
		factoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
		factoryBean.setShared(true);
		return factoryBean;
	}
}

The equivalent ehcache configuration in spring xml is given below.

<cache:annotation-driven />
<bean id="employee" class="com.concretepage.Employee"/>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
                p:cache-manager-ref="ehcache"/>
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
                p:config-location="classpath:ehcache.xml" p:shared="true"/>

ehcache.xml

Find the sample ehcache.xml file. We have created a cache with the name empcache that will be used by spring @Cacheable annotation. Here maximum 5000 elements will be cached in memory and after that it will overflow to local disk. Any element will expire if it is idle for more than 200 seconds and alive for more than 500 seconds. 
ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:noNamespaceSchemaLocation="ehcache.xsd"
     updateCheck="true" monitoring="autodetect" dynamicConfig="true">
    <cache name="empcache"
      maxEntriesLocalHeap="5000"
      maxEntriesLocalDisk="1000"
      eternal="false"
      diskSpoolBufferSizeMB="20"
      timeToIdleSeconds="200"
      timeToLiveSeconds="500"
      memoryStoreEvictionPolicy="LFU"
      transactionalMode="off">
        <persistence strategy="localTempSwap"/>
    </cache>
  </ehcache>

Using @Cacheable on Bean Method

If we annotate our bean method by Spring @Cacheable annotation, it declares that it will be cached. We need to provide cache name defined in ehcache.xml. In our example we have a cache named as empcache in ehcache.xml and we have provided this name in @Cacheable. Spring will hit the method for the first time. The result of this method will be cached and for same argument value, spring will not hit the method every time. Once the cache is expired, then the spring will hit the method again for the same argument value. 
Employee.java

package com.concretepage;
import org.springframework.cache.annotation.Cacheable;
public class Employee {
	@Cacheable("empcache")
	public String getEmployee(int empId){
		System.out.println("---Inside getEmployee() Method---");
		if(empId==1){
			return "Shankar";
		}else{
			return "Vishnu";
		}
	}
}

Test Spring Ehcache Application

Now we create a main method to test the application. Here if we call the method passing a value as an argument for the first time, spring will hit the method. And for next hit, if we pass the same argument value, we will get result from cache not by running method. 
SpringDemo.java

package com.concretepage;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringDemo {
    public static void main(String... args) {
    	 AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
  	 ctx.register(AppConfig.class);
  	 ctx.refresh();
         Employee employee=(Employee) ctx.getBean(Employee.class);

         //calling getEmployee method first time.
         System.out.println("---Fetch Employee with id 1---");
         System.out.println("Employee:"+ employee.getEmployee(1));

         //calling getEmployee method second time. This time, method will not execute.
         System.out.println("---Again Fetch Employee with id 1, result will be fetched from cache---");
         System.out.println("Employee:"+employee.getEmployee(1));

         //calling getEmployee method third time with different value.
         System.out.println("---Fetch Employee with id 2---");
          System.out.println("Employee:"+employee.getEmployee(2));
     }
}

Find the output.

17:06:49.301 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean ‘getEmployee‘
---Fetch Employee with id 1---
---Inside getEmployee() Method---
17:06:49.323 [main] DEBUG net.sf.ehcache.store.disk.Segment - put added 0 on heap
Employee:Shankar
---Again Fetch Employee with id 1, result will be fetched from cache---
Employee:Shankar
---Fetch Employee with id 2---
---Inside getEmployee() Method---
17:06:49.327 [main] DEBUG net.sf.ehcache.store.disk.Segment - put added 0 on heap
Employee:Vishnu
17:06:49.332 [empcache.data] DEBUG net.sf.ehcache.store.disk.Segment - fault removed 0 from heap
17:06:49.332 [empcache.data] DEBUG net.sf.ehcache.store.disk.Segment - fault added 0 on disk 
时间: 2024-10-11 10:46:52

Spring 4 Ehcache Configuration Example with @Cacheable Annotation的相关文章

Spring整合Ehcache管理缓存

Ehcache 是一个成熟的缓存框架,你可以直接使用它来管理你的缓存. Spring 提供了对缓存功能的抽象:即允许绑定不同的缓存解决方案(如Ehcache),但本身不直接提供缓存功能的实现.它支持注解方式使用缓存,非常方便.本文先通过Ehcache独立应用的范例来介绍它的基本使用方法,然后再介绍与Spring整合的方法. 概述 Ehcache是什么?EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点.它是Hibernate中的默认缓存框架.Ehcache已经发布了3.1版本

缓存插件 Spring支持EHCache缓存

Spring仅仅是提供了对缓存的支持,但它并没有任何的缓存功能的实现,spring使用的是第三方的缓存框架来实现缓存的功能.其中,spring对EHCache提供了很好的支持. 在介绍Spring的缓存配置之前,我们先看一下EHCache是如何配置. <?xml version="1.0" encoding="UTF-8" ?> <ehcache> <!-- 定义默认的缓存区,如果在未指定缓存区时,默认使用该缓存区 --> <

以Spring整合EhCache为例从根本上了解Spring缓存这件事(转)

前两节"Spring缓存抽象"和"基于注解驱动的缓存"是为了更加清晰的了解Spring缓存机制,整合任何一个缓存实现或者叫缓存供应商都应该了解并清楚前两节,如果只是为了快速的应用EhCache到Spring项目中,请直接前往第三节"Spring整合EhCache缓存". 一.   Spring缓存抽象 1.       注意和核心思想 Spring自身并没有实现缓存解决方案,但是对缓存管理功能提供了声明式的支持,能够与多种流行的缓存实现进行集成.

Spring AOP +EHcache为Service层方法增加缓存

在铁科院做了一个关于医保报销的项目,在这个个系统中大量使用了下拉列表框,系统主要是给机关单位使用而且都是一些干部退休了啥的,年龄都比较大不愿意自己输入东西,因此界面上的很多值都是下拉列表框从数据字典表里面加载出来. 如此以来字典表的数据量变的越来越大,在一个界面上往往需要频繁的与字典表交互,觉的很影响性能于是我们增加了缓存,即为service层中的指定方法缓存功能,具体实现是利用Spring AOP+EHcache来做. 第一次执行某个方法的时候会去数据库里面查询,当第二次执行该方法时就会去从缓

spring+shiro+ehcache整合

1.导入jar包(pom.xml文件) <!-- ehcache缓存框架 --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>2.6.11</version> </dependency> Spring 整合 ehcache 包 spring-context-

我被面试官给虐懵了,竟然是因为我不懂Spring中的@Configuration

现在大部分的Spring项目都采用了基于注解的配置,采用了@Configuration 替换标签的做法.一行简单的注解就可以解决很多事情.但是,其实每一个注解背后都有很多值得学习和思考的内容.这些思考的点也是很多大厂面试官喜欢问的内容. 在一次关于Spring注解的面试中,可能会经历面试官的一段夺命连环问: @Configuration有什么用?br/>@Configuration和XML有什么区别?哪种好?Spring是如何基于来获取Bean的定义的?@Autowired . @Inject.

Spring搭配Ehcache实例解析

转载请注明出处:http://blog.csdn.net/dongdong9223/article/details/50538085 1 Ehcache简介 EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点,是Hibernate中默认的CacheProvider. Ehcache是一种广泛使用的开源Java分布式缓存.主要面向通用缓存,Java EE和轻量级容器.它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST

转Spring+Hibernate+EHcache配置(二)

Spring AOP+EHCache简单缓存系统解决方案 需要使用Spring来实现一个Cache简单的解决方案,具体需求如下:使用任意一个现有开源Cache Framework,要求可以Cache系统中Service或则DAO层的get/find等方法返回结果,如果数据更新(使用Create/update/delete方法),则刷新cache中相应的内容. MethodCacheInterceptor.java Java代码 package com.co.cache.ehcache;     

Spring MVC xml configuration

1. Web.xml id="WebApp_ID" version="3.0"> <display-name>springMvcDemo</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name