前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >spring boot redis 数据库缓存用法

spring boot redis 数据库缓存用法

作者头像
爱撸猫的杰
发布2019-05-08 11:10:49
9340
发布2019-05-08 11:10:49
举报
文章被收录于专栏:爱撸猫的杰爱撸猫的杰

缓存处理方式应该是

1.先从缓存中拿数据,如果有,直接返回。 2.如果拿到的为空,则数据库查询,然后将查询结果存到缓存中。 由此实现方式应该如下:

代码语言:javascript
复制
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;
}

这种方式是没错的,但就是实现起来,每个接口都要做一遍重复的操作,下面演示一种简洁的使用注解实现方式:

代码语言:javascript
复制
@Cacheable(value = "newsCategory", key = "'newsCategory:'+#id", unless = "#result==null")
public CmfCategories selectByPrimaryKey(Long id) {
  return cmfCategoriesMapper.selectByPrimaryKey(id);
}

明显简单多了,而且**对代码无侵入**!

实现步骤 添加maven依赖

代码语言:javascript
复制
<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缓存配置。 */

代码语言:javascript
复制
@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;
}



}

具体使用 在需要缓存的接口上添加注解

代码语言:javascript
复制
@Cacheable(value = "newsCategory", key = "'newsCategory:'+#id", unless = "#result==null")
public CmfCategories selectByPrimaryKey(Long id) {
return cmfCategoriesMapper.selectByPrimaryKey(id);
}

当被缓存的数据被更新的时候,可以使用@CacheEvict来清除缓存,则可以保证缓存的数据是最新的

代码语言:javascript
复制
@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否决缓存条件

代码语言:javascript
复制
@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 类似,但会把方法的返回值放入缓存中, 主要用于数据新增和修改方法。

代码语言:javascript
复制
@CachePut(value = "user", key = "#user.id") 
public User save(User user) { 
users.add(user); 
return user; 
} 

@CacheEvict 方法执行成功后会从缓存中移除相应数据。 参数: value缓存名、 key缓存键值、 condition满足缓存条件、 unless否决缓存条件、 allEntries是否移除所有数据(设置为true时会移除所有缓存)

代码语言:javascript
复制
@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(); 
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-04-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 Redis
腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档