springboot cache redis 缓存

时间:2022-05-04
本文章向大家介绍springboot cache redis 缓存,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

上一节学习spring的cache缓存,介绍了spring缓存的基础:

https://cloud.tencent.com/developer/article/1060047

现在学习使用redis实现缓存:

1. 指定provider可以使用配置:

2. redis在这里充当缓存提供者的角色(cache provider),上节中没有明显指定cache provider,则会按顺序查找以下的provider:

3. 若没有查找到前9类缓存的cacheManager,则会使用最后一个simple缓存,也就是在内存中使用ConcurrentHashMap实现缓存。spring官方建议生产环境中勿使用simple缓存。上一篇就是使用这个cache provider。

4. 使用redis作为cache provider, 只需要依赖spring-boot-starter-data-redis,spring就会找到redisCacheManager,就可以使用redis作为缓存。其中redis的默认配置如下:

spring.redis.host=localhost
spring.redis.port=6379
# 第0个database
spring.redis.database=0
# 默认密码为空
spring.redis.password=
spring.redis.pool.max-active=8
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-wait=-1
spring.redis.ssl=false
spring.redis.timeout=0
#spring.redis.cluster.max-redirects=
#spring.redis.cluster.nodes=

5. windows 搭建 redis

    下载后windows版本的redis如下:

    运行start.bat就是 使用redis.windows.conf配置 来启动 redis-server.exe

6. 启动redis后,运行上一节的测试代码,就可以看到redis的窗口出现读写的输出。

    注意:实体类一定要实现serializable接口。

    redis在数据库重启,或应用程序重启后,写在redis中的缓存还是存在的,但我们可以通过实体类中的时间来判断数据是否是从缓存中读取的。

    例如,图中是我重启后第一次运行测试程序,但时间显示却是五分钟之前,所以这是从缓存中读取的。