Redis缓存的适用场景
- 读操作比较多
- 存在热数据
- 响应时效需求较高
- 一致性要求不严格
- 实现分布式锁
应用层访问缓存的模式
- 双读双写:这是最常用的缓存服务架构
读操作:先去缓存中读取数据,缓存中不存在,就去数据库中读取,再将从数据库中读取的数据写入缓存
写操作:先写数据库,再写缓存。
这种方式实现简单,但是对应用层不透明,应用层需要处理读写顺序的逻辑 - 异步更新架构
应用层只读缓存,异步更新服务将数据库的变更或者新增的数据更新到缓存中
1、在pom文件夹下添加redis依赖
<!-- 加载spring boot redis包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、在application.peroperties核心配置文件中配置Redis的连接信息
#redis配置信息
spring.redis.host=192.168.25.128
spring.redis.port=6379
3、查看RedisAutoConfiguration可以看到,SpringBoot默认为我们添加了
RedisTemplate<Object, Object> template和StringRedisTemplate template
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
@ConditionalOnMissingBean
public StringRedisTemplate stringRedisTemplate(
RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
4、RedisTemplate的API介绍
Redis的五大数据类型
String(字符串)、List(列表)、Set(集合)、Hash(散列)、ZSet(有序集合)
5、使用Redis缓存
@Service
@Transactional
public class BookServiceImpl implements BookService{
@Autowired
private RedisTemplate<Object,Book> redisTemplate;
@Autowired
private BookMapper bookMapper;
public Book findBookById(Integer id) {
//从缓存中获取
Book book = redisTemplate.opsForValue().get(id);
//双重检测
if(book == null) {
synchronized (this) {
//再去Redis中读取一次
book = redisTemplate.opsForValue().get(id);
if(book == null) {
System.out.println("从数据库中查询放到缓存中");
//从数据库中查询并添加进缓存
book = bookMapper.selectByPrimaryKey(id);
redisTemplate.opsForValue().set(book.getId(), book);
}
}
}else {
System.out.println("从缓存中获取");
}
return book;
}
}
6、自己配置Redistemplate,更改Spring boot注入Redistemplate的一些默认配置,比如修改序列化
/**
* @author WangZX
* @create 2018-09-20 11:03
*/
@Configuration
public class MyRedisConfig {
@Bean
public RedisTemplate<Object, Book> redisTemplate(
RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
RedisTemplate<Object, Book> template = new RedisTemplate<Object, Book>();
template.setConnectionFactory(redisConnectionFactory);
//配置序列化
FastJsonRedisSerializer<Book> serializer = new FastJsonRedisSerializer<Book>(Book.class);
template.setDefaultSerializer(serializer);
return template;
}
}
可以看到redisTemplate的默认序列化被修改了
7、集群哨兵模式的配置
#哨兵模式redis集群配置:
spring.redis.sentinel.master=mymaster
spring.redis.sentinel.nodes=192.168.25.128:26380,192.168.25.128:26382,192.168.25.128:26384