Spring缓存:Spring Cache注解简化缓存

Spring Cache 是Spring 提供的一整套的缓存解决方案,它不是具体的缓存实现,它只提供一整套的接口和代码规范、配置、注解等

Spring Cache优化了缓存基础场景的逻辑代码,用注解规范了缓存代码

每次调用需要缓存功能的方法时, Spring 会检查指定参数的指定的目标方法是否已

经被调用过;如果有就直接从缓存中获取方法调用后的结果,如果没有就调用方法并缓

存结果后返回给用户。下次调用直接从缓存中获取。

完成这些的逻辑代码不需要我们自己写,Spring会自己识别

1、配置

1、依赖

<!--springcache依赖-->
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-cache</artifactId>
   </dependency>
   
<!--使用redis作为缓存-->
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-data-redis</artifactId>
   </dependency>

2、yml配置

spring:
  cache:
    type: redis #指定缓存类型为redis
 # redis配置
  redis:
    host: localhost
    port: 6379
    database: 2
    jedis:
      pool:
        max-active: -1
        max-wait: 3000ms
    timeout: 3000ms

3、cache配置

package com.example.demo.config;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.CacheOperation;
import org.springframework.cache.interceptor.CacheOperationSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.util.*;

import java.time.Duration;
import java.util.*;

@EnableCaching
@Configuration
public class SpringCacheConfig implements ApplicationContextAware {


	private Set<String> cacheNames = new HashSet<>();

	private static final String SEPARATOR = "#";

	@Bean
	public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
		//默认过期时间2天
		RedisCacheConfiguration defaultConfiguration = getRedisCacheConfigurationWithTtl(2 * 24 * 3600);
		RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager
				.builder(connectionFactory)
				.cacheDefaults(defaultConfiguration);
		if (!CollectionUtils.isEmpty(cacheNames)) {
			Map<String, RedisCacheConfiguration> cacheConfigurations = new LinkedHashMap<>();
			for (String cacheName : cacheNames) {
				if (cacheName.contains(SEPARATOR)) {
					String[] strs = StringUtils.split(cacheName, SEPARATOR);
					Assert.notNull(strs);
					long ttl = Long.parseLong(strs[1].trim());
					RedisCacheConfiguration customizedConfiguration = getRedisCacheConfigurationWithTtl(ttl);
					cacheConfigurations.put(cacheName, customizedConfiguration);
				}
			}
			if (cacheConfigurations.size() > 0) {
				builder.withInitialCacheConfigurations(cacheConfigurations);
			}
		}
		return builder.build();

	}

	private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(long ttl) {
		return RedisCacheConfiguration
				.defaultCacheConfig()
				.disableCachingNullValues()
				.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
				.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
				.entryTtl(Duration.ofSeconds(ttl));
	}

	//实现ApplicationContextAware接口的Bean会被提前实例化,这个方法会优先执行
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		if (!(applicationContext instanceof ConfigurableApplicationContext)) {
			return;
		}
		ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext;
		//CacheOperationSource 可以被提前实例化,是spring cache提供的工具类
		CacheOperationSource cacheOperationSource = context.getBean(CacheOperationSource.class);
		ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
		for (String beanName : beanFactory.getBeanDefinitionNames()) {
			AbstractBeanDefinition beanDefinition = (AbstractBeanDefinition) beanFactory.getBeanDefinition(beanName);
			try {
				Class<?> beanClass = beanDefinition.resolveBeanClass(ClassUtils.getDefaultClassLoader());
				if (beanClass != null) {
					ReflectionUtils.doWithMethods(beanClass, m -> {
								Collection<CacheOperation> cacheOperations = cacheOperationSource.getCacheOperations(m, beanClass);
								if (!CollectionUtils.isEmpty(cacheOperations)) {
									for (CacheOperation operation : cacheOperations) {
										cacheNames.addAll(operation.getCacheNames());
									}
								}
							}
					);
				}
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}
}

2、注解

  • @EnableCaching (开启缓存功能)

开启缓存,缓存才能生效
直接启动类上开启

在这里插入图片描述

 @Cacheable (将数据保存到缓存)

根据方法返回结果进行缓存,下次请求时,如果缓存存在,则直接读取缓存数据返回;如果缓存不存在,则执行方法,并把返回的结果存入缓存中。一般用在查询方法上。

拥有属性:

属性名解释
value缓存名,必填,它指定了你的缓存存放在哪块命名空间(就是文件夹名),可多个
cacheNames与 value 差不多,二选一即可
key可选属性,可以使用 SpringEL 标签自定义缓存的key
keyGeneratorkey的生成器。key/keyGenerator二选一使用
cacheManager指定缓存管理器
cacheResolver指定获取解析器
condition条件符合则缓存
unless条件符合则不缓存
sync是否使用异步模式,默认为false

1、key参数设置

在这里插入图片描述 

默认方法解析:

  • 如果缓存中有,方法不用调用
  • key默认自动生成,缓存名字::SimpleKey []

此时的key就是code的值 ,value就是方法的返回值

  • @CacheEvict (将数据从缓存删除)

使用该注解标志的方法,会清空指定的缓存。一般用在更新或者删除方法上

属性名解释
value缓存名,必填,它指定了你的缓存存放在哪块命名空间(就是文件夹名),可多个
cacheNames与 value 差不多,二选一即可
key可选属性,可以使用 SpringEL 标签自定义缓存的key
keyGeneratorkey的生成器。key/keyGenerator二选一使用
cacheManager指定缓存管理器
cacheResolver指定获取解析器
condition条件符合则缓存
allEntries是否清空所有缓存,默认为false。如果指定为true,则方法调用后将立即清空所有缓存
beforeInvocation是否在方法执行前就清空,默认为false。如果指定为true,则在方法执行前就会清空缓存

@CacheEvict(value = {"cacheable1"},key ="'123'",allEntries = true,beforeInvocation = true)

@CachePut (不影响方法执行更新缓存)

使用该注解标志的方法,每次都会执行,并将结果存入指定的缓存中,会更新缓存的值。其他方法可以直接从响应的缓存中读取缓存数据,而不需要再去查询数据库。一般用在新增修改方法上。

拥有属性:

属性名解释
value缓存名,必填,它指定了你的缓存存放在哪块命名空间(就是文件夹名),可多个
cacheNames与 value 差不多,二选一即可
key可选属性,可以使用 SpringEL 标签自定义缓存的key
keyGeneratorkey的生成器。key/keyGenerator二选一使用
cacheManager指定缓存管理器
cacheResolver指定获取解析器
condition条件符合则缓存
unless条件符合则不缓存
@CachePut(value = {"cacheable1"},key ="'123'")

@CacheConfig (在类级别共享缓存的相同配置)

当我们需要缓存的地方越来越多,你可以使用@CacheConfig(cacheNames = {“cacheName”})注解在 class 之上来统一指定value的值,这时可省略value,如果你在你的方法依旧写上了value,那么依然以方法的value值为准。

拥有属性:

属性名解释
cacheNames与 value 差不多,二选一即可
keyGeneratorkey的生成器。key/keyGenerator二选一使用
cacheManager指定缓存管理器
cacheResolver指定获取解析器

@CacheConfig(cacheNames = {"cacheName"})

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yang疯狂打码中

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值