spring的cache的注解方式的简单实用(具体步骤)

本文详细介绍了Spring框架中的缓存管理机制,包括如何通过注解和配置文件启用缓存功能,配置不同类型的CacheManager,以及如何利用注解来实现方法级别的缓存控制。

     1、启用注解模式

如果使用的是注解类,需要在注解类上添加@EnableCaching,如果是使用的配置文件

<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.xsd

http://www.springframework.org/schema/cache

http://www.springframework.org/schema/cache/spring-cache.xsd

">

    <cache:annotation-driven /> <!-- 启用缓存 -->

   <bean id="cacheManager"

                 class="org.springframework.cache.concurrent.ConcurrentMapCacheManager" />

</beans>

2、配置CacheManager
Spring 3.1 内置了五个缓存管理器实现,如下:

        *SimpleCacheManager

        *NoOpCacheManger

        *ConcurrentMapCacheManager

         *CompositeCacheManger

        *EhCacheCacheManger

       Spring Data提供了两个缓存管理器:

             *RedisCacheManager(来自于Spring Data Redis项目)

             *GmfireCacheManager(来自于Spring Data GemFire项目)

在这里使用EhCacheCacheManger来实现缓存服务
配置缓存管理器实例,可以自行转换为xml中的配置

@Configuration

@EnableCaching//开启声明式缓存支持

public class RootConfig {

/**

* 注册实现CacheManager的bean

* EhCache的CacheManager要被注入到Spring的EhCacheCacheManager之中

* @param cacheManager 由下面的EhCacheManagerFactoryBean提供

* @return

*/

     @Bean

     public EhCacheCacheManager cacheCacheManager(CacheManager cacheManager){

            return new EhCacheCacheManager(cacheManager);

     }

 

       @Bean

        public EhCacheManagerFactoryBean ehcache(){

                 EhCacheManagerFactoryBean ehCacheManagerFactoryBean =

                        new EhCacheManagerFactoryBean();

                  ehCacheManagerFactoryBean.setConfigLocation(   new ClassPathResource("ehcahe.xml的配置文件所在地址")  );

                  return ehCacheManagerFactoryBean;

      }

}

   说明:Spring提供了EhCacheManagerFactoryBean来生成EhCache的CacheManager的方法。方法ehcache会创建并返回一个EhCacheManagerFactoryBean的实例。因为他是一个工厂bean(也就是说他实现了Spring的FactoryBean接口),所以在spring应用上下文中并不是EhCacheManagerFactoryBean 的示例,而是CacheManager的一个实例,因此适合注入到cacheCacheManager之中。

3、ehcache.xml文件的基本配置(具体配置可百度)

<ehcache>

      <cache name="spittleCache"

           maxBytesLocalHeap="50m" ---最大的堆存储为50m

            timeToLiveSeconds="100" ---存活时间100秒

   </ehcache>


4、spring 对Cache的注解支持

  Spring 提供了四个注解来声明缓存规则

         *@Cacheable 表明Spring在调用方法之前,首先应该在缓存中查找方法的返回值。如果这个值能够找到,就会返回缓存的的值,否则的话,这个方法就会被调用,返回值会放到缓存之中。

        *@CachePut :表明Spring应该将方法的返回值放到缓存中。在方法的调用前不会检查缓存,方法始终都会被调用。

        *@CacheEvict : 表明Spring应该在缓存中移除一个或多个条目。

        *@Caching : 这是一个分组的注解,能够同时应用多个其他的缓存注解。


5、简单示例

        @Cacheable(value="缓存空间的名称,xml中配置的" , key = "#spittle.id")--spittle是参数里面的spittle,如果不设置,就以参数作为key

        Spittle save(Spittle spittle);


  条件化缓存:

       @Cacheable(value="spittleCache" , unless="#result.message.contains('NoCache')")//当条件为true时,不保存对象

       Spittle findOne(Long id);

 

 移除缓存条目:

     @CacheEvict("spittleCache")

      void remove(Long spittled);

PS:总结比较粗糙,勿怪,主要备忘,有问题,留言,大家交流

 

 

 

