springboot(九) Cache缓存和Redis缓存

1. Cache缓存

1.1 缓存的概念&缓存注解

Cache

缓存接口,定义缓存操作。实现有:RedisCacheEhCacheCacheConcurrentMapCache

CacheManager

缓存管理器,管理各种缓存(Cache)组件

@Cacheable

主要针对方法配置,能够根据方法的请求参数对其结果进行缓存

@CacheEvict

清空缓存

@CachePut

保证方法被调用,又希望结果被缓存。

@EnableCaching

开启基于注解的缓存

keyGenerator

缓存数据时key生成策略

serialize

缓存数据时value序列化策略

1.2 @Cacheable/@CachePut/@CacheEvict 主要的参数

value

缓存的名称,在 spring 配置文件中定义,必须指定至少一个

例如:
@Cacheable(value=”mycache”) 或者 
@Cacheable(value={”cache1”,”cache2”}

key

缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合

例如:
@Cacheable(value=”testcache”

,key=”#userName”)

condition

缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存/清除缓存,在调用方法之前之后都能判断

例如:
@Cacheable(value=”testcache”,
condition=”#userName.length()>2”)

allEntries

(@CacheEvict )

是否清空所有缓存内容,缺省为 false,如果指定为 true,则方法调用后将立即清空所有缓存

例如:
@CachEvict(value=”testcache”,

allEntries=true)

beforeInvocation

(@CacheEvict)

是否在方法执行前就清空,缺省为 false,如果指定为 true,则在方法还没有执行的时候就清空缓存,缺省情况下,如果方法执行抛出异常,则不会清空缓存

例如:

@CachEvict(value=”testcache”,beforeInvocation=true)

unless

(@CachePut)

(@Cacheable)

用于否决缓存的,不像condition,该表达式只在方法执行之后判断,此时可以拿到返回值result进行判断。条件为true不会缓存,fasle才缓存

例如:
@Cacheable(value=”testcache”,

unless=”#result == null”)

2.Redis缓存

2.1 安装Redis,通过Docker安装,安装比较慢的话可以使用国内的镜像加速

> docker pull registry.docker-cn.com/library/redis

2.2 启动Redis

> docker run -d -p 6379:6379 --name brianRedis registry.docker-cn.com/library/redis

2.3 加入Redis的依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

 

2.4 Redis的数据操作

Redis常见的五大数据类型
​
/String字符串
stringRedisTemplate.opsForValue()
/List 列表
stringRedisTemplate.opsForList()
/Set 集合
stringRedisTemplate.opsForSet()
/Hash散列
stringRedisTemplate.opsForHash()
/ZSet有序集合    
stringRedisTemplate.opsForZSet()  

springBoot默认的是引用Cache缓存,如果pom里面引入了spring-boot-starter-data-redis,下面的@ConditionalOnMissingBean(value = CacheManager.class, name = "cacheResolver")条件生效,默认的缓存配置类将不会加载,所以就直接过度到redis了,依旧是使用@Cacheable ,@CachePut,@CacheEvict,@Caching,@CacheConfig操作缓存

@Configuration
@ConditionalOnClass(CacheManager.class)
@ConditionalOnBean(CacheAspectSupport.class)
@ConditionalOnMissingBean(value = CacheManager.class, name = "cacheResolver")
@EnableConfigurationProperties(CacheProperties.class)
@AutoConfigureBefore(HibernateJpaAutoConfiguration.class)
@AutoConfigureAfter({ CouchbaseAutoConfiguration.class, HazelcastAutoConfiguration.class,
        RedisAutoConfiguration.class })
@Import(CacheConfigurationImportSelector.class)
public class CacheAutoConfiguration {
    ........
}
posted @ 2018-10-11 16:47  Brian_Huang  阅读(795)  评论(0编辑  收藏  举报