Spring Cache注解的使用

前言

SpringCache是SpringFramework3.1引入的新特性,提供了基于注解的缓存配置方法.SpringCache是SpringFramework3.1引入的新特性,提供了基于注解的缓存配置方法

使用前步骤

1.引入相关jar包

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context</artifactId>
</dependency>

2.配置类

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
 
    /**
     *缓存管理器.
     *@param redisTemplate
     *@return
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate<?,?>redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        cacheManager.setDefaultExpiration(3600);
        return cacheManager;
    }
 
 
    /**
     *自定义key.
     *此方法将会根据类名+方法名+所有参数的值生成唯一的一个key,即使@Cacheable中的value属性一样,key也会不一样。
     */
    @Override
    public KeyGenerator keyGenerator() {
        System.out.println("RedisCacheConfig.keyGenerator()");
        return new KeyGenerator(){
                 @Override
                 public Object generate(Object o, Method method, Object... objects ) {
                StringBuilder sb = new StringBuilder("Cache:BaseService");
                sb.append(":" + o.getClass().getName().toString());
                sb.append(":" + method.getName().toString());
 
                StringBuilder s = new StringBuilder();
                for (Object obj : objects) {
                    if (Objects.nonNull(obj)){
                        s.append(obj.toString());
                    }
                }
 
                StringBuilder testss = sb;
                sb.append(":" + StringEncryptionUtils.StringToMd5(s.toString()));
                return sb.toString();
            }
        };
    }
}

注解

Spring为我们提供了几个注解来支持Spring Cache。
其核心主要是@Cacheable、@CachePut和@CacheEvict。
使用@Cacheable标记的方法,如果未缓存,在执行后Spring Cache将缓存其返回结果;已缓存,则直接返回缓存内容;
使用@CachePut标记的必然会在方法执行后,更新缓存;
而使用@CacheEvict标记的方法会在方法执行前或者执行后移除Spring Cache中的某些元素。

1.1 @Cacheable

@Cacheable可以标记在一个方法上,也可以标记在一个类上。标记方法上表示该方法支持缓存,标记类上表示该类下所有方法都支持缓存。
对于一个支持缓存的方法,Spring会在其被调用后将其返回值缓存起来,以保证下次利用同样的参数来执行该方法时可以直接从缓存中获取结果,而不需要再次执行该方法。
spring以键值对形式缓存,key可以自定义设置,未设置则为默认值,value则是方法返回结果。@Cacheable可以指定三个属性:value、key和condition。
@Cacheable 常用与查询操作。

1.1.1 value指定cache缓存空间

value指定当前结果缓存在哪个cache下,value值可以是一个cache,或者多个cache

@Cacheable("goods")
public Goods find(Integer goodsId) {
  return null;
}
 
@Cacheable({"goods", "channel:goods"})
public Goods find(Integer goodsId) {
  return null;
}

1.1.2 指定cache的key值

设置缓存数据的key值,未设置则为默认值。

默认策略
默认的key生成策略是通过KeyGenerator生成的,其默认策略如下:
如果方法没有参数,则使用0作为key。
如果只有一个参数的话则使用该参数作为key。
如果参数多余一个的话则使用所有参数的hashCode作为key

自定义key

@Cacheable(value="goods", key="goodsId")
public Goods find(Integer goodsId) {
  return null;
}
 
 
@Cacheable(value="goods", key="goods.goodsId")
public Goods find(Goods goods) {
  return null;
}

前言caching配置中

@Override
public KeyGenerator keyGenerator() {
	System.out.println("RedisCacheConfig.keyGenerator()");
	return new KeyGenerator(){
			 @Override
			 public Object generate(Object o, Method method, Object... objects ) {
			StringBuilder sb = new StringBuilder("Cache:BaseService");
			sb.append(":" + o.getClass().getName().toString());
			sb.append(":" + method.getName().toString());
 
 
			StringBuilder s = new StringBuilder();
			for (Object obj : objects) {
				if (Objects.nonNull(obj)){
					s.append(obj.toString());
				}
			}
 
 
			StringBuilder testss = sb;
			sb.append(":" + StringEncryptionUtils.StringToMd5(s.toString()));
			return sb.toString();
		}
	};
}

1.1.3 condition 设置缓存条件

指定缓存方法上,添加缓存条件,当满足该条件时候,结果才进行缓存。

@Cacheable(value="goods", key="goods.goodsId", condition="goods.goodsId == 123456")
public Goods find(Goods goods) {
  return null;
}

1.2 @CachePut

@CachePut也可以声明一个方法支持缓存功能。与@Cacheable不同的是使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。
@CachePut也可以标注在类上和方法上。使用@CachePut时我们可以指定的属性跟@Cacheable是一样的(这边就不重复阐述)。
@CachePut常用与更新操作。

@CachePut(value="goods", key="goods.goodsId", condition="goods.goodsId == 123456")
public Goods update(Goods goods) {
  return null;
}

1.3@CacheEvict

@CacheEvict可以标记在一个方法上,也可以标记在一个类上。标记方法上标识方法执行时候触发清楚缓存操作,当标记在一个类上时表示其中所有的方法的执行都会触发缓存的清除操作。
@CacheEvict可以指定的属性有value、key、condition、allEntries和beforeInvocation。
其中value、key和condition的语义与@Cacheable对应的属性类似。主要阐述新出现的两个属性allEntries和beforeInvocation。
@CacheEvict常用删除操作。

1.3.1 allEntries属性

allEntries是boolean类型,表示是否需要清除缓存中的所有元素,默认为false。
当指定了allEntries为true时,Spring Cache将忽略指定的key。有的时候我们需要Cache一下清除所有的元素,这比一个一个清除元素更有效率。

@CacheEvict(value="goods", key="goods.goodsId", condition="goods.goodsId == 123456")
public void deleteGoods(Goods goods) {
}
 
 
@CacheEvict(value="goods", allEntries=true)
public void deleteAllGoods() {
}

1.3.2 beforeInvocation属性

清除操作默认是在对应方法成功执行之后触发的,即方法如果因为抛出异常而未能成功返回时也不会触发清除操作。
使用beforeInvocation可以改变触发清除操作的时间,当我们指定该属性值为true时,Spring会在调用该方法之前清除缓存中的指定元素。

@CacheEvict(value="goods", beforeInvocation=true)
public void deleteGoods(Goods goods) {
}

1.4 @Caching

@Caching注解可以让我们在一个方法或者类上同时指定多个Spring Cache相关的注解。其拥有三个属性:cacheable、put和evict,分别用于指定@Cacheable、@CachePut和@CacheEvict。
原文地址:https://www.cnblogs.com/katy0308/p/13781613.html