前言

本文实现了SpringCache + Redis的集中式缓存,方便大家对学习了解缓存的使用。

本文实现:

  • SpringCache + Redis的组合
  • 通过配置文件实现了自定义key过期时间;key命名方式;value序列化方式

实现本文代码的前提:

  • 已有一个可以运行的Springboot项目,实现了简单的CRUD功能

步骤

在Spring Boot中通过@EnableCaching注解自动化配置合适的缓存管理器(CacheManager),Spring Boot根据下面的顺序去侦测缓存提供者:

Generic
JCache (JSR-107)
EhCache 2.x
Hazelcast
Infinispan
Redis
Guava
Simple
复制代码

我们所需要做的就是实现一个将缓存数据放在Redis的缓存机制。

  • 添加pom.xml依赖
    <!-- 缓存: spring cache --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency><!-- 缓存: redis --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>
复制代码

注意:- spring-boot-starter-data-redis和spring-boot-starter-redis的区别:blog.csdn.net/weixin_3852…

可以看出两个包并没有区别,但是当springBoot的版本为1.4.7 以上的时候,spring-boot-starter-redis 就空了。要想引入redis就只能选择有data的。

  • application.properties中加入redis连接设置(其它详细设置请查看参考网页)
# Redis
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.database=0
spring.redis.password=xxx
复制代码
  • 新增KeyGeneratorCacheConfig.java(或者名为CacheConfig)文件

该文件完成三项设置:key过期时间;key命名方式;value序列化方式:JSON便于查看

package com.pricemonitor.pm_backend;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;import java.lang.reflect.Method;@Configuration
public class KeyGeneratorCacheConfig extends CachingConfigurerSupport {private final RedisTemplate redisTemplate;@Autowiredpublic KeyGeneratorCacheConfig(RedisTemplate redisTemplate) {this.redisTemplate = redisTemplate;}@Overridepublic CacheManager cacheManager() {// 设置key的序列化方式为StringredisTemplate.setKeySerializer(new StringRedisSerializer());// 设置value的序列化方式为JSONGenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);// 设置默认过期时间为600秒cacheManager.setDefaultExpiration(600);return cacheManager;}/*** key值为className+methodName+参数值列表* @return*/@Overridepublic KeyGenerator keyGenerator() {return new KeyGenerator() {@Overridepublic Object generate(Object o, Method method, Object... args) {StringBuilder sb = new StringBuilder();sb.append(o.getClass().getName()).append("#");sb.append(method.getName()).append("(");for (Object obj : args) {if(obj != null) { // 在可选参数未给出时时,会出现null,此时需要跳过sb.append(obj.toString()).append(",");}}sb.append(")");return sb.toString();}};}
}复制代码
  • 在serviceImpl中加入@CacheConfig并且给给每个方法加入缓存(详细注解使用请查看参考网页)
@Service
@CacheConfig(cacheNames = "constant")
public class ConstantServiceImpl implements ConstantService {@Autowiredprivate ConstantMapper constantMapper;@Cacheable@Overridepublic List<Constant> alertMessage() {ConstantExample constantExample = new ConstantExample();ConstantExample.Criteria criteria = constantExample.createCriteria();criteria.andTypeEqualTo("alert");return constantMapper.selectByExample(constantExample);}@Cacheable@Overridepublic List<Constant> noteMessage() {ConstantExample constantExample = new ConstantExample();ConstantExample.Criteria criteria = constantExample.createCriteria();criteria.andTypeEqualTo("note");return constantMapper.selectByExample(constantExample);}@Cacheable@Overridepublic List<Constant> banner() {ConstantExample constantExample = new ConstantExample();ConstantExample.Criteria criteria = constantExample.createCriteria();criteria.andTypeEqualTo("banner");return constantMapper.selectByExample(constantExample);}
}
复制代码

效果图

注意事项

  • 若直接修改数据库的表,并没有提供接口修改的字段,缓存就没法更新。所以这种字段加缓存需要尤其注意缓存的有效性,最好让其及时过期。或者给其实现增删改接口。

