Spring之缓存机制

在Spring实际开发中,缓存机制具有很重要的作用,并且比Hibernate SessionFactory级别的二级缓存的级别更高,Spring缓存可以在控制器组件或业务逻辑组件级别进行缓存,这样应用完全无须重复调用底层的DAO(数据访问对象,通常基于Hibernate等技术实现)组件的方法,提升了开发效率。

1.配置缓存

这里介绍两种缓存配置,分别是Spring内存缓存和EhCache缓存。
1.1.Spring内置缓存实现的配置
Spring内置的缓存实现并非真正的缓存实现,所以真正的开发并非是一个好的选择,通常用来做简单的测试。
Spring内置的缓存实现通常使用SimpleCacheManager作为缓存管理器,底层直接使用了JDK的ConcurrentMap来实现缓存。SimpleCacheManager使用了ConcurrentMapCacheFactoryBean作为缓存区,每个ConcurrentMapCacheFactoryBean配置一个缓存区。Spring内置缓存实现配置是在Spring容器中实现的,即在beans.xml中进行配置,具体如下所示:
<?xml version="1.0" encoding="GBK"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:cache="http://www.springframework.org/schema/cache"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/cache
	http://www.springframework.org/schema/cache/spring-cache-4.0.xsd">
	<!-- 该元素指定Spring根据注解启用缓存功能 -->
	<cache:annotation-driven/>
	<context:component-scan 
		base-package="xxx.xx.x"/>
	<!-- 配置Spring内置的缓存管理器 -->
	<bean id="cacheManager" class=
		"org.springframework.cache.support.SimpleCacheManager">
		<!-- 配置缓存区 -->
		<property name="caches">
			<set>
				<!-- 下面列出多个缓存区,p:name用于为缓存区指定名字 -->
				<bean class=
				"org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
				p:name="default"/>
				<bean class=
				"org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
				p:name="users"/>
			</set>
		</property>
	</bean>
	
</beans>
以上配置了两个缓存区,default和users。其中上面的<context:component-scan base-package="xxx.xx.x">中的"xxx.xx.x"是指希望扫描的包及其子包。


1.2.EhCache缓存实现的配置
上面讲述的是Spring内置缓存的配置,但是在实际开发中并不使用它。下面讲述的是一个在实际开发中经常使用的缓存:EhCache缓存。Spring内置缓存的配置是在Spring容器中进行的,即在beans.xml中进行,而EhCache缓存的配置需要在应用的类加载路径下添加一个ehcache.xml配置文件。以下便是ehcache.xml配置示例。
<?xml version="1.0" encoding="gbk"?>
<ehcache>
    <diskStore path="java.io.tmpdir" />
	<!-- 配置默认的缓存区 -->
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        maxElementsOnDisk="10000000"
        diskExpiryThreadIntervalSeconds="120"
        memoryStoreEvictionPolicy="LRU"/>
	<!-- 配置名为users的缓存区 -->
    <cache name="users"
        maxElementsInMemory="10000"
        eternal="false"
        overflowToDisk="true"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600" />
</ehcache>
以上配置了一个默认缓存区以及一个名为users的缓存区。对于EhCache缓存的配置,除了需要配置ehcache.xml文件之外。Spring使用EhCacheCacheManager作为缓存实现的缓存管理器,还需要将该对象配置到Spring容器中。但是EhCacheCacheManager底层需要依赖一个net.sf.ehcache.CacheManager作为实际的缓存管理器。为了将net.sf.ehcache.CacheManager纳入Spring容器管理之下,Spring提供了EhCacheManagerFactoryBean工厂Bean,将工厂Bean注入EhCacheCacheManager中就是Spring配置成的EhCache缓存管理器。以下是beans.xml中需要完成的配置:
<?xml version="1.0" encoding="GBK"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	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-4.0.xsd
	http://www.springframework.org/schema/cache
	http://www.springframework.org/schema/cache/spring-cache-4.0.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-4.0.xsd">

	<context:component-scan 
		base-package="xxx.xx.x"/>
		
	<cache:annotation-driven cache-manager="cacheManager" />

	<!-- 配置EhCache的CacheManager
	通过configLocation指定ehcache.xml文件的位置 -->
	<bean id="ehCacheManager"
		class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
		p:configLocation="classpath:ehcache.xml"
		p:shared="false" />
	<!-- 配置基于EhCache的缓存管理器
	并将EhCache的CacheManager注入该缓存管理器Bean -->
	<bean id="cacheManager"
		class="org.springframework.cache.ehcache.EhCacheCacheManager"
		p:cacheManager-ref="ehCacheManager" > 
	</bean>
	
