一、简介

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

  本例子使用maven构建,需要的依赖如下:

  1. <dependency>
  2. <groupId>org.springframework</groupId>
  3. <artifactId>spring-core</artifactId>
  4. <version>3.2.6.RELEASE</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>net.sf.ehcache</groupId>
  8. <artifactId>ehcache-core</artifactId>
  9. <version>2.4.2</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.springframework</groupId>
  13. <artifactId>spring-context</artifactId>
  14. <version>3.2.6.RELEASE</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.springframework</groupId>
  18. <artifactId>spring-context-support</artifactId>
  19. <version>3.2.6.RELEASE</version>
  20. </dependency>

二、示例代码

  ehcache.xml代码如下:

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

  spring-config-ehcache-custom.xml代码如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  5. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  6.  
  7. <context:annotation-config />
  8. <context:component-scan base-package="com.ehcache.custom" /> <!-- 注解扫描路径 -->
  9.  
  10. <bean id="cacheService" class="com.ehcache.custom.CacheService">
  11. <property name="cachename" value="lt.ecache"></property> <!-- ehcache.xml中配置的缓存名称 -->
  12. <property name="ehCacheCacheManager" ref="ehCacheCacheManager"></property>
  13. </bean>
  14.  
  15. <bean id="ehCacheCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
  16. <property name="cacheManager" ref="ehcache" />
  17. </bean>
  18.  
  19. <bean id="ehcache"
  20. class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
  21. <property name="configLocation" value="classpath:ehcache.xml" />
  22. </bean>
  23.  
  24. </beans>

  ehcache.xml与spring-config-ehcache-custom.xml存放在系统类路径src目录下。

  实体Employee.java如下

  1. package com.ehcache.custom;
  2.  
  3. import java.io.Serializable;
  4.  
  5. public class Employee implements Serializable {
  6. private static final long serialVersionUID = -4341595236940308296L;
  7. private int id;
  8. private String name;
  9. private String designation;
  10.  
  11. public Employee(int id, String name, String designation) {
  12. super();
  13. this.id = id;
  14. this.name = name;
  15. this.designation = designation;
  16. }
  17.  
  18. public int getId() {
  19. return id;
  20. }
  21.  
  22. public void setId(int id) {
  23. this.id = id;
  24. }
  25.  
  26. @Override
  27. public String toString() {
  28. return "Employee [id=" + id + ", name=" + name + ", designation="
  29. + designation + "]";
  30. }
  31.  
  32. public String getName() {
  33. return name;
  34. }
  35.  
  36. public void setName(String name) {
  37. this.name = name;
  38. }
  39.  
  40. public String getDesignation() {
  41. return designation;
  42. }
  43.  
  44. public void setDesignation(String designation) {
  45. this.designation = designation;
  46. }
  47. }

  EmployeeDAO.java代码如下

  1. package com.ehcache.custom;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. import javax.annotation.Resource;
  7.  
  8. import org.springframework.cache.ehcache.EhCacheCacheManager;
  9. import org.springframework.stereotype.Component;
  10. import org.springframework.util.CollectionUtils;
  11.  
  12. @Component("employeeDAO")
  13. public class EmployeeDAO {
  14.  
  15. @Resource
  16. private CacheService cacheService;
  17.  
  18. private String listKey = "employeeList";
  19.  
  20. /**
  21. * 获取对象列表
  22. *
  23. * @return
  24. */
  25. public List<Employee> getEmployees() {
  26. // 从缓存中获取
  27. List<Employee> list = (List<Employee>) cacheService.get(listKey);
  28. if (CollectionUtils.isEmpty(list)) { // 缓存中没有数据
  29. System.out.println("*** 缓存中没有数据 已经调用 ***");
  30. list = new ArrayList<Employee>(5);
  31. list.add(new Employee(1, "Ben", "Architect"));
  32. list.add(new Employee(2, "Harley", "Programmer"));
  33. list.add(new Employee(3, "Peter", "BusinessAnalyst"));
  34. list.add(new Employee(4, "Sasi", "Manager"));
  35. list.add(new Employee(5, "Abhi", "Designer"));
  36. this.cacheService.put(listKey, list);// 存放在缓存
  37. }else{
  38. System.out.println("*** 缓存中数据 已经存在 ***");
  39. }
  40. return list;
  41. }
  42.  
  43. /**
  44. * 获取指定的对象
  45. *
  46. * @param id
  47. * 对象id
  48. * @param employees
  49. * @return
  50. */
  51. public Employee getEmployee(int id, List<Employee> employees) {
  52. // 从缓存中获取
  53. Employee emp = (com.ehcache.custom.Employee) cacheService.get(id);
  54. if (emp == null) {// 缓存中对象不存在
  55. System.out.println("*** 缓存中对象不存在: " + id + " ***");
  56. for (Employee employee : employees) {
  57. if (employee.getId() == id) {
  58. emp = employee;
  59. }
  60. }
  61. this.cacheService.put(id, emp);// 保存到缓存
  62. }else{
  63. System.out.println("*** 缓存中对象存在: " + id + " ***");
  64. }
  65. return emp;
  66. }
  67.  
  68. /**
  69. * 更新对象
  70. *
  71. * @param id
  72. * 对象id
  73. * @param designation
  74. * @param employees
  75. *
  76. */
  77. public void updateEmployee(int id, String designation,
  78. List<Employee> employees) {
  79. for (Employee employee : employees) {
  80. if (employee.getId() == id) {
  81. employee.setDesignation(designation);
  82. this.cacheService.put(id, employee);// 保存更新后的对象到缓存
  83. }
  84. }
  85. }
  86.  
  87. /**
  88. * 添加对象
  89. *
  90. * @param employee
  91. * 要添加的对象
  92. * @param employees
  93. *
  94. */
  95. public void addEmployee(Employee employee, List<Employee> employees) {
  96. employees.add(employee);
  97. this.cacheService.put(employee.getId(), employee);// 保存更新后的对象到缓存
  98. }
  99.  
  100. /**
  101. * 删除对象
  102. *
  103. * @param id
  104. * Employee对象id
  105. * @param employees
  106. * @return
  107. */
  108. public void removeEmployee(int id, List<Employee> employees) {
  109. int i = 0;
  110. for (Employee employee : employees) {
  111. if (employee.getId() != id) {
  112. i++;
  113. } else {
  114. break;
  115. }
  116. }
  117. this.cacheService.evict(id);// 删除缓存中的数据
  118. employees.remove(i);
  119. }
  120.  
  121. /**
  122. * 删除多个对象
  123. *
  124. * @param employees
  125. * @return
  126. */
  127. public List<Employee> removeAllEmployee(List<Employee> employees) {
  128. System.out.println("*** removeAllEmployee() : ***");
  129. employees.clear();
  130. System.out.println(employees.size());
  131. this.cacheService.evict(listKey);// 删除缓存中的数据
  132. return employees;
  133. }
  134.  
  135. }

  CacheService.java代码如下:

  1. package com.ehcache.custom;
  2.  
  3. import org.springframework.cache.Cache;
  4. import org.springframework.cache.Cache.ValueWrapper;
  5. import org.springframework.cache.ehcache.EhCacheCacheManager;
  6.  
  7. /**
  8. * 封装springcache
  9. *
  10. */
  11. public class CacheService {
  12.  
  13. /**
  14. * 缓存管理对象
  15. */
  16. private EhCacheCacheManager ehCacheCacheManager;
  17.  
  18. /**
  19. * 缓存名称
  20. */
  21. private String cachename;
  22.  
  23. public EhCacheCacheManager getEhCacheCacheManager() {
  24. return ehCacheCacheManager;
  25. }
  26.  
  27. public void setEhCacheCacheManager(EhCacheCacheManager ehCacheCacheManager) {
  28. this.ehCacheCacheManager = ehCacheCacheManager;
  29. }
  30.  
  31. public String getCachename() {
  32. return cachename;
  33. }
  34.  
  35. public void setCachename(String cachename) {
  36. this.cachename = cachename;
  37. }
  38.  
  39. /**
  40. * 获取进行操作的Cache对象
  41. *
  42. * @return
  43. */
  44. private Cache getCache() {
  45. return this.ehCacheCacheManager.getCache(this.cachename);
  46. }
  47.  
  48. /**
  49. * 获取对象
  50. *
  51. * @param key
  52. * 对象对应的key值
  53. * @return
  54. */
  55. public Object get(Object key) {
  56. ValueWrapper valueWrapper = getCache().get(key);
  57. if (valueWrapper != null) {
  58. return getCache().get(key).get();
  59. }
  60. return valueWrapper;
  61. }
  62.  
  63. /**
  64. * 缓存对象
  65. *
  66. * @param key
  67. * @param value
  68. */
  69. public void put(Object key, Object value) {
  70. getCache().put(key, value);
  71. }
  72.  
  73. /**
  74. * 如果key对应的缓存数据存在则删除
  75. * @param key
  76. */
  77. public void evict(Object key){
  78. getCache().evict(key);
  79. }
  80.  
  81. /**
  82. * 该方法获取的就是 net.sf.ehcache.Cache对象
  83. *
  84. * @return net.sf.ehcache.Cache对象
  85. */
  86. public Object getNativeCache() {
  87. return getCache().getNativeCache();
  88. }
  89.  
  90. }

  该类主要是对spring中的ehcache进行封装。

  Main.java代码如下:

  1. package com.ehcache.custom;
  2.  
  3. import java.util.List;
  4.  
  5. import org.springframework.context.ApplicationContext;
  6. import org.springframework.context.support.ClassPathXmlApplicationContext;
  7.  
  8. public class Main {
  9.  
  10. public static void main(String[] args) {
  11.  
  12. ApplicationContext context = new ClassPathXmlApplicationContext(
  13. "spring-config-ehcache-custom.xml");
  14.  
  15. EmployeeDAO dao = (EmployeeDAO) context.getBean("employeeDAO");
  16.  
  17. System.out.println("-----------------------第1次调用----------------------------");
  18. List<Employee> employees = dao.getEmployees();
  19. System.out.println(employees.toString());
  20.  
  21. System.out.println("------------------------第2次调用---------------------------");
  22. employees = dao.getEmployees();
  23. System.out.println(employees.toString());
  24.  
  25. System.out.println("------------------------第3次调用---------------------------");
  26. employees = dao.getEmployees();
  27. System.out.println(employees.toString());
  28.  
  29. System.out.println("------------------------- 获取对象--------------------------");
  30. System.out.println("-------------------------第1次调用--------------------------");
  31. Employee employee = dao.getEmployee(1, employees);
  32. System.out.println(employee.toString());
  33. System.out.println("-------------------------第2次调用--------------------------");
  34. employee = dao.getEmployee(1, employees);
  35. System.out.println(employee.toString());
  36.  
  37. System.out.println("------------------------- 对象更新--------------------------");
  38. dao.updateEmployee(1, "已经更新的对象", employees);
  39. System.out.println("-------------------------第1次调用--------------------------");
  40. employee = dao.getEmployee(1, employees);
  41. System.out.println(employee.toString());
  42. System.out.println("-------------------------第2次调用--------------------------");
  43. employee = dao.getEmployee(1, employees);
  44. System.out.println(employee.toString());
  45.  
  46. System.out.println("------------------------- 添加对象--------------------------");
  47. dao.addEmployee(new Employee(6, "555", "Designer5555"),employees);
  48. System.out.println("-------------------------第1次调用--------------------------");
  49. employee = dao.getEmployee(6, employees);
  50. System.out.println(employee);
  51. System.out.println("-------------------------第2次调用--------------------------");
  52. employee = dao.getEmployee(6, employees);
  53. System.out.println(employee.toString());
  54.  
  55. System.out.println("------------------------- 清除一个对象--------------------------");
  56. dao.removeEmployee(2, employees);
  57. System.out.println("-------------------------第1次调用--------------------------");
  58. employees = dao.getEmployees();
  59. System.out.println(employees);
  60. System.out.println("-------------------------第2次调用--------------------------");
  61. employees = dao.getEmployees();
  62. System.out.println(employees);
  63.  
  64. System.out.println("------------------------- 清除所有--------------------------");
  65. System.out.println(employees.size());
  66. employees = dao.removeAllEmployee(employees);
  67. System.out.println("-------------------------第1次调用--------------------------");
  68. employees = dao.getEmployees();
  69. System.out.println(employees);
  70. System.out.println("-------------------------第2次调用--------------------------");
  71. employees = dao.getEmployees();
  72. System.out.println(employees);
  73. }
  74. }

  执行该文件即可。