### 如何使用 Spring Cache 注解封装缓存功能 Spring CacheSpring 框架提供的一个缓存抽象,能够通过注解方式轻松集成到 Spring 应用程序中,为方法调用的结果提供缓存支持,从而提高应用程序的性能和响应速度 [^1]。以下是使用 Spring Cache 注解封装缓存功能的步骤和关键点。 #### 1. 开启缓存注解功能 在 Spring Boot 应用的主类上使用 `@EnableCaching` 注解来启用缓存支持。这样 Spring 才能识别和处理缓存相关的注解。 ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; @SpringBootApplication @EnableCaching public class CacheDemoApplication { public static void main(String[] args) { SpringApplication.run(CacheDemoApplication.class, args); } } ``` #### 2. 配置缓存管理器 Spring Cache 是一个抽象层,实际的缓存实现需要依赖具体的缓存提供者,如 `ConcurrentMapCache`(内存缓存)、`Redis`、`EhCache` 等。可以通过配置 `CacheManager` 来指定缓存实现。 例如,使用基于内存的缓存: ```java import org.springframework.cache.CacheManager; import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class CacheConfig { @Bean public CacheManager cacheManager() { return new ConcurrentMapCacheManager("role", "user"); } } ``` #### 3. 使用 Spring Cache 注解 ##### 3.1 `@Cacheable` `@Cacheable` 注解用于标记方法的返回值需要被缓存。当方法被调用时,Spring 会先检查缓存中是否存在对应的键值,如果存在则直接返回缓存结果,否则执行方法并将结果存入缓存。 ```java import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class RoleService { // 缓存 key 为 id 的值 @Cacheable(key = "#id") public Role findById(Integer id) { // 模拟数据库查询 return new Role(id, "Admin"); } // 缓存 key 为方法名 @Cacheable(key = "#root.methodName") public List<Role> findAll() { // 模拟数据库查询 return Arrays.asList(new Role(1, "Admin"), new Role(2, "User")); } } ``` ##### 3.2 `@CacheConfig` `@CacheConfig` 注解可以用于类级别,统一配置缓存名称(`cacheNames`),避免在每个方法上重复配置。 ```java import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service @CacheConfig(cacheNames = "role") public class RoleService { @Cacheable(key = "#id") public Role findById(Integer id) { return new Role(id, "Admin"); } @Cacheable(key = "#root.methodName") public List<Role> findAll() { return Arrays.asList(new Role(1, "Admin"), new Role(2, "User")); } } ``` ##### 3.3 `@CachePut` `@CachePut` 注解用于更新缓存,无论缓存中是否存在数据,都会执行方法并将结果写入缓存。 ```java import org.springframework.cache.annotation.CachePut; import org.springframework.stereotype.Service; @Service public class RoleService { @CachePut(key = "#role.id") public Role update(Role role) { // 模拟更新操作 return role; } } ``` ##### 3.4 `@CacheEvict` `@CacheEvict` 注解用于清除缓存中的数据,通常用于删除或重置缓存。 ```java import org.springframework.cache.annotation.CacheEvict; import org.springframework.stereotype.Service; @Service public class RoleService { @CacheEvict(key = "#id") public void deleteById(Integer id) { // 模拟删除操作 } @CacheEvict(allEntries = true) public void clearAll() { // 清除 role 缓存下的所有条目 } } ``` #### 4. SpEL 表达式在缓存注解中的应用 Spring Cache 支持使用 SpEL(Spring Expression Language)表达式来动态生成缓存的键值。例如: - `#id`:表示方法参数中的 `id` 值。 - `#root.methodName`:表示当前方法的名称。 - `#root.target`:表示目标对象。 - `#root.caches[0].name`:表示当前缓存的名称。 ```java @Cacheable(key = "#root.methodName + #id") public Role findById(Integer id) { return new Role(id, "Admin"); } ``` #### 5. 清空缓存并测试 在开发过程中,可以通过调用 `@CacheEvict` 方法来清空缓存,再分别执行测试方法以验证缓存行为。 ```java import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class RoleServiceTest { @Autowired private RoleService roleService; @Test void testFindById() { Role role1 = roleService.findById(1); Role role2 = roleService.findById(1); // 第二次调用应命中缓存 } @Test void testClearCache() { roleService.deleteById(1); Role role = roleService.findById(1); // 删除后重新查询,缓存应被更新 } } ``` #### 6. 总结 通过 `@EnableCaching` 启用缓存功能,结合 `@Cacheable`、`@CachePut` 和 `@CacheEvict` 等注解,可以轻松地在 Spring 应用中实现缓存功能的封装。同时,使用 `@CacheConfig` 可以统一配置缓存名称,SpEL 表达式则提供了灵活的键生成策略 [^4]。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值