一、简介

  在hibernate中就是用到了ehcache 充当缓存。spring对ehcache也提供了支持,使用也比较简单,只需在spring的配置文件中将ehcache的ehcache.xml文件配置进去即可。在spring中使用ehcache有两种方式,一种是使用spring提供的封装,使用注解的方式配置在某个方法上面,第一次调用该方法的时候,将该方法执行返回的数据缓存,当再次执行的时候如果时间没有变,就直接冲缓存获取,该方法不执行;另一种方式是获取到ehcache本地接口,直接使用ehcache本地接口进行数据缓存。第一种的方式使用简单,代码简洁,但灵活度不高,而第二种方式灵活度高,但是代码就比较到,需要自己去判断数据是否缓存,如何没有缓存就去获取上海并本放入缓;如果缓存了,就直接去缓存中获取。本例子是用的是第一种方式。

  工程使用maven构建,需要的依赖如下:

        <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>3.2.6.RELEASE</version>
</dependency>

二、示例代码

  ehcache.xml代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false"> <!-- 默认缓存配置 ,缓存名称为 default -->
<defaultCache maxElementsInMemory="50" eternal="false"
overflowToDisk="false" memoryStoreEvictionPolicy="LFU" />
<!-- 自定义缓存,名称为lt.ehcache -->
<cache name="lt.ecache" maxElementsInMemory="50" eternal="false"
overflowToDisk="false" memoryStoreEvictionPolicy="LFU" />
</ehcache>

  Spring-config-ehcache.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:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <cache:annotation-driven />
<context:component-scan base-package="com.ehcache.test" /> <!-- 注解扫描路径 --> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehcache" />
</bean> <bean id="ehcache"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml" />
</bean> </beans>

  ehcache.xml与Spring-config-ehcache.xml存放在系统目录下。

  相关代码如下:

  实体Employee.java

 package com.ehcache.test;

 import java.io.Serializable;

 public class Employee implements Serializable {
private static final long serialVersionUID = -6534180255882276966L;
private int id;
private String name;
private String designation; public Employee(int id, String name, String designation) {
super();
this.id = id;
this.name = name;
this.designation = designation;
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} @Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", designation=" + designation + "]";
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getDesignation() {
return designation;
} public void setDesignation(String designation) {
this.designation = designation;
}
}

  EmployeeDAO.java

  

 package com.ehcache.test;

 import java.util.ArrayList;
import java.util.List; import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component; @Component("employeeDAO")
public class EmployeeDAO { // key 当前类,缓存对象为返回值list
@Cacheable(value = {"lt.ecache"}, key = "#root.targetClass")
public List<Employee> getEmployees() {
System.out.println("*** getEmployees() 已经调用 ***");
List<Employee> list = new ArrayList<Employee>(5);
list.add(new Employee(1, "Ben", "Architect"));
list.add(new Employee(2, "Harley", "Programmer"));
list.add(new Employee(3, "Peter", "BusinessAnalyst"));
list.add(new Employee(4, "Sasi", "Manager"));
list.add(new Employee(5, "Abhi", "Designer"));
return list;
} // key id,缓存数据为返回值Employee对象
@Cacheable(value = "lt.ecache", key = "#id")
public Employee getEmployee(int id, List<Employee> employees) {
System.out.println("*** getEmployee(): " + id + " ***");
Employee emp = null;
for (Employee employee : employees) {
if (employee.getId() == id) {
emp = employee;
}
}
return emp;
} // @CachePut会去替换缓存中的Employee对象为当前id对应的对象
@CachePut(value = "lt.ecache", key = "#id")
public Employee updateEmployee(int id, String designation, List<Employee> employees) {
System.out.println("*** updateEmployee() " + id + " ***");
Employee emp = null;
int i = 0;
for (Employee employee : employees) {
if (employee.getId() == id) {
employee.setDesignation(designation);
emp = employee;
}
}
System.out.println(emp);
return emp;
} //key为参数中Employee对象的id,缓存指定id对应的Employee对象
@Cacheable(value = "lt.ecache", key = "#employee.id")
public Employee addEmployee(Employee employee, List<Employee> employees) {
System.out.println("*** addEmployee() : " + employee.getId() + " ***");
employees.add(employee);
System.out.println(employee);
return employee;
} //key为参数中的id,移除缓存,移除指定id对应的Employee对象
@CacheEvict(value = "lt.ecache", key = "#id")
public Employee removeEmployee(int id, List<Employee> employees) {
System.out.println("*** removeEmployee() : " + id + " ***");
Employee emp = null;
int i = 0;
for (Employee employee : employees) {
if (employee.getId() == id) {
emp = employee;
} else {
i++;
}
}
employees.remove(i);
return emp;
} //key为当前类,移除缓存,移除employees列表对象
@CacheEvict(value = "lt.ecache", key = "#root.targetClass")
public List<Employee> removeAllEmployee(List<Employee> employees) {
System.out.println("*** removeAllEmployee() : ***");
employees.clear();
System.out.println(employees.size());
return employees;
} }

  lt.ecache为ehcache.xml中配置的缓存名称。对于要使用到缓存的方法必须使用@注解,同时还要将缓存对象在方法的最后return,否则会报错。

  类中使用到了Spring Expression Language(SpEL),其中相关说明如下