  • 大坑:在可选参数未给出时时,会出现null,此时在生成Key名的时候需要跳过。已在代码中修改

for (Object obj : args) {if(obj != null) { // 在可选参数未给出时时,会出现null,此时需要跳过sb.append(obj.toString()).append(",");}
}
复制代码

参考

缓存入门:blog.didispace.com/springbootc…

Redis集中式缓存:blog.didispace.com/springbootc…

代码实现:(经典好用,有小bug):zhuanlan.zhihu.com/p/30540686

代码实现(可参考):www.jianshu.com/p/6ba2d2dbf…

[Springboot]SpringCache + Redis实现数据缓存相关推荐

  1. springboot redis 刷新时间_「SpringBoot实战」SpringCache + Redis实现数据缓存

    关注我的微信公众号:后端技术漫谈 不定期推送关于后端开发.爬虫.算法题.数据结构方面的原创技术文章,以及生活中的逸闻趣事. 我目前是一名后端开发工程师.主要关注后端开发,数据安全,网络爬虫,物联网,边 ...

  2. spring-boot 整合redis作为数据缓存

    添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>sp ...

  3. SpringBoot 结合 Spring Cache 操作 Redis 实现数据缓存

    点击上方"后端技术精选",选择"置顶公众号" 技术文章第一时间送达! 作者:超级小豆丁 http://www.mydlq.club/article/55/ 系统 ...

  4. SpringBoot+Redis完成数据缓存(内容丰富度一定超出你的想象)

    SpringBoot+Redis完成数据缓存 去年今日此门中 人面桃花相映红 人面不知何处去 桃花依旧笑春风 感谢相遇!感谢自己,努力的样子很给力! 为了更多朋友看见,还是和大家说一声抱歉,限制为粉丝 ...

  5. spring boot 缓存_Spring Boot 集成 Redis 实现数据缓存

    Spring Boot 集成 Redis 实现数据缓存,只要添加一些注解方法,就可以动态的去操作缓存了,减少代码的操作. 在这个例子中我使用的是 Redis,其实缓存类型还有很多,例如 Ecache. ...

  6. 【Java项目中 利用Redis实现数据缓存】

    文章目录 Java SpringBoot项目中 用Redis实现数据缓存 1 环境搭建 1.1 maven坐标 1.2 配置文件 1.3 配置类 2 实现缓存短信验证码 3 缓存菜品数据 4 Spri ...

  7. Spring整合Redis做数据缓存(Windows环境)

    当我们一个项目的数据量很大的时候,就需要做一些缓存机制来减轻数据库的压力,提升应用程序的性能,对于java项目来说,最常用的缓存组件有Redis.Ehcache和Memcached. Ehcache是 ...

  8. redis lettuce 超时_Spring Cache 操作 Redis 实现数据缓存(上)

    点击上方☝SpringForAll社区 轻松关注!及时获取有趣有料的技术文章 本文来源:http://www.mydlq.club/article/55/ . 一.缓存概念知识 . 1.是什么缓存 . ...

  9. SpringBoot 项目实战 ~ 9.数据缓存

    和所有以梦为马的诗人一样 我选择永恒的事业 我的事业 就是要成为太阳的一生 - - 海子 一.环境搭建 1. 数据缓存的意义 由于移动端是面向所有的消费者的,请求压力相对比较大,而我们当前所有的数据查 ...

最新文章

  1. 【转】RelativeLayout和LinearLayout及FrameLayout性能分析
  2. 【ES6】Proxy对象
  3. [转载] 大道至简:软件工程实践者的思想——第四章 流于形式的沟通
  4. 理解JavaScript原型链
  5. ctb伺服驱动器说明书_青岛FANUC伺服电机364、453故障维修
  6. Caused by: java.lang.NoClassDefFoundError: org/springframework/aop/TargetSource
  7. 【C#】获取网页内容及HTML解析器HtmlAgilityPack的使用
  8. Websocket--- long loop--ajax轮询
  9. C语言试题八十八之实现选冒泡排序算法
  10. 删除元素值最大的结点
  11. Linux学习笔记---初次编译Uboot系统
  12. python怎么清理垃圾_python清理内存
  13. bootstrap 轮播控制时间_【前端冷知识】如何封装一个图片轮播组件
  14. 【leetcode刷题笔记】Restore IP Addresses
  15. 树和二叉树总结(三)—BST二叉排序树
  16. HART协议命令与UART串口解析
  17. 平方米的计算机公式,计算平方的公式 各类计算公式
  18. JBOSS启动错误:Not pointing to a directory
  19. livp后缀文件图片怎么打开,在电脑怎么打开live照片批量转换?
  20. HDMI-CEC功能之System Audio Control

热门文章

  1. 解决 pathForResource 返回 nil的问题
  2. PHP——0128练习相关2——js点击button按钮跳转到另一个新页面
  3. Algorithm -- 全排列
  4. UITextView自定义placeholder功能:用一个label写了文字,然后当检测到长度不为0的时候就把label隐藏...
  5. JDK源码-ArrayList源码
  6. 巧用gmail转发邮件
  7. 安装完VS2010之后再安装VS2012以后,发现VS工程编译出现--fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
  8. 分表扩展全局序列实际操作_高可用_单表存储千万级_海量存储_分表扩展---MyCat分布式数据库集群架构工作笔记0026
  9. Netty工作笔记0025---SocketChannel API
  10. Python工作笔记007---win10安装Python3.7.3_以及用pycharm创建Python项目_以及对System interpreter理解