spring boot redis 数据库缓存用法
缓存处理方式应该是
1.先从缓存中拿数据,如果有,直接返回。
2.如果拿到的为空,则数据库查询,然后将查询结果存到缓存中。
由此实现方式应该如下:
private String baseKey = "category";
public CmfCategories selectByPrimaryKey(Long id) {
//1. 先从缓存中取
CmfCategories cmfCategories = redisUtils.get(baseKey + id, CmfCategories.class);
if (cmfCategories == null) { //如果取值为空
//2. 从数据中查询
cmfCategories = cmfCategoriesMapper.selectByPrimaryKey(id);
//3. 将查询结果存入缓存
redisUtils.set(baseKey + id, cmfCategories, DEFAULT_EXPIRE * 7);
}
return cmfCategories;
}
这种方式是没错的,但就是实现起来,每个接口都要做一遍重复的操作,下面演示一种简洁的使用注解实现方式:
@Cacheable(value = "newsCategory", key = "'newsCategory:'+#id", unless = "#result==null")
public CmfCategories selectByPrimaryKey(Long id) {
return cmfCategoriesMapper.selectByPrimaryKey(id);
}
明显简单多了,而且**对代码无侵入**!
实现步骤
添加maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
添加配置
/**
* Redis缓存配置。
*/
@Configuration
@EnableCaching
public class RedisCacheConfig { @Autowired
private RedisConnectionFactory factory; @Bean
public CacheManager cacheManager() {
RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate());
// 默认缓存一天 86400秒
redisCacheManager.setDefaultExpiration(86400L);
return redisCacheManager;
} @Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
// 字符串Key序列化
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
// 对象值序列化
ObjectRedisSerializer objectRedisSerializer = new ObjectRedisSerializer();
redisTemplate.setValueSerializer(objectRedisSerializer);
redisTemplate.setHashValueSerializer(objectRedisSerializer);
return redisTemplate;
} }
具体使用
在需要缓存的接口上添加注解
@Cacheable(value = "newsCategory", key = "'newsCategory:'+#id", unless = "#result==null")
public CmfCategories selectByPrimaryKey(Long id) {
return cmfCategoriesMapper.selectByPrimaryKey(id);
}
当被缓存的数据被更新的时候,可以使用@CacheEvict来清除缓存,则可以保证缓存的数据是最新的
@CacheEvict(value = "User", key = "'User:'+#userParam.userId", condition = "#userParam!=null")
public long setUserBasicInfo(UserBasicInfo userParam, String token) {
//do something
}
如果要通过value区分,那就再手动用一下#root.caches,向spring表明,我们要用value所表示的缓存名来区分具体的缓存实体;
具体用法示例:
当方法的value属性进行了设置(如@Cacheable(value={"cache1", "cache2"})),则有两个cache;
此时可以使用@Cacheable(value={"cache1", "cache2"},key="#root.caches[0].name"),意思就是使用value为“cache1”的缓存;
简单讲解
参考链接
缓存数据
对于缓存的操作,主要有:@Cacheable、@CachePut、@CacheEvict。
@Cacheable
Spring 在执行 @Cacheable 标注的方法前先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,执行该方法并将方法返回值放进缓存。 参数: value缓存名、 key缓存键值、 condition满足缓存条件、unless否决缓存条件
@Cacheable(value = "user", key = "#id")
public User findById(final Long id) {
System.out.println("cache miss, invoke find by id, id:" + id);
for (User user : users) {
if (user.getId().equals(id)) {
return user;
}
}
return null;
}
@CachePut
和 @Cacheable 类似,但会把方法的返回值放入缓存中, 主要用于数据新增和修改方法。
@CachePut(value = "user", key = "#user.id")
public User save(User user) {
users.add(user);
return user;
}
@CacheEvict
方法执行成功后会从缓存中移除相应数据。 参数: value缓存名、 key缓存键值、 condition满足缓存条件、 unless否决缓存条件、 allEntries是否移除所有数据(设置为true时会移除所有缓存)
@CacheEvict(value = "user", key = "#user.id") // 移除指定key的数据
public User delete(User user) {
users.remove(user);
return user;
} @CacheEvict(value = "user", allEntries = true) // 移除所有数据
public void deleteAll() {
users.clear();
}
spring boot redis 数据库缓存用法的更多相关文章
- Spring Boot Redis 分布式缓存的使用
一.pom 依赖 <!-- 分布式缓存 --> <dependency> <groupId>org.springframework.boot</groupId ...
- spring boot redis缓存JedisPool使用
spring boot redis缓存JedisPool使用 添加依赖pom.xml中添加如下依赖 <!-- Spring Boot Redis --> <dependency> ...
- spring boot redis 缓存(cache)集成
Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...
- Spring Boot 自带缓存及结合 Redis 使用
本文测试环境: Spring Boot 2.1.4.RELEASE + Redis 5.0.4 + CentOS 7 自带缓存 如果没有使用缓存中间件,Spring Boot 会使用默认的缓存,我们只 ...
- Spring Boot 入门之缓存和 NoSQL 篇(四)
原文地址:Spring Boot 入门之缓存和 NoSQL 篇(四) 博客地址:http://www.extlight.com 一.前言 当系统的访问量增大时,相应的数据库的性能就逐渐下降.但是,大多 ...
- Spring Boot中使用缓存
Spring Boot中使用缓存 随着时间的积累,应用的使用用户不断增加,数据规模也越来越大,往往数据库查询操作会成为影响用户使用体验的瓶颈,此时使用缓存往往是解决这一问题非常好的手段之一. 原始的使 ...
- Spring Boot中的缓存支持(一)注解配置与EhCache使用
Spring Boot中的缓存支持(一)注解配置与EhCache使用 随着时间的积累,应用的使用用户不断增加,数据规模也越来越大,往往数据库查询操作会成为影响用户使用体验的瓶颈,此时使用缓存往往是解决 ...
- spring boot访问数据库
1. Spring JAP 基本使用说明: Spring boot 访问数据库基本上都是通过Spring JPA封装的Bean作为API的,Spring JPA 将访问数据库通过封装,只要你的类实现了 ...
- Spring Boot 项目学习 (三) Spring Boot + Redis 搭建
0 引言 本文主要介绍 Spring Boot 中 Redis 的配置和基本使用. 1 配置 Redis 1. 修改pom.xml,添加Redis依赖 <!-- Spring Boot Redi ...
随机推荐
- Spring-mvc设置@RequestMapping标签更改返回头及@RequestMapping简述
1. 引子:设置返回头 2. 简述 3. value 4. method 5. consumes/produces 6. params 7. headers 1. 引子:设置返回头 返回JSON内容时 ...
- jquery和ajax的关系详细介绍【转】
jquery和ajax的关系详细介绍 http://www.jb51.net/article/43965.htm
- C/C++静态代码安全检查工具
静态代码安全检查工具是一种能够帮助程序员自动检测出源程序中是否存在安全缺陷的软件.它通过逐行分析程序的源代码,发现软件中潜在的安全漏洞.本文针对 C/C++语言程序设计中容易存在的多种安全问题,分别分 ...
- jieba库分词词频统计
代码已发至github上的python文件 词频统计结果如下(词频为1的词组数量已省略): {'是': 5, '风格': 4, '擅长': 4, '的': 4, '兴趣': 4, '宣言': 4, ' ...
- HiJson(Json格式化工具)64位中文版下载 v2.1.2
链接:https://pan.baidu.com/s/15gMvig15iUjpqSX7nUZ-5Q 密码:8086
- PAT1102: Invert a Binary Tree
1102. Invert a Binary Tree (25) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue ...
- Linux时间子系统之八:动态时钟框架(CONFIG_NO_HZ、tickless)
在前面章节的讨论中,我们一直基于一个假设:Linux中的时钟事件都是由一个周期时钟提供,不管系统中的clock_event_device是工作于周期触发模式,还是工作于单触发模式,也不管定时器系统是工 ...
- Bitmap对图像的处理
p { margin-bottom: 0.1in; line-height: 120% } a:link { } Bitmap对图像的处理 一.引言: 在开发中涉及到图片包括.png,.gif,.9. ...
- 静态代码扫描工具PMD定制xml的规则(一)操作篇
0.前言 PMD作为开源的静态代码扫描工具有很强的扩展能力,可使用java或xpath定制rule.第一篇从操作上讲解如何定制一个用于扫描xml是否规范的规则.首先我们知道xml格式的文件在java工 ...
- 思维导图软件比较-FREEMIND,XMIND,Mindjet Mindmanager
https://www.zhihu.com/question/22094277