</beans>
以上有两个Bean,其中第一个Bean是工厂Bean,第二个Bean是真正的缓存管理器,第一个Bean需要注入第二个Bean中。


2.使用缓存

这里介绍的是类级别的缓存和方法级别的缓存。本文上的示例都是以Eclipse为基础工具实现的,所以这里先申明一下需要注意的,除了需要将spring相关的jar包引入应用的类加载路径之外,还需要一些包,否则会报错。首先需要将EhCache缓存的JAR包添加到项目的类加载路径中,这里使用前面Hibernate二级缓存使用的JAR包即可,只要将Hiberna解压路径下lib\optional\ehcache\路径下的ehcache-core-2.4.3.jar和slf4j-api-1.6.1.jar复制到项目类加载路径下即可。然后又因为涉及到一些AOP方面的内容,因此需要将aspectj安装路径下lib\下的aspectjrt.jar和aspectjweaver.jar复制到项目类加载路径下即可,同时还需要下载一个jar包,即aopalliance-1.0.jar并复制到项目类加载路径中。然后开始下面示例的讲述。
2.1.类级别的缓存
为体现面向接口编程,虽然这里例子简单,但也使用了接口,如下是接口。
package service;
import handle.User;
public interface UserService {
	public User getUsersByNameAndAge(String name,int age);
	public User getAnotherUser(String name,int age);

}
然后实现类UserServiceImpl组件:
package service.impl;

import handle.User;
import service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Scope;

@Service("userService")
@Cacheable(value="users")
public class UserServiceImpl implements UserService {

	@Override
	public User getUsersByNameAndAge(String name, int age) {
		// TODO Auto-generated method stub
		System.out.println("--正在执行findUsersByNameAndAge()查询方法--");
		return new User(name,age);
	}

	@Override
	public User getAnotherUser(String name, int age) {
		// TODO Auto-generated method stub
		System.out.println("--正在执行findAnotherUser()查询方法--");
		return new User(name,age);
	}

}
其中组件中的User类如下所示:
package handle;

public class User
{
	private String name;
	private int age;
	
	public User()
	{}
	public User(String name, int age)
	{
		super();
		this.name = name;
		this.age = age;
	}
	public String getName()
	{
		return name;
	}
	public void setName(String name)
	{
		this.name = name;
	}
	public int getAge()
	{
		return age;
	}
	public void setAge(int age)
	{
		this.age = age;
	}
	
	

}
上面的注释@Service("userService")则指明了组件名,@Cacheable(value="users")修饰类,则说明是类级别的缓存,并且该组件将数据放入user缓存区。
配置文件,首先是ehcache.xml文件
<?xml version="1.0" encoding="gbk"?>
<ehcache>
    <diskStore path="java.io.tmpdir" />
	<!-- 配置默认的缓存区 -->
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        maxElementsOnDisk="10000000"
        diskExpiryThreadIntervalSeconds="120"
        memoryStoreEvictionPolicy="LRU"/>
	<!-- 配置名为users的缓存区 -->
    <cache name="users"
        maxElementsInMemory="10000"
        eternal="false"
        overflowToDisk="true"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600" />
