spring配置ConcurrentMap实现缓存

spring本身内置了对Cache的支持,本次记录的是基于Java API的ConcurrentMap的CacheManager配置。

1、xml文件中增加命名空间

<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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-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.xsd">   
   <!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,有一个cache-manager属性用来指定当前所使用的CacheManager对应的bean的名称,默认是cacheManager -->
  <cache:annotation-driven/>    
</beans>
 

<cache:annotation-driven/>有一个cache-manager属性用来指定当前所使用的CacheManager对应的bean的名称,默认是cacheManager

2、配置CacheManager

CacheManager是Spring定义的一个用来管理Cache的接口。Spring自身已经为我们提供了两种CacheManager的实现。一种是基于Java API的ConcurrentMap,另一种是基于第三方Cache实现--EhCache.。

基于ConcurrentMap的配置

<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
    <property name="caches">
        <set>
            <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean">
                <!--xxxx对应@Cacheable中的value值-->
                <property name="name" value="xxxx"/>
            </bean>
        </set>
    </property>
</bean>
 

完成以上步骤后,可进行测试下。

第一次调用时,走其中的方法,第二次不走其中方法,直接从缓存中抽取。

原文地址:https://www.cnblogs.com/amunamuna/p/9798085.html