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
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
Spring 4 Ehcache Configuration Example with @Cacheable Annotation的更多相关文章
- Spring整合EHCache框架
在Spring中使用缓存可以有效地避免不断地获取相同数据,重复地访问数据库,导致程序性能恶化. 在Spring中已经定义了缓存的CacheManager和Cache接口,只需要实例化便可使用. Spr ...
- Spring整合Ehcache管理缓存
前言 Ehcache 是一个成熟的缓存框架,你可以直接使用它来管理你的缓存. Spring 提供了对缓存功能的抽象:即允许绑定不同的缓存解决方案(如Ehcache),但本身不直接提供缓存功能的实现.它 ...
- Spring整合Ehcache管理缓存(转)
目录 前言 概述 安装 Ehcache的使用 HelloWorld范例 Ehcache基本操作 创建CacheManager 添加缓存 删除缓存 实现基本缓存操作 缓存配置 xml方式 API方式 S ...
- 缓存插件 Spring支持EHCache缓存
Spring仅仅是提供了对缓存的支持,但它并没有任何的缓存功能的实现,spring使用的是第三方的缓存框架来实现缓存的功能.其中,spring对EHCache提供了很好的支持. 在介绍Spring的缓 ...
- Spring整合EhCache详解
一.EhCache介绍 EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点,是Hibernate中默认的CacheProvider.Ehcache是一种广泛使用的开 源Java分布 ...
- 以Spring整合EhCache为例从根本上了解Spring缓存这件事(转)
前两节"Spring缓存抽象"和"基于注解驱动的缓存"是为了更加清晰的了解Spring缓存机制,整合任何一个缓存实现或者叫缓存供应商都应该了解并清楚前两节,如果 ...
- spring中ehcache的配置和使用方法
继续上篇,这篇介绍服务层缓存,ehcache一般的配置和用法 一.添加jar包引用 修改pom.xml文件,加入: <dependency> <groupId>org.spri ...
- spring+shiro+ehcache整合
1.导入jar包(pom.xml文件) <!-- ehcache缓存框架 --> <dependency> <groupId>net.sf.ehcache</ ...
- Unit Testing of Spring MVC Controllers: Configuration
Original Link: http://www.petrikainulainen.net/programming/spring-framework/unit-testing-of-spring-m ...
随机推荐
- Ildasm.exe(MSIL 反汇编程序)
MSIL 反汇编程序是 MSIL 汇编程序 (Ilasm.exe) 的伙伴工具. Ildasm.exe 采用包含 Microsoft 中间语言 (MSIL) 代码的可迁移可执行 (PE) 文件,并创建 ...
- HDU 5603 the soldier of love 离线+树状数组
这是bestcorder 67 div1 的1003 当时不会做 看了赛后官方题解,然后翻译了一下就过了,而且速度很快,膜拜官方题解.. 附上官方题解: the soldier of love 我们注 ...
- ZOJ 3469 Food Delivery 区间DP
这道题我不会,看了网上的题解才会的,涨了姿势,现阶段还是感觉区间DP比较难,主要是太弱...QAQ 思路中其实有贪心的意思,n个住户加一个商店,分布在一维直线上,应该是从商店开始,先向两边距离近的送, ...
- 《Oracle Database 12c DBA指南》第二章 - 安装Oracle和创建数据库(2.1 安装Oracle数据库软件和创建数据库概览)
当前关于12c的中文资料比较少,本人将关于DBA的一部分官方文档翻译为中文,很多地方为了帮助中国网友看懂文章,没有按照原文句式翻译,翻译不足之处难免,望多多指正. 2.1 安装Oracle数据库软件和 ...
- js 中&& 与 ||
/*** 几乎所有语言中||和&&都遵循“短路”原理,* 如&&中第一个表达式为假就不会去处理第二个表达式,而||正好相反.* js也遵循上述原则.* 当||时,找到为 ...
- bzoj 1834 [ZJOI2010]network 网络扩容(MCMF)
[题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=1834 [题意] 给定一个有向图,每条边有容量C,扩容费用W,问最大流和使容量增加K的最 ...
- 欢迎来到Googny的博客
本博客主要分享笔者的学习知识,以及工程中遇到的技术问题. 由于笔者技术水平有限,博客不足之处在所难免,还请各位网友不吝交流,共同进步. 一起体会分享的乐趣. JavaScript 部分 该部分深入浅出 ...
- Java内存管理原理及内存区域详解
一.概述 Java虚拟机在执行Java程序的过程中会把它所管理的内存划分为若干不同的数据区域,这些区域都有各自的用途以及创建和销毁的时间.Java虚拟机所管理的内存将会包括以下几个运行时数据区域,如下 ...
- OpenCV2.4.6与vs2008配置问题
刚刚学习Opencv,发现配置的时候蛮复杂的,特此记下以备后续. 我的opencv安装在D:\OpenCV\opencv 1.设置环境变量 首先说一下环境配置,看到很多网上说的是根据系统的位数来判断, ...
- hdoj 5194 DZY Loves Balls【规律&&gcd】
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5194 题意:给你n个黑球,m个白球,每次从中随机抽取一个,如果抽到黑球记为1如果抽出来白球记为0,让你 ...