</ehcache>
这里定义了两个缓存,一个是默认的缓存区,一个是user缓存区,user缓存区是组件指定的缓存区。然后需要将ehcache.xml文件配置到Spring容器中,即配置到beans.xml文件中。
<?xml version="1.0" encoding="GBK"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:cache="http://www.springframework.org/schema/cache"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/cache
	http://www.springframework.org/schema/cache/spring-cache-4.0.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

	<context:component-scan 
		base-package="service"/>
		
	<cache:annotation-driven cache-manager="cacheManager" />

	<!-- 配置EhCache的CacheManager
	通过configLocation指定ehcache.xml文件的位置 -->
	<bean id="ehCacheManager"
		class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
		p:configLocation="classpath:ehcache.xml"
		p:shared="false" />
	<!-- 配置基于EhCache的缓存管理器
	并将EhCache的CacheManager注入该缓存管理器Bean -->
	<bean id="cacheManager"
		class="org.springframework.cache.ehcache.EhCacheCacheManager"
		p:cacheManager-ref="ehCacheManager" > 
	</bean>
	
	<!-- 启动@AspectJ支持 -->
	<aop:aspectj-autoproxy/>
	
</beans>
由于第1部分配置没有讲述将AOP配置进beans.xml,而这里因为AOP的需求,将其配置到beans.xml中。

最后便是工具类的编写,实现功能。

package test;
import handle.*;
import service.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class SpringTest
{
	public static void main(String[] args)
	{
		ApplicationContext ctx =
			new ClassPathXmlApplicationContext("beans.xml");
		UserService us = ctx.getBean("userService" , UserService.class);
		// 第一次调用us对象的方法时会执行该方法,并缓存方法的结果
		User u1 = us.getUsersByNameAndAge("孙悟空", 500);
		// 由于getAnotherUser()方法使用另一个缓存区,
		// 因此无法使用getUsersByNameAndAge()方法缓存区的数据。
		User u2 = us.getAnotherUser("孙悟空", 500);
		System.out.println(u1 == u2); // 输出false
		// getAnotherUser("孙悟空", 500)已经执行过一次,故下面代码使用缓存
		User u3 = us.getAnotherUser("孙悟空", 500);
		System.out.println(u2 == u3); // 输出true
		User u4 = us.getAnotherUser("猪八戒", 500);
		System.out.println(u4 == u3); // 输出false,并且重新执行方法
	}
}

运行之后,得到结果如下:
--正在执行findUsersByNameAndAge()查询方法--
true
true
--正在执行findAnotherUser()查询方法--
false
如结果所示,由于u1、u2、u3传入的参数相同,所以当执行u1时会执行相应的方法,但是当执行u2时,会从缓存中找到相应的对象,而不会执行方法。所以前面只输出一个"--正在执行findUsersByNameAndAge()查询方法--"。而后面u4由于传入的参数不同,则会重新调用相应的方法。




2.2.方法级别的缓存
上面已经讲述了类级别的缓存,其实方法级别的缓存没有很大的不同,只是将修饰类的@Cacheable(value="xxx")用来修饰方法。便于理解,就使用上面相同的示例,便于比较分析。
首先是接口:

package service;
import handle.User;
public interface UserService {
	public User getUsersByNameAndAge(String name,int age);
	public User getAnotherUser(String name,int age);

}
实现类:
package service.impl;

import handle.User;
import service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Scope;

@Service("userService")
public class UserServiceImpl implements UserService {
	@Cacheable(value="users1")
	@Override
	public User getUsersByNameAndAge(String name, int age) {
		// TODO Auto-generated method stub
		System.out.println("--正在执行findUsersByNameAndAge()查询方法--");
		return new User(name,age);
	}
	@Cacheable(value="users2")
	@Override
	public User getAnotherUser(String name, int age) {
		// TODO Auto-generated method stub
		System.out.println("--正在执行findAnotherUser()查询方法--");
		return new User(name,age);
	}

}
实现类中涉及到的user类:
package handle;

public class User
{
	private String name;
	private int age;
	
