自贡网站推广,常州模板建站哪家好,seo博客优化,有没有什么网站做卷子目录 一 什么是Spring Cache
二 Spring Cache 各注解作用 ①EnableCaching ②Cacheable ③CachePut ④CacheEvict
三实现步骤
①导入spring cache依赖和Redis依赖
②配置Redis连接信息
③在启动类上加上开启spring cache的注解
④ 在对应的方法上加上需要的注解 一 什么…目录 一 什么是Spring Cache
二 Spring Cache 各注解作用 ①EnableCaching ②Cacheable ③CachePut ④CacheEvict
三实现步骤
①导入spring cache依赖和Redis依赖
②配置Redis连接信息
③在启动类上加上开启spring cache的注解
④ 在对应的方法上加上需要的注解 一 什么是Spring Cache spring cache是一个框架实现了基于注解的缓存功能只需要简单的加一个注解就能实现缓存功能。 而且spring cache提供了多种缓存的实现例如 ①EHCahe ②Caffeine ③Redis 想用那种缓存只需要导入对应的jar包即可。 本次我们使用Redis缓存作为用例。
二 Spring Cache 各注解作用 ①EnableCaching 开启缓存注解功能 通常加在启动类上。 ②Cacheable 在执行方法前先查询缓存中是否有数据如果有数据则直接返回缓存数据如果没有数据则调用方法并将方法返回值放到缓存中。 ③CachePut 将方法返回值放到缓存中 ④CacheEvict 将一条或者多条数据从缓存中删除 三实现步骤 ①导入spring cache依赖和Redis依赖 !-- spring cache缓存--dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-cache/artifactId/dependency
!-- 使用redis缓存--dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-redis/artifactId/dependency ②配置Redis连接信息 这是在yml文件中配置的 ③在启动类上加上开启spring cache的注解 SpringBootApplication
MapperScan(com.fs.mapper)
Slf4j
EnableCaching //开启springCache缓存
public class user_managementApplication {public static void main(String[] args) {SpringApplication.run(user_managementApplication.class , args);log.info(server is start...);}
} ④ 在对应的方法上加上需要的注解 例如我在下面这个新增用户的方法上需要把返回的用户存入缓存中去 PutMapping(/add)CachePut(cacheNames userCache , key #user.uid) //比如uid为3 那么得到存入redis的可以为“userCache::3”public Result addUser(RequestBody User user){log.info(进入新增用户:{},user);userService.addUser(user) ;return Result.success() ;} 这里需要注意一点因为我这个方法并没有返回用户对象返回的是一个Result 所以存储的也只是一个Result。 另外这个uid是主键回显的因为我这里插入使用的mp自带的所以mp会自己帮我把id回显我只需要从user中获取就行了如果你是用mybatis自己写的sql语句那么你需要自己设置主键回显可以在mapper接口层使用如下注解 Options(useGeneratedKeys true , keyProperty id) //把主键id映射到“id”返回Update(update tb_user set is_can_login0 where uid#{uid})void updateStatueByUid(Integer uid); 最后我们可以看见数据成功缓存到了redis并且key也是我们设置好的。 其他还有很多注解这里就不一一做示范了根据自己的需要使用不同注解即可。