一、简介

  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代码如下:

 <?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-custom.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: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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:annotation-config />
<context:component-scan base-package="com.ehcache.custom" /> <!-- 注解扫描路径 --> <bean id="cacheService" class="com.ehcache.custom.CacheService">
<property name="cachename" value="lt.ecache"></property> <!-- ehcache.xml中配置的缓存名称 -->
<property name="ehCacheCacheManager" ref="ehCacheCacheManager"></property>
</bean> <bean id="ehCacheCacheManager" 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-custom.xml存放在系统类路径src目录下。

  实体Employee.java如下

 package com.ehcache.custom;

 import java.io.Serializable;

 public class Employee implements Serializable {
private static final long serialVersionUID = -4341595236940308296L;
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.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代码如下:

 package com.ehcache.custom;

 import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.ehcache.EhCacheCacheManager; /**
* 封装springcache
*
*/
public class CacheService { /**
* 缓存管理对象
*/
private EhCacheCacheManager ehCacheCacheManager; /**
* 缓存名称
*/
private String cachename; public EhCacheCacheManager getEhCacheCacheManager() {
return ehCacheCacheManager;
} public void setEhCacheCacheManager(EhCacheCacheManager ehCacheCacheManager) {
this.ehCacheCacheManager = ehCacheCacheManager;
} public String getCachename() {
return cachename;
} public void setCachename(String cachename) {
this.cachename = cachename;
} /**
* 获取进行操作的Cache对象
*
* @return
*/
private Cache getCache() {
return this.ehCacheCacheManager.getCache(this.cachename);
} /**
* 获取对象
*
* @param key
* 对象对应的key值
* @return
*/
public Object get(Object key) {
ValueWrapper valueWrapper = getCache().get(key);
if (valueWrapper != null) {
return getCache().get(key).get();
}
return valueWrapper;
} /**
* 缓存对象
*
* @param key
* @param value
*/
public void put(Object key, Object value) {
getCache().put(key, value);
} /**
* 如果key对应的缓存数据存在则删除
* @param key
*/
public void evict(Object key){
getCache().evict(key);
} /**
* 该方法获取的就是 net.sf.ehcache.Cache对象
*
* @return net.sf.ehcache.Cache对象
*/
public Object getNativeCache() {
return getCache().getNativeCache();
} }

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

  Main.java代码如下:

 package com.ehcache.custom;

 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-custom.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("------------------------- 获取对象--------------------------");
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("------------------------- 清除一个对象--------------------------");
dao.removeEmployee(2, employees);
System.out.println("-------------------------第1次调用--------------------------");
employees = dao.getEmployees();
System.out.println(employees);
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注解方式

    一.简介 在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. 加密,解密,Hash

    Hash的算法: SHA256Managed(mscorlib.dll) private static string HashCreditCard(string creditCardNumber) { ...

  2. DES算法详解

    本文主要介绍了DES算法的步骤,包括IP置换.密钥置换.E扩展置换.S盒代替.P盒置换和末置换. 1.DES算法简介 DES算法为密码体制中的对称密码体制,又被称为美国数据加密标准. DES是一个分组 ...

  3. [Tool] 源代码管理之Git

    本节目录 什么是Git 什么是GitHub 安装Git GitHub之Repository GitHub之托管页面 常用Git 命令 什么是Git 由于现在的开发多人协同办公,因此出现源代码管理工具 ...

  4. Spring重点—— IOC 容器中 Bean 的生命周期

    一.理解 Bean 的生命周期,对学习 Spring 的整个运行流程有极大的帮助. 二.在 IOC 容器中,Bean 的生命周期由 Spring IOC 容器进行管理. 三.在没有添加后置处理器的情况 ...

  5. “康园圈--互联网+校园平台“项目之sprint2

    一.sprint2任务列表 1.部署框架,并上传代码到github. 2.原型设计 * 设计首页界面原型(包括功能公告.快速通道等展示栏) * 设计店铺浏览页面原型 * 设计店内浏览页面原型 * 设计 ...

  6. 移动web开发总结

    让网页的宽度自适应屏幕<meta name="viewport" content="width=device-width"/>   1)html上加 ...

  7. [转]在SqlServer 中解析JSON数据

      在Sqlserver中可以直接处理Xml格式的数据,但因为项目需要所以要保存JSON格式的数据到Sqlserver中在博客:Consuming JSON Strings in SQL Server ...

  8. 重新想象 Windows 8 Store Apps (45) - 多线程之异步编程: IAsyncAction, IAsyncOperation, IAsyncActionWithProgress, IAsyncOperationWithProgress

    [源码下载] 重新想象 Windows 8 Store Apps (45) - 多线程之异步编程: IAsyncAction, IAsyncOperation, IAsyncActionWithPro ...

  9. csharp: Sound recording

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsof ...

  10. C# 分支语句

    选择语句 if,else if是如果的意思,else是另外的意思,if后面跟()括号内为判断条件,如果符合条件则进入if语句执行命令.如果不符合则不进入if语句.else后不用加条件,但是必须与if配 ...