工程结构图:
1.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">
<!-- 磁盘缓存位置 -->
<diskStore path="java.io.tmpdir/ehcache"/>
<!-- 默认缓存 -->
<defaultCache
maxEntriesLocalHeap="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxEntriesLocalDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"/>
<!-- helloworld1缓存 -->
<cache name="helloworld1"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="5"
timeToLiveSeconds="5"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"/>
<!-- helloworld2缓存 -->
<cache name="helloworld2"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="5"
timeToLiveSeconds="5"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"/>
<!-- users缓存 -->
<cache name="users"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="5"
timeToLiveSeconds="5"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
2.spring-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"
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-3.2.xsd">
<description>ehcache缓存配置管理文件</description>
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:spring/ehcache.xml"/>
</bean>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehcache"/>
</bean>
<!-- 启用缓存注解开关 -->
<cache:annotation-driven cache-manager="cacheManager"/>
</beans>
3.applicationContext.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:component-scan base-package="ehcache.com"/>
<!-- 加载资源文件 -->
<import resource="classpath:spring/spring-ehcache.xml"/>
</beans>
4.实体类User.java
package ehcache.com.model;
import java.io.Serializable;
public class User implements Serializable{
private static final long serialVersionUID = 1L;
private int id;
private String name;
public User() {}
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
5.业务类UserService.java
package ehcache.com.service;
import java.util.HashSet;
import java.util.Set;
import org.springframework.stereotype.Service;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import ehcache.com.model.User;
@Service
public class UserService {
private Set<User> users;
public UserService() {
users = new HashSet<User>();
User user1 = new User(1, "张三");
User user2 = new User(2, "赵四");
User user3 = new User(3, "王五");
users.add(user1);
users.add(user2);
users.add(user3);
}
@Cacheable({"users"})
public User findUser(User user) {
return findUserInDB(user.getId());
}
@Cacheable(value = "users", condition = "#user.getId() <= 2")
public User findUserInLimit(User user) {
return findUserInDB(user.getId());
}
@CacheEvict(value="users")
public void removeUser(User user) {
removeUserInDB(user.getId());
}
@CacheEvict(value = "users", allEntries = true)
public void clear() {
removeAllInDB();
}
/**
* 模拟查找数据库
*/
public User findUserInDB(int id) {
for (User u : users) {
if (id == u.getId()) {
System.out.println("查找数据库 id = " + id + " 成功");
return u;
}
}
return null;
}
/**
* 模拟更新数据库
*/
public void updateUserInDB(User user) {
for (User u : users) {
if (user.getId() == u.getId()) {
System.out.println("更新数据库" + u + " -> " + user);
u.setName(user.getName());
}
}
}
private void removeUserInDB(int id) {
for (User u : users) {
if (id == u.getId()) {
System.out.println("从数据库移除 id = " + id + " 的数据");
users.remove(u);
break;
}
}
}
private void removeAllInDB() {
users.clear();
}
}
6.测试类EhcacheWithSpringTest.java
package ehcache.com;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.beans.factory.annotation.Autowired;
import ehcache.com.model.User;
import ehcache.com.service.UserService;
/**
* 本类展示并测试 Spring + Ehcache 的缓存解决方案
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/applicationContext.xml"})
public class EhcacheWithSpringTest {
@Autowired
UserService userService;
/**
* 测试@Cacheable
*/
@Test
public void testFindUser() throws InterruptedException {
// 设置查询条件
User user1 = new User(1, null);
User user2 = new User(2, null);
User user3 = new User(3, null);
System.out.println("第一次查询");
System.out.println(userService.findUser(user1));
System.out.println(userService.findUser(user2));
System.out.println(userService.findUser(user3));
System.out.println("\n第二次查询");
System.out.println(userService.findUser(user1));
System.out.println(userService.findUser(user2));
System.out.println(userService.findUser(user3));
// 在classpath:ehcache/ehcache.xml中,设置了userCache的缓存时间为3000 ms, 这里设置等待
Thread.sleep(3000);
System.out.println("\n缓存过期,再次查询");
System.out.println(userService.findUser(user1));
System.out.println(userService.findUser(user2));
System.out.println(userService.findUser(user3));
}
/**
* 测试@Cacheable设置Spring SpEL条件限制
*/
@Test
public void testFindUserInLimit() throws InterruptedException {
// 设置查询条件
User user1 = new User(1, null);
User user2 = new User(2, null);
User user3 = new User(3, null);
System.out.println("第一次查询user info");
System.out.println(userService.findUserInLimit(user1));
System.out.println(userService.findUserInLimit(user2));
System.out.println(userService.findUserInLimit(user3));
System.out.println("\n第二次查询user info");
System.out.println(userService.findUserInLimit(user1));
System.out.println(userService.findUserInLimit(user2));
System.out.println(userService.findUserInLimit(user3)); // 超过限制条件,不会从缓存中读数据
// 在classpath:ehcache/ehcache.xml中,设置了userCache的缓存时间为3000 ms, 这里设置等待
Thread.sleep(3000);
System.out.println("\n缓存过期,再次查询");
System.out.println(userService.findUserInLimit(user1));
System.out.println(userService.findUserInLimit(user2));
System.out.println(userService.findUserInLimit(user3));
}
/**
* 测试@CachePut
*/
@Test
public void testUpdateUser() {
// 设置查询条件
User user2 = new User(2, null);
System.out.println(userService.findUser(user2));
userService.updateUserInDB(new User(2, "尼古拉斯.赵四"));
System.out.println(userService.findUser(user2));
}
/**
* 测试@CacheEvict删除指定缓存
*/
@Test
public void testRemoveUser() {
// 设置查询条件
User user1 = new User(1, null);
System.out.println("数据删除前:");
System.out.println(userService.findUser(user1));
userService.removeUser(user1);
System.out.println("数据删除后:");
System.out.println(userService.findUser(user1));
}
/**
* 测试@CacheEvict删除所有缓存
*/
@Test
public void testClear() {
System.out.println("数据清空前:");
System.out.println(userService.findUser(new User(1, null)));
System.out.println(userService.findUser(new User(2, null)));
System.out.println(userService.findUser(new User(3, null)));
userService.clear();
System.out.println("\n数据清空后:");
System.out.println(userService.findUser(new User(1, null)));
System.out.println(userService.findUser(new User(2, null)));
System.out.println(userService.findUser(new User(3, null)));
}
}
参考自:http://www.codeceo.com/article/spring-integration-ehcache-management-cache.html