一、简介
ehcache整合spring,可以通过使用echache的本地接口,从而达到定制的目的。在方法中根据业务逻辑进行判断,从缓存中获取数据或将数据保存到缓存。这样让程序变得更加灵活。
本例子使用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代码如下:
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 8 <context:annotation-config /> 9 <context:component-scan base-package="com.ehcache.custom" /> <!-- 注解扫描路径 --> 10 11 <bean id="cacheService" class="com.ehcache.custom.CacheService"> 12 <property name="cachename" value="lt.ecache"></property> <!-- ehcache.xml中配置的缓存名称 --> 13 <property name="ehCacheCacheManager" ref="ehCacheCacheManager"></property> 14 </bean> 15 16 <bean id="ehCacheCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> 17 <property name="cacheManager" ref="ehcache" /> 18 </bean> 19 20 <bean id="ehcache" 21 class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> 22 <property name="configLocation" value="classpath:ehcache.xml" /> 23 </bean> 24 25 </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代码如下
package com.ehcache.custom; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.springframework.cache.ehcache.EhCacheCacheManager; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; @Component("employeeDAO") public class EmployeeDAO { @Resource private CacheService cacheService; private String listKey = "employeeList"; /** * 获取对象列表 * * @return */ public List<Employee> getEmployees() { // 从缓存中获取 List<Employee> list = (List<Employee>) cacheService.get(listKey); if (CollectionUtils.isEmpty(list)) { // 缓存中没有数据 System.out.println("*** 缓存中没有数据 已经调用 ***"); 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")); this.cacheService.put(listKey, list);// 存放在缓存 }else{ System.out.println("*** 缓存中数据 已经存在 ***"); } return list; } /** * 获取指定的对象 * * @param id * 对象id * @param employees * @return */ public Employee getEmployee(int id, List<Employee> employees) { // 从缓存中获取 Employee emp = (com.ehcache.custom.Employee) cacheService.get(id); if (emp == null) {// 缓存中对象不存在 System.out.println("*** 缓存中对象不存在: " + id + " ***"); for (Employee employee : employees) { if (employee.getId() == id) { emp = employee; } } this.cacheService.put(id, emp);// 保存到缓存 }else{ System.out.println("*** 缓存中对象存在: " + id + " ***"); } return emp; } /** * 更新对象 * * @param id * 对象id * @param designation * @param employees * */ public void updateEmployee(int id, String designation, List<Employee> employees) { for (Employee employee : employees) { if (employee.getId() == id) { employee.setDesignation(designation); this.cacheService.put(id, employee);// 保存更新后的对象到缓存 } } } /** * 添加对象 * * @param employee * 要添加的对象 * @param employees * */ public void addEmployee(Employee employee, List<Employee> employees) { employees.add(employee); this.cacheService.put(employee.getId(), employee);// 保存更新后的对象到缓存 } /** * 删除对象 * * @param id * Employee对象id * @param employees * @return */ public void removeEmployee(int id, List<Employee> employees) { int i = 0; for (Employee employee : employees) { if (employee.getId() != id) { i++; } else { break; } } this.cacheService.evict(id);// 删除缓存中的数据 employees.remove(i); } /** * 删除多个对象 * * @param employees * @return */ public List<Employee> removeAllEmployee(List<Employee> employees) { System.out.println("*** removeAllEmployee() : ***"); employees.clear(); System.out.println(employees.size()); this.cacheService.evict(listKey);// 删除缓存中的数据 return employees; } }
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 /** 83 * 该方法获取的就是 net.sf.ehcache.Cache对象 84 * 85 * @return net.sf.ehcache.Cache对象 86 */ 87 public Object getNativeCache() { 88 return getCache().getNativeCache(); 89 } 90 91 }
该类主要是对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 30 System.out.println("------------------------- 获取对象--------------------------"); 31 System.out.println("-------------------------第1次调用--------------------------"); 32 Employee employee = dao.getEmployee(1, employees); 33 System.out.println(employee.toString()); 34 System.out.println("-------------------------第2次调用--------------------------"); 35 employee = dao.getEmployee(1, employees); 36 System.out.println(employee.toString()); 37 38 39 System.out.println("------------------------- 对象更新--------------------------"); 40 dao.updateEmployee(1, "已经更新的对象", employees); 41 System.out.println("-------------------------第1次调用--------------------------"); 42 employee = dao.getEmployee(1, employees); 43 System.out.println(employee.toString()); 44 System.out.println("-------------------------第2次调用--------------------------"); 45 employee = dao.getEmployee(1, employees); 46 System.out.println(employee.toString()); 47 48 49 System.out.println("------------------------- 添加对象--------------------------"); 50 dao.addEmployee(new Employee(6, "555", "Designer5555"),employees); 51 System.out.println("-------------------------第1次调用--------------------------"); 52 employee = dao.getEmployee(6, employees); 53 System.out.println(employee); 54 System.out.println("-------------------------第2次调用--------------------------"); 55 employee = dao.getEmployee(6, employees); 56 System.out.println(employee.toString()); 57 58 59 System.out.println("------------------------- 清除一个对象--------------------------"); 60 dao.removeEmployee(2, employees); 61 System.out.println("-------------------------第1次调用--------------------------"); 62 employees = dao.getEmployees(); 63 System.out.println(employees); 64 System.out.println("-------------------------第2次调用--------------------------"); 65 employees = dao.getEmployees(); 66 System.out.println(employees); 67 68 69 System.out.println("------------------------- 清除所有--------------------------"); 70 System.out.println(employees.size()); 71 employees = dao.removeAllEmployee(employees); 72 System.out.println("-------------------------第1次调用--------------------------"); 73 employees = dao.getEmployees(); 74 System.out.println(employees); 75 System.out.println("-------------------------第2次调用--------------------------"); 76 employees = dao.getEmployees(); 77 System.out.println(employees); 78 } 79 }
执行该文件即可。