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 ...
随机推荐
- JS跨域:2.解决方案之-设置回调参数
一 服务器端代码 package com.cn; import java.util.List; import javax.servlet.http.HttpServletRequest; import ...
- CSS定位使用方法
.box0 { width: 200px; height: 200px; position: relative; background: #cfa } .box0-1,.box0-2 { width: ...
- Oracle12c中SQL优化(SQL TUNING)新特性之SQL计划指令
SQL计划指令是Oracle12c中自适应查询优化的功能之一.SQL计划指令就像“额外的提醒” ,用以提醒优化器你先前选择了的计划并不是最优的,典型的是因为错误的势评估.错误的势评估往往是由统计信息缺 ...
- 浅谈java中的"=="和eqals区别
在初学Java时,可能会经常碰到下面的代码: 1 String str1 = new String("hello"); 2 String str2 = new String(&qu ...
- OVMF基础
什么是OVMF The Open Virtual Machine Firmware (OVMF) project aims to support firmware for Virtual Machin ...
- Hadoop是一种开源的适合大数据的分布式存储和处理的平台
"Hadoop能做什么?" ,概括如下: 1)搜索引擎:这也正是Doug Cutting设计Hadoop的初衷,为了针对大规模的网页快速建立索引: 2)大数据存储:利用Hadoop ...
- float的范围和有效位
首先说一下: 范围是3.4E-38 ——3.4E+38,可提供7位有效数字. 上述这两个量都是近似值,各个编译器不太一样的. 下面我就将标准值是怎么定义的,和你说一下: 这个比较复杂,建议你找一下IE ...
- SSM-MyBatis-11:Mybatis中查询全部用resultmap
------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 实体类很普通,四个字段,编号,名字,作者名,价格 在接口中的方法声明如下 //查全部 public List& ...
- 。net加密解密相关方法
AES加密及解密 声明密钥级偏移向量--------/// <summary> /// 加密密钥 /// </summary> private static readonly ...
- Latex appendix 生成附录A和B
第一种: \documentclass[a4paper,12pt]{cctart} \begin{document} main body %正文内容 \appendix \renewc ...