#root.methodName 被执行方法的名称
#root.method.name 被执行的方法
#root.target 被执行的目标对象 
#root.targetClass 被执行的目标对象的class
#root.args[0] 调用目标方法的时候目标方法里面的参数(可将参数列表类比成对象数组)的第一个
#root.caches[0].name 获取当前执行方法的缓存

Main.java

 package com.ehcache.test;

 import java.util.List;

 import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("spring-config-ehcache.xml"); EmployeeDAO dao = (EmployeeDAO) context.getBean("employeeDAO"); System.out.println("-----------------------第1次调用----------------------------");
List<Employee> employees = dao.getEmployees();
System.out.println(employees.toString());
System.out.println("------------------------第2次调用---------------------------");
employees = dao.getEmployees();
System.out.println(employees.toString());
System.out.println("------------------------第3次调用---------------------------");
employees = dao.getEmployees();
System.out.println(employees.toString()); System.out.println("-------------------------第1次调用--------------------------");
Employee employee = dao.getEmployee(1, employees);
System.out.println(employee.toString());
System.out.println("-------------------------第2次调用--------------------------");
employee = dao.getEmployee(1, employees);
System.out.println(employee.toString()); System.out.println("------------------------- 对象更新--------------------------");
dao.updateEmployee(1, "已经更新的对象", employees);
System.out.println("-------------------------第1次调用--------------------------");
employee = dao.getEmployee(1, employees);
System.out.println(employee.toString());
System.out.println("-------------------------第2次调用--------------------------");
employee = dao.getEmployee(1, employees);
System.out.println(employee.toString()); System.out.println("------------------------- 添加对象--------------------------");
dao.addEmployee(new Employee(6, "555", "Designer5555"),employees);
System.out.println("-------------------------第1次调用--------------------------");
employee = dao.getEmployee(6, employees);
System.out.println(employee);
System.out.println("-------------------------第2次调用--------------------------");
employee = dao.getEmployee(6, employees);
System.out.println(employee.toString()); System.out.println("------------------------- 清除一个对象--------------------------");
System.out.println(employees.size());
employee = dao.removeEmployee(6, employees);
System.out.println("-------------------------第1次调用--------------------------");
employees = dao.getEmployees();
System.out.println(employees);
System.out.println(employees.size());
System.out.println("-------------------------第2次调用--------------------------");
employees = dao.getEmployees();
System.out.println(employees); System.out.println("------------------------- 清除所有--------------------------");
System.out.println(employees.size());
employees = dao.removeAllEmployee(employees);
System.out.println("-------------------------第1次调用--------------------------");
employees = dao.getEmployees();
System.out.println(employees);
System.out.println("-------------------------第2次调用--------------------------");
employees = dao.getEmployees();
System.out.println(employees);
}
}

  当对象缓存之后方法就不会执行,而是直接从缓存中获取。