	public User()
	{}
	public User(String name, int age)
	{
		super();
		this.name = name;
		this.age = age;
	}
	public String getName()
	{
		return name;
	}
	public void setName(String name)
	{
		this.name = name;
	}
	public int getAge()
	{
		return age;
	}
	public void setAge(int age)
	{
		this.age = age;
	}
	
	

}
很明显上面的实现类分别使用@Cacheable(value="users1")和@Cacheable(value="users2")修饰该组件类的两个方法,使用了两个缓存区,然后对应的需要在ehcache.xml文件中配置这两个缓存区,配置内容如下:
<?xml version="1.0" encoding="gbk"?>
<ehcache>
    <diskStore path="java.io.tmpdir" />
	<!-- 配置默认的缓存区 -->
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        maxElementsOnDisk="10000000"
        diskExpiryThreadIntervalSeconds="120"
        memoryStoreEvictionPolicy="LRU"/>
	<!-- 配置名为users1的缓存区 -->
    <cache name="users1"
        maxElementsInMemory="10000"
        eternal="false"
        overflowToDisk="true"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600" />
    <!-- 配置名为users2的缓存区 -->
    <cache name="users2"
        maxElementsInMemory="10000"
        eternal="false"
        overflowToDisk="true"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600" />
</ehcache>
然后将ehcache.xml文件配置到beans.xml文件中:

<?xml version="1.0" encoding="GBK"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:cache="http://www.springframework.org/schema/cache"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/cache
	http://www.springframework.org/schema/cache/spring-cache-4.0.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

	<context:component-scan 
		base-package="service"/>
		
	<cache:annotation-driven cache-manager="cacheManager" />

	<!-- 配置EhCache的CacheManager
	通过configLocation指定ehcache.xml文件的位置 -->
	<bean id="ehCacheManager"
		class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
		p:configLocation="classpath:ehcache.xml"
		p:shared="false" />
	<!-- 配置基于EhCache的缓存管理器
	并将EhCache的CacheManager注入该缓存管理器Bean -->
	<bean id="cacheManager"
		class="org.springframework.cache.ehcache.EhCacheCacheManager"
		p:cacheManager-ref="ehCacheManager" > 
	</bean>
	
	<!-- 启动@AspectJ支持 -->
	<aop:aspectj-autoproxy/>
	
</beans>
最后编写工具类:

package test;
import service.UserService;
import handle.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class EhcacheTest
{
	public static void main(String[] args)
	{
		ApplicationContext ctx =
			new ClassPathXmlApplicationContext("beans.xml");
		UserService us = ctx.getBean("userService" , UserService.class);
		// 第一次调用us对象的方法时会执行该方法,并缓存方法的结果
		User u1 = us.getUsersByNameAndAge("孙悟空", 500);
		// 由于getAnotherUser()方法使用另一个缓存区,
		// 因此无法使用getUsersByNameAndAge()方法缓存区的数据。
		User u2 = us.getAnotherUser("孙悟空", 500);
		System.out.println(u1 == u2); // 输出false
		// getAnotherUser("孙悟空", 500)已经执行过一次,故下面代码使用缓存
		User u3 = us.getAnotherUser("孙悟空", 500);
		System.out.println(u2 == u3); // 输出true
	}
}
运行程序,结果如下:

--正在执行findUsersByNameAndAge()查询方法--
--正在执行findAnotherUser()查询方法--
false
true
结合工具类与结果所示:对象u1访问第一个方法,数据存储在users1缓存区,对象u2虽然参数与对象u1的参数相同,但是访问的是第二个方法,而第二个方法的数据是属于缓存区users2的,此时第一次访问方法2,所以会执行方法2 。所以u2和u1处于不同缓存区,即使参数相同,但它们并不相等。对象u3参数与前两个对象参数相同,且访问的是方法2,由于对象u2已经被存储在缓存区users2,所以执行u3时,会直接取出缓存区参数相同的对象u2,所以不会执行方法,所以u2和u3是相等的


以上便是两种级别的缓存的讲述,使用缓存的过程中,需要注意的是:
1.注释的使用
2.两种级别的缓存的区别
3.jar包的需求,否则会报错。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值