ehcache整合spring本地接口方式的更多相关文章

  1. ehcache整合spring注解方式

    一.简介 在hibernate中就是用到了ehcache 充当缓存.spring对ehcache也提供了支持,使用也比较简单,只需在spring的配置文件中将ehcache的ehcache.xml文件 ...

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

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

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

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

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

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

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

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

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

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

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

    转自:http://www.cnblogs.com/hoojo/archive/2012/07/12/2587556.html Ehcache在很多项目中都出现过,用法也比较简单.一般的加些配置就可以 ...

  8. Ehcache整合spring配置

    为了提高系统的运行效率,引入缓存机制,减少数据库访问和磁盘IO.下面说明一下ehcache和spring整合配置. 1.   需要的jar包 slf4j-api-1.6.1.jar ehcache-c ...

  9. Ehcache学习总结(2)--Ehcache整合spring配置

    首先需要的maven依赖为: [html] view plain copy <!--ehcache--> <dependency> <groupId>com.goo ...

随机推荐

  1. mysql 在row模式下truncate 与 delete 二进制日志记录的差异

    二进行日志的格式为row mysql> show variables like 'binlog_format'; +---------------+-------+ | Variable_nam ...

  2. mysql如何修改所有的definer

    mysql中的definer是什么,有什么作用? 我们在mysql创建view.trigger.function.procedure.event时都会定义一个Definer=‘xxx’,类似如下: C ...

  3. 2015年百度之星初赛(1) --- C 序列变换

    序列变换 Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submis ...

  4. P6 EPPM R16.1安装与配置指南(二)

    P6 EPPM R16.1安装与配置指南(一) http://www.cnblogs.com/endv/p/5634620.html P6 EPPM R16.1安装与配置指南(二) 环境变量配置 新建 ...

  5. 【jQuery基础学习】06 jQuery表单验证插件-Validation

    jQuery的基础部分前面都讲完了,那么就看插件了. 关于jQuery表单验证插件-Validation validation特点: 内置验证规则:拥有必填.数字.E-Mail.URL和信用卡号码等1 ...

  6. QQ视差特效和ListView侧滑删除

    如图所示是效果图,当向下拉时,图片会被拉出来,松手后恢复.和ListView的侧滑删除   1.视差特效 首先图片是通过addHeaderView加上去的,所以在设置Adapter前先设置一个View ...

  7. CodeForces 149D Coloring Brackets

    Coloring Brackets time limit per test: 2 seconds memory limit per test: 256 megabytes input: standar ...

  8. java四大域总结

    最近学完了web部分,发现有些地方总是单个容易理解,可是把所有的放在一起来大杂烩,总是有那么几个知识点容易混淆.其实网上的资料已经够多了,虽然也不乏辛劳的搬运工.可是最终的目的不就是要我们自身理解吗? ...

  9. C#中的索引器原理

    朋友们,还记得我们在C#语言开发中用到过索引器吗? 记得在获得DataGridView控件的某列值时:dgvlist.SelectedRows[0].Cells[0].Value; 记得在获得List ...

  10. 以Web Host的方式来寄宿Web API

    一.新建一个Common的类库项目并新建一个测试用的Contact实体类 namespace Common { public class Contact { public string Id { ge ...