文章目录
通过本文章,可以完成多级缓存架构中的Redis缓存。
一、Redis服务
在docker/docker-compose.ym
l中,添加redis服务块
redis:
container_name: redis
image: redis:7.2
volumes:
- ./redis/redis.conf:/usr/local/etc/redis/redis.conf
ports:
- "6379:6379"
command: ["redis-server", "/usr/local/etc/redis/redis.conf"]
networks:
multi-cache:
ipv4_address: 172.30.3.21
二、Redis缓存预热
在spirngboot
项目启动时,将固定的热点数据提前加载到redis
中。
1. 引入依赖
pom.xml
添加如下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
<version>6.1.4.RELEASE</version> <!-- 或更高版本 -->
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2 -->
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.41</version>
</dependency>
application.yml
添加如下配置
spring:
redis:
host: 172.30.3.21
2. handler类实现
新建config.RedisHandler
类,内容如下,主要是重写afterPropertiesSet
,完成缓存预热逻辑,saveItem
和deleteItemById
函数给之后的章节使用。
@Component
public class RedisHandler implements InitializingBean {
@Autowired
private StringRedisTemp