一、简介
在开发过程中,往往需要对数据进行缓存。spring cache是spring的缓存管理方式,
默认的缓存实现是org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean,
其实也就是ConcurrentHashMap,也就是内存缓存。对数据量少且访问频繁的数据,可以采用这种方法进行数据缓存。
本文主要以默认缓存实现为例进行介绍。
二、缓存配置添加
缓存配置添加有两种,即xml方式和java注解方式,java注解方式与xml方式的内容是一样的,只是形式变了,同学们可二选一,
1、xml配置方式如下:
a) 在配置文件中添加注解驱动的配置,即
<cache:annotation-driven />b)添加缓存管理器,内部定义缓存实现方式,可指定多个,每种缓存方式可自定义名称,如
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager"> <property name="caches"> <set> <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="default" /> <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="mycache" /> </set> </property> </bean>
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" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd "> <context:component-scan base-package="com.dragon.study" /> <cache:annotation-driven />