ehcache整合spring注解方式的更多相关文章

  1. ehcache整合spring本地接口方式

    一.简介 ehcache整合spring,可以通过使用echache的本地接口,从而达到定制的目的.在方法中根据业务逻辑进行判断,从缓存中获取数据或将数据保存到缓存.这样让程序变得更加灵活. 本例子使 ...

  2. Ehcache 整合Spring 使用页面、对象缓存

    Ehcache 整合Spring 使用页面.对象缓存 Ehcache在很多项目中都出现过,用法也比较简单.一 般的加些配置就可以了,而且Ehcache可以对页面.对象.数据进行缓存,同时支持集群/分布 ...

  3. spring注解方式在一个普通的java类里面注入dao

    spring注解方式在一个普通的java类里面注入dao @Repositorypublic class BaseDaoImpl implements BaseDao {这是我的dao如果在servi ...

  4. (转)使用Spring注解方式管理事务与传播行为详解

    http://blog.csdn.net/yerenyuan_pku/article/details/52885041 使用Spring注解方式管理事务 前面讲解了怎么使用@Transactional ...

  5. Ehcache学习总结(3)--Ehcache 整合Spring 使用页面、对象缓存

    Ehcache 整合Spring 使用页面.对象缓存 Ehcache在很多项目中都出现过,用法也比较简单.一般的加些配置就可以了,而且Ehcache可以对页面.对象.数据进行缓存,同时支持集群/分布式 ...

  6. Spring Boot整合Mybatis(注解方式和XML方式)

    其实对我个人而言还是不够熟悉JPA.hibernate,所以觉得这两种框架使用起来好麻烦啊. 一直用的Mybatis作为持久层框架, JPA(Hibernate)主张所有的SQL都用Java代码生成, ...

  7. Ibatis,Spring整合(注解方式注入)

    applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xm ...

  8. ActiveMQ学习总结(10)——ActiveMQ采用Spring注解方式发送和监听

    对于ActiveMQ消息的发送,原声的api操作繁琐,而且如果不进行二次封装,打开关闭会话以及各种创建操作也是够够的了.那么,Spring提供了一个很方便的去收发消息的框架,spring jms.整合 ...

  9. (转)Ehcache 整合Spring 使用页面、对象缓存

    Ehcache在很多项目中都出现过,用法也比较简单.一般的加些配置就可以了,而且Ehcache可以对页面.对象.数据进行缓存,同时支持集群/分布式缓存.如果整合Spring.Hibernate也非常的 ...

随机推荐

  1. 一起Polyfill系列:Function.prototype.bind的四个阶段

    昨天边参考es5-shim边自己实现Function.prototype.bind,发现有不少以前忽视了的地方,这里就作为一个小总结吧. 一.Function.prototype.bind的作用 其实 ...

  2. java:[1,1] 需要class, interface或enum

    状态: cmd编译.java文件时报异常:java:[1,1] 需要class, interface或enum异常原因: 主要原因是java文件的编码问题. 在中文操作系统中,使用一贯的"j ...

  3. 后缀数组 - 求最长回文子串 + 模板题 --- ural 1297

    1297. Palindrome Time Limit: 1.0 secondMemory Limit: 16 MB The “U.S. Robots” HQ has just received a ...

  4. C#设计模式——生成器模式(Builder Pattern)

    一.概述在软件系统中,有时候面临着复杂的对象创建,该对象由一定算法构成的子对象组成,由于需求变化,这些子对象会经常变换,但组合在一起的算法却是稳定的.生成器模式可以处理这类对象的构建,它提供了一种封装 ...

  5. sql server聚合函数sum计算出来为空,怎样返回0

    通常我们计算数据库中表的数据有几个常用的聚合函数 1.count : 计数 2.sum: 计算总和 3.avg: 取平均值 4.max: 取最大值 5.min: 取最小值 6.isnull: 当返回数 ...

  6. 野比的示波器案例(Winfrom用户控件)

    使用该用户控件做的效果图,如果数据正确,可实现 波形.直线.等等效果图...... 对于本程序的认识还是不够深彻.如果有其他方法或算法,欢迎讨论下.将我所能理解的代码都再次标识了一番. ------- ...

  7. 操作AppConfig.xml中AppSettings对应值字符串

    //查询AppSettings的key         public static List sql()         {             List list = new List();   ...

  8. Mysql进阶(二)

    一.触发器 对某个表进行[增/删/改]操作的前后如果希望触发某个特定的行为时,可以使用触发器,触发器用于定制用户对表的行进行[增/删/改]前后的行为. 创建视图 # 插入前CREATE TRIGGER ...

  9. RadioButton 自定义控件

    在res/drawable新建radiobutton.xml(本案例为video——evaluate.xml)如下 <?xml version="1.0" encoding= ...

  10. 设计模式之Builder (创建者模式)的一些个人理解(转)

    对于Builder模式很简单,但是一直想不明白为什么要这么设计,为什么要向builder要Product而不是向知道建造过程的Director要.刚才google到一篇文章,总算清楚了.在这里转贴一下 ...