SpringCache

打印 上一主题 下一主题

主题 893|帖子 893|积分 2679

1、什么是SpringCache

Spring Cache 是一个框架,实现了基于注解的缓存功能,只需要简朴地加一个注解,就能实现缓存功能。
Spring Cache 提供了一层抽象,底层可以切换差别的缓存实现。


  • EHCache
  • Caffeine
  • Redis
我们不需要主动显式要求使用什么缓存实现。
比如我们要使用redis实现,只需要在项目中导入 redis的 Java客户端的依赖比如: SpringDataRedis。springcache会自动使用。
2、准备工作

在这里,将redis作为SpringCache的缓存实现。
2.1、添加redis起步依赖
  1. <dependency>
  2.   <groupId>org.springframework.boot</groupId>
  3.   <artifactId>spring-boot-starter-data-redis</artifactId>
  4. </dependency>
  5. <dependency>
  6.   <groupId>org.apache.commons</groupId>
  7.   <artifactId>commons-pool2</artifactId>
  8.   <version>2.11.1</version>
  9. </dependency>
复制代码
2.2、配置文件配置数据源

根据SpringBoot的版本差别,配置略有差别。
如果是SpringBoot 3.x
  1. spring:
  2.   data:
  3.     redis:
  4.       host: localhost
  5.       port: 6379
  6.       password: 123456
  7.       lettuce:
  8.         pool:
  9.           max-active: 8 # 最大连接数
  10.           max-idle: 8 #最大空闲数
  11.           min-idle: 0 # 最小空闲数
  12.           max-wait: 100 # 最大等待时间
复制代码
如果是SpringBoot 2.x
  1. spring:
  2.   redis:
  3.     host: 101.43.108.196
  4.     port: 6379
  5.     password: 123456
  6.     lettuce:
  7.       pool:
  8.         max-active: 8 # 最大连接数
  9.         max-idle: 8 #最大空闲数
  10.         min-idle: 0 # 最小空闲数
  11.         max-wait: 100 # 最大等待时间
复制代码
补充:
关于客户端的选择:
发起使用[Lettuce](https://lettuce.io/),而这也是Spring Data Redis默认使用的。因为它是基于 Netty 开辟,支持非阻塞式 IO,性能会更好。
2.3、配置类,配置redisTemplate对象,主要是设置 序列化器
  1. @Configuration
  2. @Slf4j
  3. public class RedisTemplateConfiguration {
  4.     @Bean
  5.     public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
  6.         RedisTemplate redisTemplate=new RedisTemplate();
  7.         //设置key的序列化器,默认为JdkSerializationRedisSerializer
  8.         redisTemplate.setKeySerializer(new StringRedisSerializer());
  9.         redisTemplate.setConnectionFactory(redisConnectionFactory);
  10.         return redisTemplate;
  11.     }
  12. }
复制代码
补充:redisTemplate的使用()
  1. @Autowired
  2. private RedisTemplate redisTemplate;
  3. Object name = redisTemplate.opsForValue().get("NAME");
复制代码
2.4、添加Spring Cache的依赖
  1. <dependency>
  2.   <groupId>org.springframework.boot</groupId>
  3.   <artifactId>spring-boot-starter-cache</artifactId>
  4. </dependency>
复制代码
3、常用注解


@EnableCaching

加在SpringBoot项目的启动类上。
@CachePut

@CachePut(cacheNames = "usercache", key = "#user.id")
cacheNames :用于作为缓存的键的天生规则的一部分。
key :也是作为键值对天生的规则,可以写死,也可以动态天生!!!
比如:@CachePut(cacheNames = "usercache", key = "1")在缓存中天生的key就是,usercache::1
但是,这样时写死的,key后面应该是动态绑定的。基本上有5种写法。
  1. @CachePut(cacheNames = "usercache", key = "#user.id")           //名为user的参数
  2. @CachePut(cacheNames = "usercache", key = "#result.id")                //#result是方法返回值
  3. @CachePut(cacheNames = "usercache", key = "#p0.id")                        //p0是第一个参数
  4. @CachePut(cacheNames = "usercache", key = "#a0.id")                        //a0也是第一个参数
  5. @CachePut(cacheNames = "usercache", key = "#root.args[0].id")        //也是第一个参数
  6. public User insert(@RequestBody User user){
  7.     springCacheUserMapper.insert(user);
  8.     return user;
  9. }
复制代码
@Cacheable

1、如果不需要动态天生 键值对 中的键,那么使用@Cacheable(value = "xxx")
比如: @Cacheable(value = "username")
这里的"username" 会作为redis数据库中的 key
2、如果需要使用 动态天生 键值对 中的键,则需要像下面一样使用。
@Cacheable(cacheNames = "usercache", key = "#id")
动态天生的键值对的键 usercache::#{id}。先去缓存中查这个key存不存在,不存在才会进行对应的方法体。而且在方法体实行完之后,将方法返回的数据存入缓存中。
@CacheEvict
  1. @CacheEvict(cacheNames = "usercache",key = "#id")                //删除某个键值对
  2. @CacheEvict(cacheNames = "usercache",allEntries = true) //表示删除usercache::下的所有的键值对
复制代码
4、实践

4.1、根据地址簿id查询,一条地址记录

在这个controller方法上添加注解,先查询缓存再查询数据库,而且支持存入数据库
  1. /**
  2. * @ description 根据id查询地址信息
  3. * @param id
  4. * @ return com.zyp.pojo.Result
  5. * @ author DELL
  6. */
  7. @GetMapping("/one")
  8. @Cacheable(cacheNames = "useraddress", key = "#id")
  9. public Result<AddressVo> selectById(Long id){
  10.     AddressVo res = addressService.selectById(id);
  11.     return Result.success(res);
  12. }
复制代码
如果id=1,天生的redis中的key 是 useraddress::1
4.2、当发生增、删、改,把缓存的数据删除
  1. /**
  2. * @ description 删除地址
  3. * @ param address
  4. * @ return com.zyp.pojo.Result
  5. * @ author DELL
  6. */
  7. @PostMapping("/del")
  8. @CacheEvict(cacheNames = "useraddress", allEntries = true)
  9. public Result delete(@RequestBody Address address){
  10.     Long id = address.getId();
  11.     addressService.delete(id);
  12.     return Result.success();
  13. }
复制代码
这里举删除的例子,会把useraddress::下的所有的键值对删除。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

杀鸡焉用牛刀

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表