新手从零基础建站初级网站建设,东莞网络推广外包公司,大宗商品报价平台,wordpress 小说1、介绍#xff1a; Spring Cache 是一个框架#xff0c;实现了基于注解的缓存功能#xff0c;只需要简单加个注解#xff0c;就能实现缓存功能。它提供了一层抽象#xff0c;底层可以切换不同的cache实现。具体就是通过CacheManager 接口来实现不同的缓存技术。 针对不同…1、介绍 Spring Cache 是一个框架实现了基于注解的缓存功能只需要简单加个注解就能实现缓存功能。它提供了一层抽象底层可以切换不同的cache实现。具体就是通过CacheManager 接口来实现不同的缓存技术。 针对不同的混存技术需要实现不同的CacheManager:
CacheManager描述EhCacheCacheManager使用EhCache作为缓存技术GuavaCacheManager使用Google的GuavaCache作为缓存技术RedisCacheManager使用Redis作为缓存技术
2、Spring Cache常用注解
注解说明EnableCaching开启缓存注解功能Cacheable在方法执行前spring先查看缓存中是否有数据如果有数据则直接返回缓存数据若没有数据调用方法并将方法返回值放到缓存中CachePut将方法的返回值放到缓存中CacheEvict将一条或者多条数据从缓存中删除
在spring boot项目中使用缓存技术只需要导入相关缓存技术的依赖包并在启动类上使用EnableCaching开启缓存支持即可。例如使用Redis作为缓存技术只需要导入Spring Data Redis的maven坐标即可。
比如此处CachePut使用例子
CachePut(value name,key #result.id)//将方法返回值放入缓存 SpEL方法格式获得数据
publie User save(User user){userService.save(user);return user;}//此处value就是缓存的名称每个缓存下面可以有多个key//key:缓存的key//清理指定缓存
CacheEvict(value userCache,key #p0)//或者
CacheEvict(value userCache,key #root.args[0])
CacheEvict(value userCache,key #id)
DeleteMapping(/{id})
public void delete(PathVariable Long id) {userService.removeById(id);}Cacheable(value userCache ,key #id,condition #result ! null)
GetMapping(/{id})
public User getById(PathVariable Long id) {
User user userService.getById(id);
//此时有缓存则直接返回数据不会进入该方法
//当id查询为空时也会返回null数据当做缓存此时需要加Cacheable中方法condition条件,返回值不为空时加入缓存
//(unless #result null),返回值为空时不缓存return user;
}GetMapping(/list)
Cacheable(value userCache,key #user.id _#user.name)
public ListUser list (User user) {LambdaQueryWrapper user queryWrapper new LambdaQueryWrapper();queryWrapper.eq(user.getId() ! null,User::getId,user.getId());queryWrapper.eq(user.getName() ! null,User::getName,user.getName());ListUser list userService.list(querryWrapper):return list;
}底层基于Map来实现的此时重启服务缓存都会消失下面使用Redis来做缓存技术配置文件需要配置redis的cache同时可配置缓存有效期time-to-live。
具体实现思路
1、导入Spring Cache 和 Redis 相关 maven坐标
2、在application.yml中配置缓存数据的过期时间
3、在启动类上加EnableCaching注解开启缓存注解功能
4、在查询方法上加入Cacheable注解
5、在修改保存方法上加入CacheEvict注解