Redis单击缓存
和Ehcache一样,如果在classpath下存在Redis并且Redis已经配置好了,此时就是默认提供RedisCacheManager座位缓存提供者。Redis使用步骤如下:
1.创建项目 添加缓存依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>letture-core</artifactId>
</exclusion>
<exclusion>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</exclusion>
</exclusions>
2.缓存配置
Redis单击缓存只需要开发者在application.properties中进行Redis配置及缓存配置即可,代码如下:
# 缓存配置
spring.cache.cache.names=c1,c2
spriing.cache.redis.time-to-live=1800s
# Redis配置
spring.redis.database=0
spring.redis.host=192.168.86.129
spring.redis.port=6379
spring.redis.password=123456
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.max-wait=1ms
spring.redis.jedis.pool.min-idle=0
代码解释
第二行是配置缓存名称,Redis中的Key都有一个前缀,默认前缀就是“缓存名::”
第三行是配置缓存的有效期,即Redis中的Key的过期时期
第5-12行是Redis缓存配置,
3.开启缓存
接下来在项目入口类中开启缓存,代码如下:
@SpringBootApplication
public class RedisCacheApplication{
public static void main(String[] args) {
SpringApplication.run(RedisCacheApplication.class, args);
}
}
最后黄建BaseDao进行测试,如上一节一样,这里不再叙述
Redis集群缓存
不同于Redis单击缓存,Redis集群缓存会复杂一点主要体现在配置上,缓存的使用和Redis单击缓存介绍的一样,搭建Redis集群缓存主要分为三个步骤
1.搭建Redis集群;
2.配置缓存
3.使用缓存
1.配置缓存
当Redis集群搭建成功之后,并且能从Spring Boot 项目中访问集群后,只需要简单的Redis缓存配置即可:
@Configuration
public class RedisCacheConfig{
@Autowired
RedisConnectionFantory connectionFantory;
@Bean
RedisCacheManager redisCacheManager(){
Map<String,RedisCacheConfiguration> configmap = new HashMap<>();
RedisCacheConfiguration redisCacheConfig = RedisCacheConfiguration
.defaulCacheConfig()
.prefinKeyWith("sang:")
.disableCachingBullValues()
.entryTtl(Duration.ofMinutes(300));
configmap.put("c1",redisCacheConfig);
RedisCacheWriter cacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFantory);
RedisCacheManager redisCacheManager = new RedisCacheManager(cacheWriter,
RedisCacheConfiguration.defaulCacheConfig(),
configMap;)
return redisCacheManager;
}
}
代码解释:
- 在配置Redis集群时,已经向Spring容器中注册了一个JedisConnectionFactory的实例,这里将之注入到RedisCacheConfig配置文件中备用(RedisConnectionFactory是JedisConnectionFactory的父类)。
- 在RedisCacheConfig中提供RedisCacheManager的实例,该实例的构造需要三个参数,第一个参数是cacheWriter,直接通过nonLockingRedisCacheWriter方法构造出来即可;第二个参数默认的缓存配置,第三个参数是提前定义好的缓存配置。
- RedisCacheManager构造方法中第三个参数是提前定义好的缓存参数,它是一个Map类型的参数,该Map中的Key指缓存的名字, value是指该缓存所对应的缓存配置,例如Key的前缀、缓存过期的时间等,若缓存注解中使用的缓存名称不存在于Map中,则使用RedisCacheManager构造方法中的第二个参数所定义的缓存策略进行数据缓存,例如如下两个缓存配置:
@Cacheable(value = "c1")
@Cacheable(value = "c2")
第一行中的注解,c1存在于configMap集合中,因此使用的缓存策略是configMap集合中c1所对应的缓存策略,c2不存在于configMap集合中,因此使用的缓存策略是默认的缓存策略
本案例中默认缓存策略通过RedisCacheConfiguration中的defaultCacheConfig方法获取,该方法的源代码如下:
public static RedisCacheConfiguration defaltCacheConfig(){
...
...
return new RedisCacheConfiguration(Duration.ZERO,true,true,CacheKeyPrefix.simple(),
SerialirationPair.formSerializer(new StringRedisSerializer));
SerialirationPair.formSerializer(new JbkSerialirationRedisSerializer(),
conversionService);
}
有这一段代码可以看到,默认的缓存过期时间为0,即永不过期,第二个参数true表示可以存储null,第三个参数true表示开启Key的前缀,最后一个参数表示Key的默认前缀是"缓存名:"接下来的两个参数表示Key和value的序列化方式,最后一个参数则表示一个类型转换器。
- 8-2行表示一个自定义的缓存配置,第10设置了缓存的默认名称是“sang”,第11行禁止缓存一个null,第12行设置缓存的过期时间为30分钟。
2. 使用缓存
缓存设置完成后,接下来首先在项目启动类中通过@EnableCaching注解开启缓存,代码如下:
@Spring BootApplication
@EnableCaching
public class RedisclustercacheApplication{
public static void main(String[] args) {
SpringApplication.run(RedisCacheApplication.class, args);
}
}
然后创建一个BookDao,代码如下:
@Repository
public class BookDao{
@Cacheable(value = "c1")
public String getBookById(Integer id){
System.out.println(getBookBuId);
return "全新的肖申克的救赎";
}
@CachePut(value = "c1")
public String updateBookById(Book book){
System.out.println(updateBookBuId);
return "这是全新的肖申克的救赎";
}
@CacheEvict(value = "c1")
public void deleteBookById(Integer id){
System.out.println(deleteBookBuId);
}
@Cacheable(value = "c1")
public String getBookById2(Integer id){
System.out.println(getBookById2);
return "这本书是肖申克的救赎";
}
}
最后黄建单元测试,代码如下:
@RunWith(SpringRunner.class)
@Spring BootTest
public class RedisclustercacheApplicationTests{
@Autowired
BookDao bookDao;
@Test
public void contextLoads(){
bookDao.getBookById(100);
String book = booDao.getBookById(100);
System.out.println(book);
String book2 = booDao.getBookById(100);
System.out.println(book);
book.deleteById(100);
book.getBookById(100);
book.getBookById2(99);
}
}
}
由单元测试可以看到,一开始做了两次查询,但是查询的方法值调用了一次,因为第二次使用了缓存,接下来执行了缓存,当更新成功后再去查询,此时缓存已经更新成功,接下来执行删除,删除成功之后再去执行查询,查询方法又被调用,说明缓存已经被删除了,最后一个查询了id为99的记录这次使用的是默认的缓存配置,在Redis缓存服务器上也可以看到缓存结果。