@EnableCaching与@Cacheable的使用方法,结合redis进行说明
1、两者作用
首先说明这两个注解都是spring提供的,可以结合不同的缓存技术使用。
@EnableCaching是开启缓存功能,作用于缓存配置类上或者作用于springboot启动类上。
@Cacheable 注解在方法上,表示该方法的返回结果是可以缓存的。也就是说,该方法的返回结果会放在缓存中,以便于以后使用相同的参数调用该方法时,会返回缓存中的值,而不会实际执行该方法。如果缓存过期,则重新执行。
结合redis介绍如何使用
1、首先给出redis的配置类
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;import java.time.Duration;@Configuration
@EnableCaching
public class BootRedisConfig{@Beanpublic CacheManager cacheManager(RedisConnectionFactory factory){//Duration.ofSeconds(120)设置缓存默认过期时间120秒RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(120));//解决使用@Cacheable,redis数据库value乱码config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json()));RedisCacheManager cacheManager = RedisCacheManager.builder(factory).cacheDefaults(config).build();return cacheManager;}@Beanpublic RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();//连接redis服务器redisTemplate.setConnectionFactory(factory);//将redis默认序列化方式转换为json格式Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);//redisTemplate.setDefaultSerializer(jackson2JsonRedisSerializer);redisTemplate.setKeySerializer(new StringRedisSerializer());redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);return redisTemplate;}
}
2、准备个实体类:
@Data
public class Student implements Serializable {private String name;private int age;
}
3、做个简单测试:
@RestController
@RequestMapping("/cache")
public class CacheController { @GetMapping("/findById/{id}")@Cacheable("student00")public Student findById(@PathVariable("id")String id){Student student = new Student();student.setAge(23);student.setName("zhangsan");return student;}
}
执行findById,@Cacheable(“student00”)使返回结果缓存到redis(配置了redis),结果以key为student00::{传入参数id},value为返回的student对象。下次执行该方法时先根据id与student00拼串进行判断缓存中是否有对应的key,有的话直接返回结果。
定义多个缓存名,会存多份
@GetMapping("/findByIds/{id}")
@Cacheable({"student01","student02"})
public Student findByIds(@PathVariable("id")String id){Student student = new Student();student.setAge(25);student.setName("lisi");return student;
}
另外,默认的key拼串并不是很友好,调用的方法只有一个参数时,会自动使用@Cacheable(“student00”)中设置的student00 + :: + 传入参数;当多个参数时:
@GetMapping("/findById/{id}/{name}")
@Cacheable("student00")
public Student findById(@PathVariable("id")String id,@PathVariable("name")String name){Student student = new Student();student.setAge(23);student.setName("zhangsan");return student;
}
为了更直观,可以显式指定key,利用SpEL(Spring Expression Language,Spring 表达式语言)来动态拼接key:
@Cacheable(value = "student00",key = "'id-name:' + #id + '-' + #name")
此外,@Cacheable()中还可加入sync = true/false属性,
在一个多线程的环境中,某些操作可能被相同的参数并发地调用,这样同一个 value 值可能被多次计算(或多次访问 db),这样就达不到缓存的目的。针对这些可能高并发的操作,我们可以使用 sync 参数来告诉底层的缓存提供者将缓存的入口锁住,这样就只能有一个线程计算操作的结果值,而其它线程需要等待,这样就避免了 n-1 次数据库访问。
sync = true 可以有效的避免缓存击穿的问题。
另外还可加入缓存判断条件,对方法传入参数进行判断,满足条件则执行缓存查询;不满足条件则直接把该方法当作普通方法使用,不会进行缓存判断,也不会把结果放近缓存。
condition = “#id > 1” //只有id>1才走缓存
@EnableCaching与@Cacheable的使用方法,结合redis进行说明相关推荐
- 扩展基于注解的spring缓存,使缓存有效期的设置支持方法级别-redis篇
2019独角兽企业重金招聘Python工程师标准>>> 这里用的spring对redis的封装spring-data-redis,主要是对RedisCacheManager做一个二次 ...
- 项目总结--3(@Cacheable的使用方法和使用技巧)
在项目中缓存是经常要用到的,之前用的缓存都是Redis做为缓存的,但是在实际工作中用到缓存的地方是非常多,但是又不是只有Redis这一种操作,实际中可以用到的缓存还有SpringBoot,中的@Cac ...
- SpringBoot使用@Cacheable实现最简单的Redis缓存
前言 之前我们使用过RedisTemplate来实现redis缓存,然后使用工具类来实现操作redis的存储.这样的方式好处是很自由,但是还不是最简单的处理方式.对于一些简单的应用来说,其实redis ...
- @EnableCaching、@Cacheable、@CachePut、@CacheEvict、@Caching、@CacheConfig:缓存核心注解,用来实现缓存功能...
本文主要详解spring中缓存的使用. 背景 缓存大家都有了解过吧,主要用来提升系统查询速度. 比如电商中商品详情信息,这些信息通常不会经常变动但是会高频访问,我们可以将这些信息从db中拿出来放在缓存 ...
- php两个数组之间去重,php数组去重、魔术方法、redis常用数据结构及应用场景
一.用函数对数组进行去重的方法 1. arrau_unique函数的作用 移除数组中重复的值. 将值作为字符串进行排序,然后保留 每个值第一次 出现的健名,健名保留不变. 第二个参数可以选择排序方式: ...
- redis使用@Cacheable等注解为接口添加缓存
缓存处理方式应该是 先从缓存中拿数据,如果有,直接返回. 如果拿到的为空,则数据库查询,然后将查询结果存到缓存中. 由此实现方式应该如下: private String baseKey = " ...
- redis服务器信息统计,利用Redis统计网站在线活跃用户的方法
前言 在工作中我们经常遇到这样的需求,要对某个在线网站的活跃用户数量进行统计.这里我们以redis为例,说明一下其实现的过程. 实现方法 在Redis中存在bitmap这种数据类型,这种数据类型是建立 ...
- php session存到redis,php Session存储到Redis的方法
php Session存储到Redis的方法 当然要写先安装php的扩展,可参考这篇文章:Redis及PHP扩展安装修改php.ini的设置 复制代码 代码如下: session.save_handl ...
- Redis 实现限流器的三种方法
方法一:基于Redis的setnx的操作 我们在使用Redis的分布式锁的时候,大家都知道是依靠了setnx的指令,在CAS(Compare and swap)的操作的时候,同时给指定的key设置了过 ...
最新文章
- tomcat集群 (自带Cluster集群)
- android Activity runOnUiThread() 方法使用
- Openstack 之 调整nova相关参数
- 原生js来实现对dom元素class的操作方法
- 关于计算机考试网上操作的题目及答案,《计算机基础考试题及答案》.doc
- python中出现UserWarning: libuv only supports millisecond timer resolution怎么解决
- AndroidStuido连接不上手机的解决方法
- 修改时无论改成什么,值总是默认为1
- java项目关联关系_Mybatis一对多关联关系映射实现过程解析
- 数据库更新DATE类型的时间
- lopatkin俄大神精简系统Windows 10 Pro 18362.10006 19H2 PreRelease x86-x64 ZH-CN MICRO
- 你想要的宏基因组-微生物组知识全在这(2021.3)
- n次独立重复试验暨伯努利试验
- CES2013前瞻:1080p屏幕手机集中爆发
- SqlServer 对象名无效的原因及解决方法
- <<人工智能导论>>上机--遗传算法求解函数最值
- Seq2Seq Attention模型
- Feature|微生物组学研究的机遇与挑战
- Python小工具:将对象转换为不可变类型并计算其哈希值
- 京东商城主图视频抓取的方法步骤